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.

625 lines
21KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. #include "../../../juce_core/basics/juce_StandardHeader.h"
  24. BEGIN_JUCE_NAMESPACE
  25. #include "juce_AudioDeviceManager.h"
  26. #include "../../gui/components/juce_Desktop.h"
  27. #include "../../../juce_core/text/juce_LocalisedStrings.h"
  28. //==============================================================================
  29. AudioDeviceManager::AudioDeviceManager()
  30. : currentAudioDevice (0),
  31. currentCallback (0),
  32. numInputChansNeeded (0),
  33. numOutputChansNeeded (2),
  34. lastExplicitSettings (0),
  35. listNeedsScanning (true),
  36. useInputNames (false),
  37. enabledMidiInputs (4),
  38. midiCallbacks (4),
  39. midiCallbackDevices (4),
  40. defaultMidiOutput (0),
  41. cpuUsageMs (0),
  42. timeToCpuScale (0)
  43. {
  44. callbackHandler.owner = this;
  45. AudioIODeviceType::createDeviceTypes (availableDeviceTypes);
  46. }
  47. AudioDeviceManager::~AudioDeviceManager()
  48. {
  49. stopDevice();
  50. deleteAndZero (currentAudioDevice);
  51. deleteAndZero (defaultMidiOutput);
  52. delete lastExplicitSettings;
  53. }
  54. //==============================================================================
  55. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  56. const int numOutputChannelsNeeded,
  57. const XmlElement* const e,
  58. const bool selectDefaultDeviceOnFailure)
  59. {
  60. if (listNeedsScanning)
  61. refreshDeviceList();
  62. numInputChansNeeded = numInputChannelsNeeded;
  63. numOutputChansNeeded = numOutputChannelsNeeded;
  64. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  65. {
  66. lastExplicitSettings = new XmlElement (*e);
  67. BitArray ins, outs;
  68. ins.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  69. outs.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  70. String error (setAudioDevice (e->getStringAttribute (T("audioDeviceName")),
  71. e->getIntAttribute (T("audioDeviceBufferSize")),
  72. e->getDoubleAttribute (T("audioDeviceRate")),
  73. e->hasAttribute (T("audioDeviceInChans")) ? &ins : 0,
  74. e->hasAttribute (T("audioDeviceOutChans")) ? &outs : 0,
  75. true));
  76. StringArray enabledMidiIns;
  77. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  78. enabledMidiIns.add (c->getStringAttribute (T("name")));
  79. const StringArray allMidiIns (MidiInput::getDevices());
  80. for (int i = allMidiIns.size(); --i >= 0;)
  81. setMidiInputEnabled (allMidiIns[i], enabledMidiIns.contains (allMidiIns[i]));
  82. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  83. initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0, false);
  84. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  85. return error;
  86. }
  87. else
  88. {
  89. setInputDeviceNamesUsed (numOutputChannelsNeeded == 0);
  90. String defaultDevice;
  91. if (availableDeviceTypes [0] != 0)
  92. defaultDevice = availableDeviceTypes[0]->getDefaultDeviceName (numOutputChannelsNeeded == 0,
  93. numInputChannelsNeeded,
  94. numOutputChannelsNeeded);
  95. return setAudioDevice (defaultDevice, 0, 0, 0, 0, false);
  96. }
  97. }
  98. XmlElement* AudioDeviceManager::createStateXml() const
  99. {
  100. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  101. }
  102. //==============================================================================
  103. const StringArray AudioDeviceManager::getAvailableAudioDeviceNames() const
  104. {
  105. if (listNeedsScanning)
  106. refreshDeviceList();
  107. StringArray names;
  108. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  109. names.addArray (availableDeviceTypes[i]->getDeviceNames (useInputNames));
  110. return names;
  111. }
  112. void AudioDeviceManager::refreshDeviceList() const
  113. {
  114. listNeedsScanning = false;
  115. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  116. availableDeviceTypes[i]->scanForDevices();
  117. }
  118. void AudioDeviceManager::setInputDeviceNamesUsed (const bool useInputNames_)
  119. {
  120. useInputNames = useInputNames_;
  121. sendChangeMessage (this);
  122. }
  123. void AudioDeviceManager::addDeviceNamesToComboBox (ComboBox& combo) const
  124. {
  125. int n = 0;
  126. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  127. {
  128. AudioIODeviceType* const type = availableDeviceTypes[i];
  129. if (availableDeviceTypes.size() > 1)
  130. combo.addSectionHeading (type->getTypeName() + T(" devices:"));
  131. const StringArray names (type->getDeviceNames (useInputNames));
  132. for (int j = 0; j < names.size(); ++j)
  133. combo.addItem (names[j], ++n);
  134. combo.addSeparator();
  135. }
  136. combo.addItem (TRANS("<< no audio device >>"), -1);
  137. }
  138. const String AudioDeviceManager::getCurrentAudioDeviceName() const
  139. {
  140. if (currentAudioDevice != 0)
  141. return currentAudioDevice->getName();
  142. return String::empty;
  143. }
  144. const String AudioDeviceManager::setAudioDevice (const String& deviceNameToUse,
  145. int blockSizeToUse,
  146. double sampleRateToUse,
  147. const BitArray* inChans,
  148. const BitArray* outChans,
  149. const bool treatAsChosenDevice)
  150. {
  151. stopDevice();
  152. String error;
  153. if (deviceNameToUse.isNotEmpty())
  154. {
  155. const StringArray devNames (getAvailableAudioDeviceNames());
  156. int index = devNames.indexOf (deviceNameToUse, true);
  157. if (index >= 0)
  158. {
  159. if (currentAudioDevice == 0
  160. || currentAudioDevice->getLastError().isNotEmpty()
  161. || ! deviceNameToUse.equalsIgnoreCase (currentAudioDevice->getName()))
  162. {
  163. // change of device..
  164. deleteAndZero (currentAudioDevice);
  165. int n = 0;
  166. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  167. {
  168. AudioIODeviceType* const type = availableDeviceTypes[i];
  169. const StringArray names (type->getDeviceNames (useInputNames));
  170. if (index >= n && index < n + names.size())
  171. {
  172. currentAudioDevice = type->createDevice (deviceNameToUse);
  173. break;
  174. }
  175. n += names.size();
  176. }
  177. error = currentAudioDevice->getLastError();
  178. if (error.isNotEmpty())
  179. {
  180. deleteAndZero (currentAudioDevice);
  181. return error;
  182. }
  183. inputChannels.clear();
  184. inputChannels.setRange (0, numInputChansNeeded, true);
  185. outputChannels.clear();
  186. outputChannels.setRange (0, numOutputChansNeeded, true);
  187. }
  188. if (inChans != 0)
  189. inputChannels = *inChans;
  190. if (outChans != 0)
  191. outputChannels = *outChans;
  192. error = restartDevice (blockSizeToUse,
  193. sampleRateToUse,
  194. inputChannels,
  195. outputChannels);
  196. if (error.isNotEmpty())
  197. {
  198. deleteAndZero (currentAudioDevice);
  199. }
  200. }
  201. else
  202. {
  203. deleteAndZero (currentAudioDevice);
  204. error << "No such device: " << deviceNameToUse;
  205. }
  206. }
  207. else
  208. {
  209. deleteAndZero (currentAudioDevice);
  210. }
  211. if (treatAsChosenDevice && error.isEmpty())
  212. updateXml();
  213. return error;
  214. }
  215. const String AudioDeviceManager::restartDevice (int blockSizeToUse,
  216. double sampleRateToUse,
  217. const BitArray& inChans,
  218. const BitArray& outChans)
  219. {
  220. stopDevice();
  221. inputChannels = inChans;
  222. outputChannels = outChans;
  223. if (sampleRateToUse > 0)
  224. {
  225. bool ok = false;
  226. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  227. {
  228. const double sr = currentAudioDevice->getSampleRate (i);
  229. if (sr == sampleRateToUse)
  230. ok = true;
  231. }
  232. if (! ok)
  233. sampleRateToUse = 0;
  234. }
  235. if (sampleRateToUse == 0)
  236. {
  237. double lowestAbove44 = 0.0;
  238. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  239. {
  240. const double sr = currentAudioDevice->getSampleRate (i);
  241. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  242. lowestAbove44 = sr;
  243. }
  244. if (lowestAbove44 == 0.0)
  245. sampleRateToUse = currentAudioDevice->getSampleRate (0);
  246. else
  247. sampleRateToUse = lowestAbove44;
  248. }
  249. const String error (currentAudioDevice->open (inChans, outChans,
  250. sampleRateToUse, blockSizeToUse));
  251. if (error.isEmpty())
  252. currentAudioDevice->start (&callbackHandler);
  253. sendChangeMessage (this);
  254. return error;
  255. }
  256. void AudioDeviceManager::stopDevice()
  257. {
  258. if (currentAudioDevice != 0)
  259. currentAudioDevice->stop();
  260. }
  261. void AudioDeviceManager::setInputChannels (const BitArray& newEnabledChannels,
  262. const bool treatAsChosenDevice)
  263. {
  264. if (currentAudioDevice != 0
  265. && newEnabledChannels != inputChannels)
  266. {
  267. setAudioDevice (currentAudioDevice->getName(),
  268. currentAudioDevice->getCurrentBufferSizeSamples(),
  269. currentAudioDevice->getCurrentSampleRate(),
  270. &newEnabledChannels, 0,
  271. treatAsChosenDevice);
  272. }
  273. }
  274. void AudioDeviceManager::setOutputChannels (const BitArray& newEnabledChannels,
  275. const bool treatAsChosenDevice)
  276. {
  277. if (currentAudioDevice != 0
  278. && newEnabledChannels != outputChannels)
  279. {
  280. setAudioDevice (currentAudioDevice->getName(),
  281. currentAudioDevice->getCurrentBufferSizeSamples(),
  282. currentAudioDevice->getCurrentSampleRate(),
  283. 0, &newEnabledChannels,
  284. treatAsChosenDevice);
  285. }
  286. }
  287. void AudioDeviceManager::updateXml()
  288. {
  289. delete lastExplicitSettings;
  290. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  291. lastExplicitSettings->setAttribute (T("audioDeviceName"), getCurrentAudioDeviceName());
  292. if (currentAudioDevice != 0)
  293. {
  294. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  295. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  296. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  297. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), inputChannels.toString (2));
  298. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), outputChannels.toString (2));
  299. }
  300. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  301. {
  302. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  303. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  304. lastExplicitSettings->addChildElement (m);
  305. }
  306. if (defaultMidiOutputName.isNotEmpty())
  307. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  308. }
  309. //==============================================================================
  310. void AudioDeviceManager::setAudioCallback (AudioIODeviceCallback* newCallback)
  311. {
  312. if (newCallback != currentCallback)
  313. {
  314. AudioIODeviceCallback* lastCallback = currentCallback;
  315. audioCallbackLock.enter();
  316. currentCallback = 0;
  317. audioCallbackLock.exit();
  318. if (currentAudioDevice != 0)
  319. {
  320. if (lastCallback != 0)
  321. lastCallback->audioDeviceStopped();
  322. if (newCallback != 0)
  323. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  324. }
  325. currentCallback = newCallback;
  326. }
  327. }
  328. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  329. int totalNumInputChannels,
  330. float** outputChannelData,
  331. int totalNumOutputChannels,
  332. int numSamples)
  333. {
  334. const ScopedLock sl (audioCallbackLock);
  335. if (currentCallback != 0)
  336. {
  337. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  338. currentCallback->audioDeviceIOCallback (inputChannelData,
  339. totalNumInputChannels,
  340. outputChannelData,
  341. totalNumOutputChannels,
  342. numSamples);
  343. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  344. const double filterAmount = 0.2;
  345. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  346. }
  347. }
  348. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  349. {
  350. cpuUsageMs = 0;
  351. const double sampleRate = device->getCurrentSampleRate();
  352. const int blockSize = device->getCurrentBufferSizeSamples();
  353. if (sampleRate > 0.0 && blockSize > 0)
  354. {
  355. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  356. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  357. }
  358. if (currentCallback != 0)
  359. currentCallback->audioDeviceAboutToStart (device);
  360. sendChangeMessage (this);
  361. }
  362. void AudioDeviceManager::audioDeviceStoppedInt()
  363. {
  364. cpuUsageMs = 0;
  365. timeToCpuScale = 0;
  366. sendChangeMessage (this);
  367. if (currentCallback != 0)
  368. currentCallback->audioDeviceStopped();
  369. }
  370. double AudioDeviceManager::getCpuUsage() const
  371. {
  372. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  373. }
  374. //==============================================================================
  375. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  376. const bool enabled)
  377. {
  378. if (enabled != isMidiInputEnabled (name))
  379. {
  380. if (enabled)
  381. {
  382. const int index = MidiInput::getDevices().indexOf (name);
  383. if (index >= 0)
  384. {
  385. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  386. if (min != 0)
  387. {
  388. enabledMidiInputs.add (min);
  389. min->start();
  390. }
  391. }
  392. }
  393. else
  394. {
  395. for (int i = enabledMidiInputs.size(); --i >= 0;)
  396. if (enabledMidiInputs[i]->getName() == name)
  397. enabledMidiInputs.remove (i);
  398. }
  399. updateXml();
  400. sendChangeMessage (this);
  401. }
  402. }
  403. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  404. {
  405. for (int i = enabledMidiInputs.size(); --i >= 0;)
  406. if (enabledMidiInputs[i]->getName() == name)
  407. return true;
  408. return false;
  409. }
  410. void AudioDeviceManager::addMidiInputCallback (const String& name,
  411. MidiInputCallback* callback)
  412. {
  413. removeMidiInputCallback (callback);
  414. if (name.isEmpty())
  415. {
  416. midiCallbacks.add (callback);
  417. midiCallbackDevices.add (0);
  418. }
  419. else
  420. {
  421. for (int i = enabledMidiInputs.size(); --i >= 0;)
  422. {
  423. if (enabledMidiInputs[i]->getName() == name)
  424. {
  425. const ScopedLock sl (midiCallbackLock);
  426. if (! midiCallbacks.contains (callback))
  427. {
  428. midiCallbacks.add (callback);
  429. midiCallbackDevices.add (enabledMidiInputs[i]);
  430. }
  431. break;
  432. }
  433. }
  434. }
  435. }
  436. void AudioDeviceManager::removeMidiInputCallback (MidiInputCallback* callback)
  437. {
  438. const ScopedLock sl (midiCallbackLock);
  439. const int index = midiCallbacks.indexOf (callback);
  440. midiCallbacks.remove (index);
  441. midiCallbackDevices.remove (index);
  442. }
  443. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  444. const MidiMessage& message)
  445. {
  446. if (! message.isActiveSense())
  447. {
  448. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  449. const ScopedLock sl (midiCallbackLock);
  450. for (int i = midiCallbackDevices.size(); --i >= 0;)
  451. {
  452. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  453. if (md == source || (md == 0 && isDefaultSource))
  454. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  455. }
  456. }
  457. }
  458. //==============================================================================
  459. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  460. {
  461. if (defaultMidiOutputName != deviceName)
  462. {
  463. deleteAndZero (defaultMidiOutput);
  464. defaultMidiOutputName = deviceName;
  465. if (deviceName.isNotEmpty())
  466. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  467. updateXml();
  468. sendChangeMessage (this);
  469. }
  470. }
  471. //==============================================================================
  472. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  473. int totalNumInputChannels,
  474. float** outputChannelData,
  475. int totalNumOutputChannels,
  476. int numSamples)
  477. {
  478. owner->audioDeviceIOCallbackInt (inputChannelData, totalNumInputChannels, outputChannelData, totalNumOutputChannels, numSamples);
  479. }
  480. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  481. {
  482. owner->audioDeviceAboutToStartInt (device);
  483. }
  484. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  485. {
  486. owner->audioDeviceStoppedInt();
  487. }
  488. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  489. {
  490. owner->handleIncomingMidiMessageInt (source, message);
  491. }
  492. END_JUCE_NAMESPACE