Audio plugin host https://kx.studio/carla
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.

1250 lines
41KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  18. : sampleRate (0),
  19. bufferSize (0),
  20. useDefaultInputChannels (true),
  21. useDefaultOutputChannels (true)
  22. {
  23. }
  24. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  25. {
  26. return outputDeviceName == other.outputDeviceName
  27. && inputDeviceName == other.inputDeviceName
  28. && sampleRate == other.sampleRate
  29. && bufferSize == other.bufferSize
  30. && inputChannels == other.inputChannels
  31. && useDefaultInputChannels == other.useDefaultInputChannels
  32. && outputChannels == other.outputChannels
  33. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  34. }
  35. //==============================================================================
  36. class AudioDeviceManager::CallbackHandler : public AudioIODeviceCallback,
  37. public MidiInputCallback,
  38. public AudioIODeviceType::Listener
  39. {
  40. public:
  41. CallbackHandler (AudioDeviceManager& adm) noexcept : owner (adm) {}
  42. private:
  43. void audioDeviceIOCallback (const float** ins, int numIns, float** outs, int numOuts, int numSamples) override
  44. {
  45. owner.audioDeviceIOCallbackInt (ins, numIns, outs, numOuts, numSamples);
  46. }
  47. void audioDeviceAboutToStart (AudioIODevice* device) override
  48. {
  49. owner.audioDeviceAboutToStartInt (device);
  50. }
  51. void audioDeviceStopped() override
  52. {
  53. owner.audioDeviceStoppedInt();
  54. }
  55. void audioDeviceError (const String& message) override
  56. {
  57. owner.audioDeviceErrorInt (message);
  58. }
  59. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message) override
  60. {
  61. owner.handleIncomingMidiMessageInt (source, message);
  62. }
  63. void audioDeviceListChanged() override
  64. {
  65. owner.audioDeviceListChanged();
  66. }
  67. AudioDeviceManager& owner;
  68. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CallbackHandler)
  69. };
  70. //==============================================================================
  71. AudioDeviceManager::AudioDeviceManager()
  72. : numInputChansNeeded (0),
  73. numOutputChansNeeded (2),
  74. listNeedsScanning (true),
  75. inputLevel (0),
  76. cpuUsageMs (0),
  77. timeToCpuScale (0)
  78. {
  79. callbackHandler = new CallbackHandler (*this);
  80. }
  81. AudioDeviceManager::~AudioDeviceManager()
  82. {
  83. currentAudioDevice = nullptr;
  84. defaultMidiOutput = nullptr;
  85. }
  86. //==============================================================================
  87. void AudioDeviceManager::createDeviceTypesIfNeeded()
  88. {
  89. if (availableDeviceTypes.size() == 0)
  90. {
  91. OwnedArray<AudioIODeviceType> types;
  92. createAudioDeviceTypes (types);
  93. for (int i = 0; i < types.size(); ++i)
  94. addAudioDeviceType (types.getUnchecked(i));
  95. types.clear (false);
  96. if (AudioIODeviceType* first = availableDeviceTypes.getFirst())
  97. currentDeviceType = first->getTypeName();
  98. }
  99. }
  100. const OwnedArray<AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  101. {
  102. scanDevicesIfNeeded();
  103. return availableDeviceTypes;
  104. }
  105. void AudioDeviceManager::audioDeviceListChanged()
  106. {
  107. if (currentAudioDevice != nullptr)
  108. {
  109. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  110. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  111. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  112. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  113. }
  114. sendChangeMessage();
  115. }
  116. //==============================================================================
  117. static void addIfNotNull (OwnedArray<AudioIODeviceType>& list, AudioIODeviceType* const device)
  118. {
  119. if (device != nullptr)
  120. list.add (device);
  121. }
  122. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray<AudioIODeviceType>& list)
  123. {
  124. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI (false));
  125. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI (true));
  126. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_DirectSound());
  127. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ASIO());
  128. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_CoreAudio());
  129. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_iOSAudio());
  130. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_JACK());
  131. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ALSA());
  132. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_OpenSLES());
  133. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Android());
  134. }
  135. void AudioDeviceManager::addAudioDeviceType (AudioIODeviceType* newDeviceType)
  136. {
  137. if (newDeviceType != nullptr)
  138. {
  139. jassert (lastDeviceTypeConfigs.size() == availableDeviceTypes.size());
  140. availableDeviceTypes.add (newDeviceType);
  141. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  142. newDeviceType->addListener (callbackHandler);
  143. }
  144. }
  145. static bool deviceListContains (AudioIODeviceType* type, bool isInput, const String& name)
  146. {
  147. StringArray devices (type->getDeviceNames (isInput));
  148. for (int i = devices.size(); --i >= 0;)
  149. if (devices[i].trim().equalsIgnoreCase (name.trim()))
  150. return true;
  151. return false;
  152. }
  153. //==============================================================================
  154. String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  155. const int numOutputChannelsNeeded,
  156. const XmlElement* const xml,
  157. const bool selectDefaultDeviceOnFailure,
  158. const String& preferredDefaultDeviceName,
  159. const AudioDeviceSetup* preferredSetupOptions)
  160. {
  161. scanDevicesIfNeeded();
  162. numInputChansNeeded = numInputChannelsNeeded;
  163. numOutputChansNeeded = numOutputChannelsNeeded;
  164. if (xml != nullptr && xml->hasTagName ("DEVICESETUP"))
  165. return initialiseFromXML (*xml, selectDefaultDeviceOnFailure,
  166. preferredDefaultDeviceName, preferredSetupOptions);
  167. return initialiseDefault (preferredDefaultDeviceName, preferredSetupOptions);
  168. }
  169. String AudioDeviceManager::initialiseDefault (const String& preferredDefaultDeviceName,
  170. const AudioDeviceSetup* preferredSetupOptions)
  171. {
  172. AudioDeviceSetup setup;
  173. if (preferredSetupOptions != nullptr)
  174. {
  175. setup = *preferredSetupOptions;
  176. }
  177. else if (preferredDefaultDeviceName.isNotEmpty())
  178. {
  179. for (int j = availableDeviceTypes.size(); --j >= 0;)
  180. {
  181. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  182. const StringArray outs (type->getDeviceNames (false));
  183. for (int i = 0; i < outs.size(); ++i)
  184. {
  185. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  186. {
  187. setup.outputDeviceName = outs[i];
  188. break;
  189. }
  190. }
  191. const StringArray ins (type->getDeviceNames (true));
  192. for (int i = 0; i < ins.size(); ++i)
  193. {
  194. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  195. {
  196. setup.inputDeviceName = ins[i];
  197. break;
  198. }
  199. }
  200. }
  201. }
  202. insertDefaultDeviceNames (setup);
  203. return setAudioDeviceSetup (setup, false);
  204. }
  205. String AudioDeviceManager::initialiseFromXML (const XmlElement& xml,
  206. const bool selectDefaultDeviceOnFailure,
  207. const String& preferredDefaultDeviceName,
  208. const AudioDeviceSetup* preferredSetupOptions)
  209. {
  210. lastExplicitSettings = new XmlElement (xml);
  211. String error;
  212. AudioDeviceSetup setup;
  213. if (preferredSetupOptions != nullptr)
  214. setup = *preferredSetupOptions;
  215. if (xml.getStringAttribute ("audioDeviceName").isNotEmpty())
  216. {
  217. setup.inputDeviceName = setup.outputDeviceName
  218. = xml.getStringAttribute ("audioDeviceName");
  219. }
  220. else
  221. {
  222. setup.inputDeviceName = xml.getStringAttribute ("audioInputDeviceName");
  223. setup.outputDeviceName = xml.getStringAttribute ("audioOutputDeviceName");
  224. }
  225. currentDeviceType = xml.getStringAttribute ("deviceType");
  226. if (findType (currentDeviceType) == nullptr)
  227. {
  228. if (AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName))
  229. currentDeviceType = type->getTypeName();
  230. else if (availableDeviceTypes.size() > 0)
  231. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  232. }
  233. setup.bufferSize = xml.getIntAttribute ("audioDeviceBufferSize");
  234. setup.sampleRate = xml.getDoubleAttribute ("audioDeviceRate");
  235. setup.inputChannels .parseString (xml.getStringAttribute ("audioDeviceInChans", "11"), 2);
  236. setup.outputChannels.parseString (xml.getStringAttribute ("audioDeviceOutChans", "11"), 2);
  237. setup.useDefaultInputChannels = ! xml.hasAttribute ("audioDeviceInChans");
  238. setup.useDefaultOutputChannels = ! xml.hasAttribute ("audioDeviceOutChans");
  239. error = setAudioDeviceSetup (setup, true);
  240. midiInsFromXml.clear();
  241. forEachXmlChildElementWithTagName (xml, c, "MIDIINPUT")
  242. midiInsFromXml.add (c->getStringAttribute ("name"));
  243. const StringArray allMidiIns (MidiInput::getDevices());
  244. for (int i = allMidiIns.size(); --i >= 0;)
  245. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  246. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  247. error = initialise (numInputChansNeeded, numOutputChansNeeded,
  248. nullptr, false, preferredDefaultDeviceName);
  249. setDefaultMidiOutput (xml.getStringAttribute ("defaultMidiOutput"));
  250. return error;
  251. }
  252. String AudioDeviceManager::initialiseWithDefaultDevices (int numInputChannelsNeeded,
  253. int numOutputChannelsNeeded)
  254. {
  255. lastExplicitSettings = nullptr;
  256. return initialise (numInputChannelsNeeded, numOutputChannelsNeeded,
  257. nullptr, false, String(), nullptr);
  258. }
  259. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  260. {
  261. if (AudioIODeviceType* type = getCurrentDeviceTypeObject())
  262. {
  263. if (setup.outputDeviceName.isEmpty())
  264. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  265. if (setup.inputDeviceName.isEmpty())
  266. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  267. }
  268. }
  269. XmlElement* AudioDeviceManager::createStateXml() const
  270. {
  271. return lastExplicitSettings.createCopy();
  272. }
  273. //==============================================================================
  274. void AudioDeviceManager::scanDevicesIfNeeded()
  275. {
  276. if (listNeedsScanning)
  277. {
  278. listNeedsScanning = false;
  279. createDeviceTypesIfNeeded();
  280. for (int i = availableDeviceTypes.size(); --i >= 0;)
  281. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  282. }
  283. }
  284. AudioIODeviceType* AudioDeviceManager::findType (const String& typeName)
  285. {
  286. scanDevicesIfNeeded();
  287. for (int i = availableDeviceTypes.size(); --i >= 0;)
  288. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == typeName)
  289. return availableDeviceTypes.getUnchecked(i);
  290. return nullptr;
  291. }
  292. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  293. {
  294. scanDevicesIfNeeded();
  295. for (int i = availableDeviceTypes.size(); --i >= 0;)
  296. {
  297. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  298. if ((inputName.isNotEmpty() && deviceListContains (type, true, inputName))
  299. || (outputName.isNotEmpty() && deviceListContains (type, false, outputName)))
  300. {
  301. return type;
  302. }
  303. }
  304. return nullptr;
  305. }
  306. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  307. {
  308. setup = currentSetup;
  309. }
  310. void AudioDeviceManager::deleteCurrentDevice()
  311. {
  312. currentAudioDevice = nullptr;
  313. currentSetup.inputDeviceName.clear();
  314. currentSetup.outputDeviceName.clear();
  315. }
  316. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  317. const bool treatAsChosenDevice)
  318. {
  319. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  320. {
  321. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  322. && currentDeviceType != type)
  323. {
  324. if (currentAudioDevice != nullptr)
  325. {
  326. closeAudioDevice();
  327. Thread::sleep (1500); // allow a moment for OS devices to sort themselves out, to help
  328. // avoid things like DirectSound/ASIO clashes
  329. }
  330. currentDeviceType = type;
  331. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  332. insertDefaultDeviceNames (s);
  333. setAudioDeviceSetup (s, treatAsChosenDevice);
  334. sendChangeMessage();
  335. break;
  336. }
  337. }
  338. }
  339. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  340. {
  341. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  342. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == currentDeviceType)
  343. return availableDeviceTypes.getUnchecked(i);
  344. return availableDeviceTypes[0];
  345. }
  346. String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  347. const bool treatAsChosenDevice)
  348. {
  349. jassert (&newSetup != &currentSetup); // this will have no effect
  350. if (newSetup == currentSetup && currentAudioDevice != nullptr)
  351. return String();
  352. if (! (newSetup == currentSetup))
  353. sendChangeMessage();
  354. stopDevice();
  355. const String newInputDeviceName (numInputChansNeeded == 0 ? String() : newSetup.inputDeviceName);
  356. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String() : newSetup.outputDeviceName);
  357. String error;
  358. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  359. if (type == nullptr || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  360. {
  361. deleteCurrentDevice();
  362. if (treatAsChosenDevice)
  363. updateXml();
  364. return String();
  365. }
  366. if (currentSetup.inputDeviceName != newInputDeviceName
  367. || currentSetup.outputDeviceName != newOutputDeviceName
  368. || currentAudioDevice == nullptr)
  369. {
  370. deleteCurrentDevice();
  371. scanDevicesIfNeeded();
  372. if (newOutputDeviceName.isNotEmpty() && ! deviceListContains (type, false, newOutputDeviceName))
  373. return "No such device: " + newOutputDeviceName;
  374. if (newInputDeviceName.isNotEmpty() && ! deviceListContains (type, true, newInputDeviceName))
  375. return "No such device: " + newInputDeviceName;
  376. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  377. if (currentAudioDevice == nullptr)
  378. error = "Can't open the audio device!\n\n"
  379. "This may be because another application is currently using the same device - "
  380. "if so, you should close any other applications and try again!";
  381. else
  382. error = currentAudioDevice->getLastError();
  383. if (error.isNotEmpty())
  384. {
  385. deleteCurrentDevice();
  386. return error;
  387. }
  388. if (newSetup.useDefaultInputChannels)
  389. {
  390. inputChannels.clear();
  391. inputChannels.setRange (0, numInputChansNeeded, true);
  392. }
  393. if (newSetup.useDefaultOutputChannels)
  394. {
  395. outputChannels.clear();
  396. outputChannels.setRange (0, numOutputChansNeeded, true);
  397. }
  398. if (newInputDeviceName.isEmpty()) inputChannels.clear();
  399. if (newOutputDeviceName.isEmpty()) outputChannels.clear();
  400. }
  401. if (! newSetup.useDefaultInputChannels) inputChannels = newSetup.inputChannels;
  402. if (! newSetup.useDefaultOutputChannels) outputChannels = newSetup.outputChannels;
  403. currentSetup = newSetup;
  404. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  405. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  406. error = currentAudioDevice->open (inputChannels,
  407. outputChannels,
  408. currentSetup.sampleRate,
  409. currentSetup.bufferSize);
  410. if (error.isEmpty())
  411. {
  412. currentDeviceType = currentAudioDevice->getTypeName();
  413. currentAudioDevice->start (callbackHandler);
  414. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  415. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  416. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  417. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  418. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  419. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  420. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  421. if (treatAsChosenDevice)
  422. updateXml();
  423. }
  424. else
  425. {
  426. deleteCurrentDevice();
  427. }
  428. return error;
  429. }
  430. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  431. {
  432. jassert (currentAudioDevice != nullptr);
  433. const Array<double> rates (currentAudioDevice->getAvailableSampleRates());
  434. if (rate > 0 && rates.contains (rate))
  435. return rate;
  436. rate = currentAudioDevice->getCurrentSampleRate();
  437. if (rate > 0 && rates.contains (rate))
  438. return rate;
  439. double lowestAbove44 = 0.0;
  440. for (int i = rates.size(); --i >= 0;)
  441. {
  442. const double sr = rates[i];
  443. if (sr >= 44100.0 && (lowestAbove44 < 1.0 || sr < lowestAbove44))
  444. lowestAbove44 = sr;
  445. }
  446. if (lowestAbove44 > 0.0)
  447. return lowestAbove44;
  448. return rates[0];
  449. }
  450. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  451. {
  452. jassert (currentAudioDevice != nullptr);
  453. if (bufferSize > 0 && currentAudioDevice->getAvailableBufferSizes().contains (bufferSize))
  454. return bufferSize;
  455. return currentAudioDevice->getDefaultBufferSize();
  456. }
  457. void AudioDeviceManager::stopDevice()
  458. {
  459. if (currentAudioDevice != nullptr)
  460. currentAudioDevice->stop();
  461. }
  462. void AudioDeviceManager::closeAudioDevice()
  463. {
  464. stopDevice();
  465. currentAudioDevice = nullptr;
  466. }
  467. void AudioDeviceManager::restartLastAudioDevice()
  468. {
  469. if (currentAudioDevice == nullptr)
  470. {
  471. if (currentSetup.inputDeviceName.isEmpty()
  472. && currentSetup.outputDeviceName.isEmpty())
  473. {
  474. // This method will only reload the last device that was running
  475. // before closeAudioDevice() was called - you need to actually open
  476. // one first, with setAudioDevice().
  477. jassertfalse;
  478. return;
  479. }
  480. AudioDeviceSetup s (currentSetup);
  481. setAudioDeviceSetup (s, false);
  482. }
  483. }
  484. void AudioDeviceManager::updateXml()
  485. {
  486. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  487. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  488. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  489. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  490. if (currentAudioDevice != nullptr)
  491. {
  492. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  493. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  494. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  495. if (! currentSetup.useDefaultInputChannels)
  496. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  497. if (! currentSetup.useDefaultOutputChannels)
  498. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  499. }
  500. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  501. lastExplicitSettings->createNewChildElement ("MIDIINPUT")
  502. ->setAttribute ("name", enabledMidiInputs[i]->getName());
  503. if (midiInsFromXml.size() > 0)
  504. {
  505. // Add any midi devices that have been enabled before, but which aren't currently
  506. // open because the device has been disconnected.
  507. const StringArray availableMidiDevices (MidiInput::getDevices());
  508. for (int i = 0; i < midiInsFromXml.size(); ++i)
  509. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  510. lastExplicitSettings->createNewChildElement ("MIDIINPUT")
  511. ->setAttribute ("name", midiInsFromXml[i]);
  512. }
  513. if (defaultMidiOutputName.isNotEmpty())
  514. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  515. }
  516. //==============================================================================
  517. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  518. {
  519. {
  520. const ScopedLock sl (audioCallbackLock);
  521. if (callbacks.contains (newCallback))
  522. return;
  523. }
  524. if (currentAudioDevice != nullptr && newCallback != nullptr)
  525. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  526. const ScopedLock sl (audioCallbackLock);
  527. callbacks.add (newCallback);
  528. }
  529. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  530. {
  531. if (callbackToRemove != nullptr)
  532. {
  533. bool needsDeinitialising = currentAudioDevice != nullptr;
  534. {
  535. const ScopedLock sl (audioCallbackLock);
  536. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  537. callbacks.removeFirstMatchingValue (callbackToRemove);
  538. }
  539. if (needsDeinitialising)
  540. callbackToRemove->audioDeviceStopped();
  541. }
  542. }
  543. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  544. int numInputChannels,
  545. float** outputChannelData,
  546. int numOutputChannels,
  547. int numSamples)
  548. {
  549. const ScopedLock sl (audioCallbackLock);
  550. if (inputLevelMeasurementEnabledCount.get() > 0 && numInputChannels > 0)
  551. {
  552. for (int j = 0; j < numSamples; ++j)
  553. {
  554. float s = 0;
  555. for (int i = 0; i < numInputChannels; ++i)
  556. s += std::abs (inputChannelData[i][j]);
  557. s /= numInputChannels;
  558. const double decayFactor = 0.99992;
  559. if (s > inputLevel)
  560. inputLevel = s;
  561. else if (inputLevel > 0.001f)
  562. inputLevel *= decayFactor;
  563. else
  564. inputLevel = 0;
  565. }
  566. }
  567. else
  568. {
  569. inputLevel = 0;
  570. }
  571. if (callbacks.size() > 0)
  572. {
  573. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  574. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  575. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  576. outputChannelData, numOutputChannels, numSamples);
  577. float** const tempChans = tempBuffer.getArrayOfWritePointers();
  578. for (int i = callbacks.size(); --i > 0;)
  579. {
  580. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  581. tempChans, numOutputChannels, numSamples);
  582. for (int chan = 0; chan < numOutputChannels; ++chan)
  583. {
  584. if (const float* const src = tempChans [chan])
  585. if (float* const dst = outputChannelData [chan])
  586. for (int j = 0; j < numSamples; ++j)
  587. dst[j] += src[j];
  588. }
  589. }
  590. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  591. const double filterAmount = 0.2;
  592. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  593. }
  594. else
  595. {
  596. for (int i = 0; i < numOutputChannels; ++i)
  597. zeromem (outputChannelData[i], sizeof (float) * (size_t) numSamples);
  598. }
  599. }
  600. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  601. {
  602. cpuUsageMs = 0;
  603. const double sampleRate = device->getCurrentSampleRate();
  604. const int blockSize = device->getCurrentBufferSizeSamples();
  605. if (sampleRate > 0.0 && blockSize > 0)
  606. {
  607. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  608. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  609. }
  610. {
  611. const ScopedLock sl (audioCallbackLock);
  612. for (int i = callbacks.size(); --i >= 0;)
  613. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  614. }
  615. sendChangeMessage();
  616. }
  617. void AudioDeviceManager::audioDeviceStoppedInt()
  618. {
  619. cpuUsageMs = 0;
  620. timeToCpuScale = 0;
  621. sendChangeMessage();
  622. const ScopedLock sl (audioCallbackLock);
  623. for (int i = callbacks.size(); --i >= 0;)
  624. callbacks.getUnchecked(i)->audioDeviceStopped();
  625. }
  626. void AudioDeviceManager::audioDeviceErrorInt (const String& message)
  627. {
  628. const ScopedLock sl (audioCallbackLock);
  629. for (int i = callbacks.size(); --i >= 0;)
  630. callbacks.getUnchecked(i)->audioDeviceError (message);
  631. }
  632. double AudioDeviceManager::getCpuUsage() const
  633. {
  634. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  635. }
  636. //==============================================================================
  637. void AudioDeviceManager::setMidiInputEnabled (const String& name, const bool enabled)
  638. {
  639. if (enabled != isMidiInputEnabled (name))
  640. {
  641. if (enabled)
  642. {
  643. const int index = MidiInput::getDevices().indexOf (name);
  644. if (index >= 0)
  645. {
  646. if (MidiInput* const midiIn = MidiInput::openDevice (index, callbackHandler))
  647. {
  648. enabledMidiInputs.add (midiIn);
  649. midiIn->start();
  650. }
  651. }
  652. }
  653. else
  654. {
  655. for (int i = enabledMidiInputs.size(); --i >= 0;)
  656. if (enabledMidiInputs[i]->getName() == name)
  657. enabledMidiInputs.remove (i);
  658. }
  659. updateXml();
  660. sendChangeMessage();
  661. }
  662. }
  663. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  664. {
  665. for (int i = enabledMidiInputs.size(); --i >= 0;)
  666. if (enabledMidiInputs[i]->getName() == name)
  667. return true;
  668. return false;
  669. }
  670. void AudioDeviceManager::addMidiInputCallback (const String& name, MidiInputCallback* callbackToAdd)
  671. {
  672. removeMidiInputCallback (name, callbackToAdd);
  673. if (name.isEmpty() || isMidiInputEnabled (name))
  674. {
  675. const ScopedLock sl (midiCallbackLock);
  676. MidiCallbackInfo mc;
  677. mc.deviceName = name;
  678. mc.callback = callbackToAdd;
  679. midiCallbacks.add (mc);
  680. }
  681. }
  682. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callbackToRemove)
  683. {
  684. for (int i = midiCallbacks.size(); --i >= 0;)
  685. {
  686. const MidiCallbackInfo& mc = midiCallbacks.getReference(i);
  687. if (mc.callback == callbackToRemove && mc.deviceName == name)
  688. {
  689. const ScopedLock sl (midiCallbackLock);
  690. midiCallbacks.remove (i);
  691. }
  692. }
  693. }
  694. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message)
  695. {
  696. if (! message.isActiveSense())
  697. {
  698. const ScopedLock sl (midiCallbackLock);
  699. for (int i = 0; i < midiCallbacks.size(); ++i)
  700. {
  701. const MidiCallbackInfo& mc = midiCallbacks.getReference(i);
  702. if (mc.deviceName.isEmpty() || mc.deviceName == source->getName())
  703. mc.callback->handleIncomingMidiMessage (source, message);
  704. }
  705. }
  706. }
  707. //==============================================================================
  708. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  709. {
  710. if (defaultMidiOutputName != deviceName)
  711. {
  712. Array<AudioIODeviceCallback*> oldCallbacks;
  713. {
  714. const ScopedLock sl (audioCallbackLock);
  715. oldCallbacks.swapWith (callbacks);
  716. }
  717. if (currentAudioDevice != nullptr)
  718. for (int i = oldCallbacks.size(); --i >= 0;)
  719. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  720. defaultMidiOutput = nullptr;
  721. defaultMidiOutputName = deviceName;
  722. if (deviceName.isNotEmpty())
  723. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  724. if (currentAudioDevice != nullptr)
  725. for (int i = oldCallbacks.size(); --i >= 0;)
  726. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  727. {
  728. const ScopedLock sl (audioCallbackLock);
  729. oldCallbacks.swapWith (callbacks);
  730. }
  731. updateXml();
  732. sendChangeMessage();
  733. }
  734. }
  735. //==============================================================================
  736. // This is an AudioTransportSource which will own it's assigned source
  737. class AudioSourceOwningTransportSource : public AudioTransportSource
  738. {
  739. public:
  740. AudioSourceOwningTransportSource() {}
  741. ~AudioSourceOwningTransportSource() { setSource (nullptr); }
  742. void setSource (PositionableAudioSource* newSource)
  743. {
  744. if (src != newSource)
  745. {
  746. ScopedPointer<PositionableAudioSource> oldSourceDeleter (src);
  747. src = newSource;
  748. // tell the base class about the new source before deleting the old one
  749. AudioTransportSource::setSource (newSource);
  750. }
  751. }
  752. private:
  753. ScopedPointer<PositionableAudioSource> src;
  754. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSourceOwningTransportSource)
  755. };
  756. //==============================================================================
  757. // An Audio player which will remove itself from the AudioDeviceManager's
  758. // callback list once it finishes playing its source
  759. class AutoRemovingSourcePlayer : public AudioSourcePlayer,
  760. private ChangeListener
  761. {
  762. public:
  763. struct DeleteOnMessageThread : public CallbackMessage
  764. {
  765. DeleteOnMessageThread (AutoRemovingSourcePlayer* p) : parent (p) {}
  766. void messageCallback() override { delete parent; }
  767. AutoRemovingSourcePlayer* parent;
  768. };
  769. //==============================================================================
  770. AutoRemovingSourcePlayer (AudioDeviceManager& deviceManager, bool ownSource)
  771. : manager (deviceManager),
  772. deleteWhenDone (ownSource),
  773. hasAddedCallback (false),
  774. recursiveEntry (false)
  775. {
  776. }
  777. void changeListenerCallback (ChangeBroadcaster* newSource) override
  778. {
  779. if (AudioTransportSource* currentTransport
  780. = dynamic_cast<AudioTransportSource*> (getCurrentSource()))
  781. {
  782. ignoreUnused (newSource);
  783. jassert (newSource == currentTransport);
  784. if (! currentTransport->isPlaying())
  785. {
  786. // this will call audioDeviceStopped!
  787. manager.removeAudioCallback (this);
  788. }
  789. else if (! hasAddedCallback)
  790. {
  791. hasAddedCallback = true;
  792. manager.addAudioCallback (this);
  793. }
  794. }
  795. }
  796. void audioDeviceStopped() override
  797. {
  798. if (! recursiveEntry)
  799. {
  800. ScopedValueSetter<bool> s (recursiveEntry, true, false);
  801. manager.removeAudioCallback (this);
  802. AudioSourcePlayer::audioDeviceStopped();
  803. if (MessageManager* mm = MessageManager::getInstanceWithoutCreating())
  804. {
  805. if (mm->isThisTheMessageThread())
  806. delete this;
  807. else
  808. (new DeleteOnMessageThread (this))->post();
  809. }
  810. }
  811. }
  812. void setSource (AudioTransportSource* newSource)
  813. {
  814. AudioSource* oldSource = getCurrentSource();
  815. if (AudioTransportSource* oldTransport = dynamic_cast<AudioTransportSource*> (oldSource))
  816. oldTransport->removeChangeListener (this);
  817. if (newSource != nullptr)
  818. newSource->addChangeListener (this);
  819. AudioSourcePlayer::setSource (newSource);
  820. if (deleteWhenDone)
  821. delete oldSource;
  822. }
  823. private:
  824. // only allow myself to be deleted when my audio callback has been removed
  825. ~AutoRemovingSourcePlayer()
  826. {
  827. setSource (nullptr);
  828. }
  829. AudioDeviceManager& manager;
  830. bool deleteWhenDone, hasAddedCallback, recursiveEntry;
  831. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AutoRemovingSourcePlayer)
  832. };
  833. //==============================================================================
  834. // An AudioSource which simply outputs a buffer
  835. class AudioSampleBufferSource : public PositionableAudioSource
  836. {
  837. public:
  838. AudioSampleBufferSource (AudioSampleBuffer* audioBuffer, bool shouldLoop, bool ownBuffer)
  839. : position (0),
  840. buffer (audioBuffer),
  841. looping (shouldLoop),
  842. deleteWhenDone (ownBuffer)
  843. {}
  844. ~AudioSampleBufferSource()
  845. {
  846. if (deleteWhenDone)
  847. delete buffer;
  848. }
  849. //==============================================================================
  850. void setNextReadPosition (int64 newPosition) override
  851. {
  852. jassert (newPosition >= 0);
  853. if (looping)
  854. newPosition = newPosition % static_cast<int64> (buffer->getNumSamples());
  855. position = jmin (buffer->getNumSamples(), static_cast<int> (newPosition));
  856. }
  857. int64 getNextReadPosition() const override
  858. {
  859. return static_cast<int64> (position);
  860. }
  861. int64 getTotalLength() const override
  862. {
  863. return static_cast<int64> (buffer->getNumSamples());
  864. }
  865. bool isLooping() const override
  866. {
  867. return looping;
  868. }
  869. void setLooping (bool shouldLoop) override
  870. {
  871. looping = shouldLoop;
  872. }
  873. //==============================================================================
  874. void prepareToPlay (int samplesPerBlockExpected, double sampleRate) override
  875. {
  876. ignoreUnused (samplesPerBlockExpected, sampleRate);
  877. }
  878. void releaseResources() override
  879. {}
  880. void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override
  881. {
  882. int max = jmin (buffer->getNumSamples() - position, bufferToFill.numSamples);
  883. jassert (max >= 0);
  884. {
  885. int ch;
  886. int maxInChannels = buffer->getNumChannels();
  887. int maxOutChannels = jmin (bufferToFill.buffer->getNumChannels(),
  888. jmax (maxInChannels, 2));
  889. for (ch = 0; ch < maxOutChannels; ch++)
  890. {
  891. int inChannel = ch % maxInChannels;
  892. if (max > 0)
  893. bufferToFill.buffer->copyFrom (ch, bufferToFill.startSample, *buffer, inChannel, position, max);
  894. }
  895. for (; ch < bufferToFill.buffer->getNumChannels(); ++ch)
  896. bufferToFill.buffer->clear (ch, bufferToFill.startSample, bufferToFill.numSamples);
  897. }
  898. position += max;
  899. if (looping)
  900. position = position % buffer->getNumSamples();
  901. }
  902. private:
  903. //==============================================================================
  904. int position;
  905. AudioSampleBuffer* buffer;
  906. bool looping, deleteWhenDone;
  907. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioSampleBufferSource)
  908. };
  909. void AudioDeviceManager::playSound (const File& file)
  910. {
  911. if (file.existsAsFile())
  912. {
  913. AudioFormatManager formatManager;
  914. formatManager.registerBasicFormats();
  915. playSound (formatManager.createReaderFor (file), true);
  916. }
  917. }
  918. void AudioDeviceManager::playSound (const void* resourceData, size_t resourceSize)
  919. {
  920. if (resourceData != nullptr && resourceSize > 0)
  921. {
  922. AudioFormatManager formatManager;
  923. formatManager.registerBasicFormats();
  924. MemoryInputStream* mem = new MemoryInputStream (resourceData, resourceSize, false);
  925. playSound (formatManager.createReaderFor (mem), true);
  926. }
  927. }
  928. void AudioDeviceManager::playSound (AudioFormatReader* reader, bool deleteWhenFinished)
  929. {
  930. playSound (new AudioFormatReaderSource (reader, deleteWhenFinished), true);
  931. }
  932. void AudioDeviceManager::playSound (PositionableAudioSource* audioSource, bool deleteWhenFinished)
  933. {
  934. if (audioSource != nullptr && currentAudioDevice != nullptr)
  935. {
  936. if (AudioTransportSource* transport = dynamic_cast<AudioTransportSource*> (audioSource))
  937. {
  938. AutoRemovingSourcePlayer* player = new AutoRemovingSourcePlayer (*this, deleteWhenFinished);
  939. player->setSource (transport);
  940. }
  941. else
  942. {
  943. AudioTransportSource* transportSource;
  944. if (deleteWhenFinished)
  945. {
  946. AudioSourceOwningTransportSource* owningTransportSource = new AudioSourceOwningTransportSource();
  947. owningTransportSource->setSource (audioSource);
  948. transportSource = owningTransportSource;
  949. }
  950. else
  951. {
  952. transportSource = new AudioTransportSource;
  953. transportSource->setSource (audioSource);
  954. }
  955. // recursively call myself
  956. playSound (transportSource, true);
  957. transportSource->start();
  958. }
  959. }
  960. else
  961. {
  962. if (deleteWhenFinished)
  963. delete audioSource;
  964. }
  965. }
  966. void AudioDeviceManager::playSound (AudioSampleBuffer* buffer, bool deleteWhenFinished)
  967. {
  968. playSound (new AudioSampleBufferSource (buffer, false, deleteWhenFinished), true);
  969. }
  970. void AudioDeviceManager::playTestSound()
  971. {
  972. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  973. const int soundLength = (int) sampleRate;
  974. const double frequency = 440.0;
  975. const float amplitude = 0.5f;
  976. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  977. AudioSampleBuffer* newSound = new AudioSampleBuffer (1, soundLength);
  978. for (int i = 0; i < soundLength; ++i)
  979. newSound->setSample (0, i, amplitude * (float) std::sin (i * phasePerSample));
  980. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  981. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  982. playSound (newSound, true);
  983. }
  984. //==============================================================================
  985. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  986. {
  987. if (enableMeasurement)
  988. ++inputLevelMeasurementEnabledCount;
  989. else
  990. --inputLevelMeasurementEnabledCount;
  991. inputLevel = 0;
  992. }
  993. double AudioDeviceManager::getCurrentInputLevel() const
  994. {
  995. jassert (inputLevelMeasurementEnabledCount.get() > 0); // you need to call enableInputLevelMeasurement() before using this!
  996. return inputLevel;
  997. }