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.

944 lines
32KB

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