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.

967 lines
32KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software 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. useInputNames (false),
  76. inputLevel (0),
  77. testSoundPosition (0),
  78. tempBuffer (2, 2),
  79. cpuUsageMs (0),
  80. timeToCpuScale (0)
  81. {
  82. callbackHandler = new CallbackHandler (*this);
  83. }
  84. AudioDeviceManager::~AudioDeviceManager()
  85. {
  86. currentAudioDevice = nullptr;
  87. defaultMidiOutput = nullptr;
  88. }
  89. //==============================================================================
  90. void AudioDeviceManager::createDeviceTypesIfNeeded()
  91. {
  92. if (availableDeviceTypes.size() == 0)
  93. {
  94. OwnedArray <AudioIODeviceType> types;
  95. createAudioDeviceTypes (types);
  96. for (int i = 0; i < types.size(); ++i)
  97. addAudioDeviceType (types.getUnchecked(i));
  98. types.clear (false);
  99. if (AudioIODeviceType* first = availableDeviceTypes.getFirst())
  100. currentDeviceType = first->getTypeName();
  101. }
  102. }
  103. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  104. {
  105. scanDevicesIfNeeded();
  106. return availableDeviceTypes;
  107. }
  108. void AudioDeviceManager::audioDeviceListChanged()
  109. {
  110. if (currentAudioDevice != nullptr)
  111. {
  112. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  113. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  114. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  115. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  116. }
  117. sendChangeMessage();
  118. }
  119. //==============================================================================
  120. static void addIfNotNull (OwnedArray <AudioIODeviceType>& list, AudioIODeviceType* const device)
  121. {
  122. if (device != nullptr)
  123. list.add (device);
  124. }
  125. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  126. {
  127. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_WASAPI());
  128. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_DirectSound());
  129. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ASIO());
  130. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_CoreAudio());
  131. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_iOSAudio());
  132. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_JACK());
  133. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_ALSA());
  134. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_OpenSLES());
  135. addIfNotNull (list, AudioIODeviceType::createAudioIODeviceType_Android());
  136. }
  137. void AudioDeviceManager::addAudioDeviceType (AudioIODeviceType* newDeviceType)
  138. {
  139. if (newDeviceType != nullptr)
  140. {
  141. jassert (lastDeviceTypeConfigs.size() == availableDeviceTypes.size());
  142. availableDeviceTypes.add (newDeviceType);
  143. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  144. newDeviceType->addListener (callbackHandler);
  145. }
  146. }
  147. //==============================================================================
  148. String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  149. const int numOutputChannelsNeeded,
  150. const XmlElement* const e,
  151. const bool selectDefaultDeviceOnFailure,
  152. const String& preferredDefaultDeviceName,
  153. const AudioDeviceSetup* preferredSetupOptions)
  154. {
  155. scanDevicesIfNeeded();
  156. numInputChansNeeded = numInputChannelsNeeded;
  157. numOutputChansNeeded = numOutputChannelsNeeded;
  158. if (e != nullptr && e->hasTagName ("DEVICESETUP"))
  159. {
  160. lastExplicitSettings = new XmlElement (*e);
  161. String error;
  162. AudioDeviceSetup setup;
  163. if (preferredSetupOptions != nullptr)
  164. setup = *preferredSetupOptions;
  165. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  166. {
  167. setup.inputDeviceName = setup.outputDeviceName
  168. = e->getStringAttribute ("audioDeviceName");
  169. }
  170. else
  171. {
  172. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  173. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  174. }
  175. currentDeviceType = e->getStringAttribute ("deviceType");
  176. if (findType (currentDeviceType) == nullptr)
  177. {
  178. if (AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName))
  179. currentDeviceType = type->getTypeName();
  180. else if (availableDeviceTypes.size() > 0)
  181. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  182. }
  183. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  184. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  185. setup.inputChannels .parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  186. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  187. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  188. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  189. error = setAudioDeviceSetup (setup, true);
  190. midiInsFromXml.clear();
  191. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  192. midiInsFromXml.add (c->getStringAttribute ("name"));
  193. const StringArray allMidiIns (MidiInput::getDevices());
  194. for (int i = allMidiIns.size(); --i >= 0;)
  195. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  196. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  197. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  198. false, preferredDefaultDeviceName);
  199. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  200. return error;
  201. }
  202. else
  203. {
  204. AudioDeviceSetup setup;
  205. if (preferredSetupOptions != nullptr)
  206. {
  207. setup = *preferredSetupOptions;
  208. }
  209. else if (preferredDefaultDeviceName.isNotEmpty())
  210. {
  211. for (int j = availableDeviceTypes.size(); --j >= 0;)
  212. {
  213. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  214. const StringArray outs (type->getDeviceNames (false));
  215. for (int i = 0; i < outs.size(); ++i)
  216. {
  217. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  218. {
  219. setup.outputDeviceName = outs[i];
  220. break;
  221. }
  222. }
  223. const StringArray ins (type->getDeviceNames (true));
  224. for (int i = 0; i < ins.size(); ++i)
  225. {
  226. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  227. {
  228. setup.inputDeviceName = ins[i];
  229. break;
  230. }
  231. }
  232. }
  233. }
  234. insertDefaultDeviceNames (setup);
  235. return setAudioDeviceSetup (setup, false);
  236. }
  237. }
  238. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  239. {
  240. if (AudioIODeviceType* type = getCurrentDeviceTypeObject())
  241. {
  242. if (setup.outputDeviceName.isEmpty())
  243. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  244. if (setup.inputDeviceName.isEmpty())
  245. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  246. }
  247. }
  248. XmlElement* AudioDeviceManager::createStateXml() const
  249. {
  250. return lastExplicitSettings.createCopy();
  251. }
  252. //==============================================================================
  253. void AudioDeviceManager::scanDevicesIfNeeded()
  254. {
  255. if (listNeedsScanning)
  256. {
  257. listNeedsScanning = false;
  258. createDeviceTypesIfNeeded();
  259. for (int i = availableDeviceTypes.size(); --i >= 0;)
  260. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  261. }
  262. }
  263. AudioIODeviceType* AudioDeviceManager::findType (const String& typeName)
  264. {
  265. scanDevicesIfNeeded();
  266. for (int i = availableDeviceTypes.size(); --i >= 0;)
  267. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == typeName)
  268. return availableDeviceTypes.getUnchecked(i);
  269. return nullptr;
  270. }
  271. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  272. {
  273. scanDevicesIfNeeded();
  274. for (int i = availableDeviceTypes.size(); --i >= 0;)
  275. {
  276. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  277. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  278. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  279. {
  280. return type;
  281. }
  282. }
  283. return nullptr;
  284. }
  285. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  286. {
  287. setup = currentSetup;
  288. }
  289. void AudioDeviceManager::deleteCurrentDevice()
  290. {
  291. currentAudioDevice = nullptr;
  292. currentSetup.inputDeviceName.clear();
  293. currentSetup.outputDeviceName.clear();
  294. }
  295. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  296. const bool treatAsChosenDevice)
  297. {
  298. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  299. {
  300. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  301. && currentDeviceType != type)
  302. {
  303. if (currentAudioDevice != nullptr)
  304. {
  305. closeAudioDevice();
  306. Thread::sleep (1500); // allow a moment for OS devices to sort themselves out, to help
  307. // avoid things like DirectSound/ASIO clashes
  308. }
  309. currentDeviceType = type;
  310. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  311. insertDefaultDeviceNames (s);
  312. setAudioDeviceSetup (s, treatAsChosenDevice);
  313. sendChangeMessage();
  314. break;
  315. }
  316. }
  317. }
  318. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  319. {
  320. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  321. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == currentDeviceType)
  322. return availableDeviceTypes.getUnchecked(i);
  323. return availableDeviceTypes[0];
  324. }
  325. String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  326. const bool treatAsChosenDevice)
  327. {
  328. jassert (&newSetup != &currentSetup); // this will have no effect
  329. if (newSetup == currentSetup && currentAudioDevice != nullptr)
  330. return String();
  331. if (! (newSetup == currentSetup))
  332. sendChangeMessage();
  333. stopDevice();
  334. const String newInputDeviceName (numInputChansNeeded == 0 ? String() : newSetup.inputDeviceName);
  335. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String() : newSetup.outputDeviceName);
  336. String error;
  337. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  338. if (type == nullptr || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  339. {
  340. deleteCurrentDevice();
  341. if (treatAsChosenDevice)
  342. updateXml();
  343. return String();
  344. }
  345. if (currentSetup.inputDeviceName != newInputDeviceName
  346. || currentSetup.outputDeviceName != newOutputDeviceName
  347. || currentAudioDevice == nullptr)
  348. {
  349. deleteCurrentDevice();
  350. scanDevicesIfNeeded();
  351. if (newOutputDeviceName.isNotEmpty()
  352. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  353. {
  354. return "No such device: " + newOutputDeviceName;
  355. }
  356. if (newInputDeviceName.isNotEmpty()
  357. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  358. {
  359. return "No such device: " + newInputDeviceName;
  360. }
  361. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  362. if (currentAudioDevice == nullptr)
  363. error = "Can't open the audio device!\n\n"
  364. "This may be because another application is currently using the same device - "
  365. "if so, you should close any other applications and try again!";
  366. else
  367. error = currentAudioDevice->getLastError();
  368. if (error.isNotEmpty())
  369. {
  370. deleteCurrentDevice();
  371. return error;
  372. }
  373. if (newSetup.useDefaultInputChannels)
  374. {
  375. inputChannels.clear();
  376. inputChannels.setRange (0, numInputChansNeeded, true);
  377. }
  378. if (newSetup.useDefaultOutputChannels)
  379. {
  380. outputChannels.clear();
  381. outputChannels.setRange (0, numOutputChansNeeded, true);
  382. }
  383. if (newInputDeviceName.isEmpty()) inputChannels.clear();
  384. if (newOutputDeviceName.isEmpty()) outputChannels.clear();
  385. }
  386. if (! newSetup.useDefaultInputChannels) inputChannels = newSetup.inputChannels;
  387. if (! newSetup.useDefaultOutputChannels) outputChannels = newSetup.outputChannels;
  388. currentSetup = newSetup;
  389. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  390. currentSetup.bufferSize = chooseBestBufferSize (newSetup.bufferSize);
  391. error = currentAudioDevice->open (inputChannels,
  392. outputChannels,
  393. currentSetup.sampleRate,
  394. currentSetup.bufferSize);
  395. if (error.isEmpty())
  396. {
  397. currentDeviceType = currentAudioDevice->getTypeName();
  398. currentAudioDevice->start (callbackHandler);
  399. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  400. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  401. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  402. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  403. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  404. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  405. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  406. if (treatAsChosenDevice)
  407. updateXml();
  408. }
  409. else
  410. {
  411. deleteCurrentDevice();
  412. }
  413. return error;
  414. }
  415. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  416. {
  417. jassert (currentAudioDevice != nullptr);
  418. const Array<double> rates (currentAudioDevice->getAvailableSampleRates());
  419. if (rate > 0 && rates.contains (rate))
  420. return rate;
  421. double lowestAbove44 = 0.0;
  422. for (int i = rates.size(); --i >= 0;)
  423. {
  424. const double sr = rates[i];
  425. if (sr >= 44100.0 && (lowestAbove44 < 1.0 || sr < lowestAbove44))
  426. lowestAbove44 = sr;
  427. }
  428. if (lowestAbove44 > 0.0)
  429. return lowestAbove44;
  430. return rates[0];
  431. }
  432. int AudioDeviceManager::chooseBestBufferSize (int bufferSize) const
  433. {
  434. jassert (currentAudioDevice != nullptr);
  435. if (bufferSize > 0 && currentAudioDevice->getAvailableBufferSizes().contains (bufferSize))
  436. return bufferSize;
  437. return currentAudioDevice->getDefaultBufferSize();
  438. }
  439. void AudioDeviceManager::stopDevice()
  440. {
  441. if (currentAudioDevice != nullptr)
  442. currentAudioDevice->stop();
  443. testSound = nullptr;
  444. }
  445. void AudioDeviceManager::closeAudioDevice()
  446. {
  447. stopDevice();
  448. currentAudioDevice = nullptr;
  449. }
  450. void AudioDeviceManager::restartLastAudioDevice()
  451. {
  452. if (currentAudioDevice == nullptr)
  453. {
  454. if (currentSetup.inputDeviceName.isEmpty()
  455. && currentSetup.outputDeviceName.isEmpty())
  456. {
  457. // This method will only reload the last device that was running
  458. // before closeAudioDevice() was called - you need to actually open
  459. // one first, with setAudioDevice().
  460. jassertfalse;
  461. return;
  462. }
  463. AudioDeviceSetup s (currentSetup);
  464. setAudioDeviceSetup (s, false);
  465. }
  466. }
  467. void AudioDeviceManager::updateXml()
  468. {
  469. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  470. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  471. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  472. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  473. if (currentAudioDevice != nullptr)
  474. {
  475. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  476. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  477. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  478. if (! currentSetup.useDefaultInputChannels)
  479. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  480. if (! currentSetup.useDefaultOutputChannels)
  481. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  482. }
  483. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  484. lastExplicitSettings->createNewChildElement ("MIDIINPUT")
  485. ->setAttribute ("name", enabledMidiInputs[i]->getName());
  486. if (midiInsFromXml.size() > 0)
  487. {
  488. // Add any midi devices that have been enabled before, but which aren't currently
  489. // open because the device has been disconnected.
  490. const StringArray availableMidiDevices (MidiInput::getDevices());
  491. for (int i = 0; i < midiInsFromXml.size(); ++i)
  492. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  493. lastExplicitSettings->createNewChildElement ("MIDIINPUT")
  494. ->setAttribute ("name", midiInsFromXml[i]);
  495. }
  496. if (defaultMidiOutputName.isNotEmpty())
  497. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  498. }
  499. //==============================================================================
  500. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  501. {
  502. {
  503. const ScopedLock sl (audioCallbackLock);
  504. if (callbacks.contains (newCallback))
  505. return;
  506. }
  507. if (currentAudioDevice != nullptr && newCallback != nullptr)
  508. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  509. const ScopedLock sl (audioCallbackLock);
  510. callbacks.add (newCallback);
  511. }
  512. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callbackToRemove)
  513. {
  514. if (callbackToRemove != nullptr)
  515. {
  516. bool needsDeinitialising = currentAudioDevice != nullptr;
  517. {
  518. const ScopedLock sl (audioCallbackLock);
  519. needsDeinitialising = needsDeinitialising && callbacks.contains (callbackToRemove);
  520. callbacks.removeFirstMatchingValue (callbackToRemove);
  521. }
  522. if (needsDeinitialising)
  523. callbackToRemove->audioDeviceStopped();
  524. }
  525. }
  526. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  527. int numInputChannels,
  528. float** outputChannelData,
  529. int numOutputChannels,
  530. int numSamples)
  531. {
  532. const ScopedLock sl (audioCallbackLock);
  533. if (inputLevelMeasurementEnabledCount.get() > 0 && numInputChannels > 0)
  534. {
  535. for (int j = 0; j < numSamples; ++j)
  536. {
  537. float s = 0;
  538. for (int i = 0; i < numInputChannels; ++i)
  539. s += std::abs (inputChannelData[i][j]);
  540. s /= numInputChannels;
  541. const double decayFactor = 0.99992;
  542. if (s > inputLevel)
  543. inputLevel = s;
  544. else if (inputLevel > 0.001f)
  545. inputLevel *= decayFactor;
  546. else
  547. inputLevel = 0;
  548. }
  549. }
  550. else
  551. {
  552. inputLevel = 0;
  553. }
  554. if (callbacks.size() > 0)
  555. {
  556. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  557. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  558. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  559. outputChannelData, numOutputChannels, numSamples);
  560. float** const tempChans = tempBuffer.getArrayOfChannels();
  561. for (int i = callbacks.size(); --i > 0;)
  562. {
  563. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  564. tempChans, numOutputChannels, numSamples);
  565. for (int chan = 0; chan < numOutputChannels; ++chan)
  566. {
  567. if (const float* const src = tempChans [chan])
  568. if (float* const dst = outputChannelData [chan])
  569. for (int j = 0; j < numSamples; ++j)
  570. dst[j] += src[j];
  571. }
  572. }
  573. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  574. const double filterAmount = 0.2;
  575. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  576. }
  577. else
  578. {
  579. for (int i = 0; i < numOutputChannels; ++i)
  580. zeromem (outputChannelData[i], sizeof (float) * (size_t) numSamples);
  581. }
  582. if (testSound != nullptr)
  583. {
  584. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  585. const float* const src = testSound->getSampleData (0, testSoundPosition);
  586. for (int i = 0; i < numOutputChannels; ++i)
  587. for (int j = 0; j < numSamps; ++j)
  588. outputChannelData [i][j] += src[j];
  589. testSoundPosition += numSamps;
  590. if (testSoundPosition >= testSound->getNumSamples())
  591. testSound = nullptr;
  592. }
  593. }
  594. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  595. {
  596. cpuUsageMs = 0;
  597. const double sampleRate = device->getCurrentSampleRate();
  598. const int blockSize = device->getCurrentBufferSizeSamples();
  599. if (sampleRate > 0.0 && blockSize > 0)
  600. {
  601. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  602. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  603. }
  604. {
  605. const ScopedLock sl (audioCallbackLock);
  606. for (int i = callbacks.size(); --i >= 0;)
  607. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  608. }
  609. sendChangeMessage();
  610. }
  611. void AudioDeviceManager::audioDeviceStoppedInt()
  612. {
  613. cpuUsageMs = 0;
  614. timeToCpuScale = 0;
  615. sendChangeMessage();
  616. const ScopedLock sl (audioCallbackLock);
  617. for (int i = callbacks.size(); --i >= 0;)
  618. callbacks.getUnchecked(i)->audioDeviceStopped();
  619. }
  620. void AudioDeviceManager::audioDeviceErrorInt (const String& message)
  621. {
  622. const ScopedLock sl (audioCallbackLock);
  623. for (int i = callbacks.size(); --i >= 0;)
  624. callbacks.getUnchecked(i)->audioDeviceError (message);
  625. }
  626. double AudioDeviceManager::getCpuUsage() const
  627. {
  628. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  629. }
  630. //==============================================================================
  631. void AudioDeviceManager::setMidiInputEnabled (const String& name, const bool enabled)
  632. {
  633. if (enabled != isMidiInputEnabled (name))
  634. {
  635. if (enabled)
  636. {
  637. const int index = MidiInput::getDevices().indexOf (name);
  638. if (index >= 0)
  639. {
  640. if (MidiInput* const midiIn = MidiInput::openDevice (index, callbackHandler))
  641. {
  642. enabledMidiInputs.add (midiIn);
  643. midiIn->start();
  644. }
  645. }
  646. }
  647. else
  648. {
  649. for (int i = enabledMidiInputs.size(); --i >= 0;)
  650. if (enabledMidiInputs[i]->getName() == name)
  651. enabledMidiInputs.remove (i);
  652. }
  653. updateXml();
  654. sendChangeMessage();
  655. }
  656. }
  657. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  658. {
  659. for (int i = enabledMidiInputs.size(); --i >= 0;)
  660. if (enabledMidiInputs[i]->getName() == name)
  661. return true;
  662. return false;
  663. }
  664. void AudioDeviceManager::addMidiInputCallback (const String& name, MidiInputCallback* callbackToAdd)
  665. {
  666. removeMidiInputCallback (name, callbackToAdd);
  667. if (name.isEmpty() || isMidiInputEnabled (name))
  668. {
  669. const ScopedLock sl (midiCallbackLock);
  670. midiCallbacks.add (callbackToAdd);
  671. midiCallbackDevices.add (name);
  672. }
  673. }
  674. void AudioDeviceManager::removeMidiInputCallback (const String& name, MidiInputCallback* callbackToRemove)
  675. {
  676. for (int i = midiCallbacks.size(); --i >= 0;)
  677. {
  678. if (midiCallbackDevices[i] == name && midiCallbacks.getUnchecked(i) == callbackToRemove)
  679. {
  680. const ScopedLock sl (midiCallbackLock);
  681. midiCallbacks.remove (i);
  682. midiCallbackDevices.remove (i);
  683. }
  684. }
  685. }
  686. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message)
  687. {
  688. if (! message.isActiveSense())
  689. {
  690. const bool isDefaultSource = (source == nullptr || source == enabledMidiInputs.getFirst());
  691. const ScopedLock sl (midiCallbackLock);
  692. for (int i = midiCallbackDevices.size(); --i >= 0;)
  693. {
  694. const String name (midiCallbackDevices[i]);
  695. if ((isDefaultSource && name.isEmpty()) || (name.isNotEmpty() && name == source->getName()))
  696. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  697. }
  698. }
  699. }
  700. //==============================================================================
  701. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  702. {
  703. if (defaultMidiOutputName != deviceName)
  704. {
  705. Array <AudioIODeviceCallback*> oldCallbacks;
  706. {
  707. const ScopedLock sl (audioCallbackLock);
  708. oldCallbacks.swapWith (callbacks);
  709. }
  710. if (currentAudioDevice != nullptr)
  711. for (int i = oldCallbacks.size(); --i >= 0;)
  712. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  713. defaultMidiOutput = nullptr;
  714. defaultMidiOutputName = deviceName;
  715. if (deviceName.isNotEmpty())
  716. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  717. if (currentAudioDevice != nullptr)
  718. for (int i = oldCallbacks.size(); --i >= 0;)
  719. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  720. {
  721. const ScopedLock sl (audioCallbackLock);
  722. oldCallbacks.swapWith (callbacks);
  723. }
  724. updateXml();
  725. sendChangeMessage();
  726. }
  727. }
  728. //==============================================================================
  729. void AudioDeviceManager::playTestSound()
  730. {
  731. { // cunningly nested to swap, unlock and delete in that order.
  732. ScopedPointer <AudioSampleBuffer> oldSound;
  733. {
  734. const ScopedLock sl (audioCallbackLock);
  735. oldSound = testSound;
  736. }
  737. }
  738. testSoundPosition = 0;
  739. if (currentAudioDevice != nullptr)
  740. {
  741. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  742. const int soundLength = (int) sampleRate;
  743. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  744. float* samples = newSound->getSampleData (0);
  745. const double frequency = 440.0;
  746. const float amplitude = 0.5f;
  747. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  748. for (int i = 0; i < soundLength; ++i)
  749. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  750. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  751. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  752. const ScopedLock sl (audioCallbackLock);
  753. testSound = newSound;
  754. }
  755. }
  756. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  757. {
  758. if (enableMeasurement)
  759. ++inputLevelMeasurementEnabledCount;
  760. else
  761. --inputLevelMeasurementEnabledCount;
  762. inputLevel = 0;
  763. }
  764. double AudioDeviceManager::getCurrentInputLevel() const
  765. {
  766. jassert (inputLevelMeasurementEnabledCount.get() > 0); // you need to call enableInputLevelMeasurement() before using this!
  767. return inputLevel;
  768. }