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.

472 lines
20KB

  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. #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  24. #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
  25. #include "juce_AudioIODeviceType.h"
  26. #include "juce_MidiInput.h"
  27. #include "juce_MidiOutput.h"
  28. #include "../../../juce_core/text/juce_XmlElement.h"
  29. #include "../../gui/components/controls/juce_ComboBox.h"
  30. #include "../dsp/juce_AudioSampleBuffer.h"
  31. //==============================================================================
  32. /**
  33. Manages the state of some audio and midi i/o devices.
  34. This class keeps tracks of a currently-selected audio device, through
  35. with which it continuously streams data from an audio callback, as well as
  36. one or more midi inputs.
  37. The idea is that your application will create one global instance of this object,
  38. and let it take care of creating and deleting specific types of audio devices
  39. internally. So when the device is changed, your callbacks will just keep running
  40. without having to worry about this.
  41. The manager can save and reload all of its device settings as XML, which
  42. makes it very easy for you to save and reload the audio setup of your
  43. application.
  44. And to make it easy to let the user change its settings, there's a component
  45. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  46. device selection/sample-rate/latency controls.
  47. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  48. call setAudioCallback() to register your audio callback with it, and use that to process
  49. your audio data.
  50. The manager also acts as a handy hub for incoming midi messages, allowing a
  51. listener to register for messages from either a specific midi device, or from whatever
  52. the current default midi input device is. The listener then doesn't have to worry about
  53. re-registering with different midi devices if they are changed or deleted.
  54. And yet another neat trick is that amount of CPU time being used is measured and
  55. available with the getCpuUsage() method.
  56. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  57. listeners whenever one of its settings is changed.
  58. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  59. */
  60. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  61. {
  62. public:
  63. //==============================================================================
  64. /** Creates a default AudioDeviceManager.
  65. Initially no audio device will be selected. You should call the initialise() method
  66. and register an audio callback with setAudioCallback() before it'll be able to
  67. actually make any noise.
  68. */
  69. AudioDeviceManager();
  70. /** Destructor. */
  71. ~AudioDeviceManager();
  72. //==============================================================================
  73. /**
  74. This structure holds a set of properties describing the current audio setup.
  75. @see AudioDeviceManager::setAudioDeviceSetup()
  76. */
  77. struct AudioDeviceSetup
  78. {
  79. AudioDeviceSetup();
  80. bool operator== (const AudioDeviceSetup& other) const;
  81. /** The name of the audio device used for output.
  82. This may be the same as the input device.
  83. */
  84. String outputDeviceName;
  85. /** The name of the audio device used for input.
  86. This may be the same as the output device.
  87. */
  88. String inputDeviceName;
  89. /** The current sample rate.
  90. This rate is used for both the input and output devices.
  91. */
  92. double sampleRate;
  93. /** The buffer size, in samples.
  94. This buffer size is used for both the input and output devices.
  95. */
  96. int bufferSize;
  97. /** The set of active input channels.
  98. The bits that are set in this array indicate the channels of the
  99. input device that are active.
  100. */
  101. BitArray inputChannels;
  102. /** If this is true, it indicates that the inputChannels array
  103. should be ignored, and instead, the device's default channels
  104. should be used.
  105. */
  106. bool useDefaultInputChannels;
  107. /** The set of active output channels.
  108. The bits that are set in this array indicate the channels of the
  109. input device that are active.
  110. */
  111. BitArray outputChannels;
  112. /** If this is true, it indicates that the outputChannels array
  113. should be ignored, and instead, the device's default channels
  114. should be used.
  115. */
  116. bool useDefaultOutputChannels;
  117. };
  118. //==============================================================================
  119. /** Opens a set of audio devices ready for use.
  120. This will attempt to open either a default audio device, or one that was
  121. previously saved as XML.
  122. @param numInputChannelsNeeded a minimum number of input channels needed
  123. by your app.
  124. @param numOutputChannelsNeeded a minimum number of output channels to open
  125. @param savedState either a previously-saved state that was produced
  126. by createStateXml(), or 0 if you want the manager
  127. to choose the best device to open.
  128. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  129. fails to open, then a default device will be used
  130. instead. If false, then on failure, no device is
  131. opened.
  132. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  133. name, then that will be used as the default device
  134. (assuming that there wasn't one specified in the XML).
  135. The string can actually be a simple wildcard, containing "*"
  136. and "?" characters
  137. @param preferredSetupOptions if this is non-null, the structure will be used as the
  138. set of preferred settings when opening the device. If you
  139. use this parameter, the preferredDefaultDeviceName
  140. field will be ignored
  141. @returns an error message if anything went wrong, or an empty string if it worked ok.
  142. */
  143. const String initialise (const int numInputChannelsNeeded,
  144. const int numOutputChannelsNeeded,
  145. const XmlElement* const savedState,
  146. const bool selectDefaultDeviceOnFailure,
  147. const String& preferredDefaultDeviceName = String::empty,
  148. const AudioDeviceSetup* preferredSetupOptions = 0);
  149. /** Returns some XML representing the current state of the manager.
  150. This stores the current device, its samplerate, block size, etc, and
  151. can be restored later with initialise().
  152. */
  153. XmlElement* createStateXml() const;
  154. //==============================================================================
  155. /** Returns the current device properties that are in use.
  156. @see setAudioDeviceSetup
  157. */
  158. void getAudioDeviceSetup (AudioDeviceSetup& setup);
  159. /** Changes the current device or its settings.
  160. If you want to change a device property, like the current sample rate or
  161. block size, you can call getAudioDeviceSetup() to retrieve the current
  162. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  163. and pass it back into this method to apply the new settings.
  164. @param newSetup the settings that you'd like to use
  165. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  166. settings will be taken as having been explicitly chosen by the
  167. user, and the next time createStateXml() is called, these settings
  168. will be returned. If it's false, then the device is treated as a
  169. temporary or default device, and a call to createStateXml() will
  170. return either the last settings that were made with treatAsChosenDevice
  171. as true, or the last XML settings that were passed into initialise().
  172. @returns an error message if anything went wrong, or an empty string if it worked ok.
  173. @see getAudioDeviceSetup
  174. */
  175. const String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  176. const bool treatAsChosenDevice);
  177. /** Returns the currently-active audio device. */
  178. AudioIODevice* getCurrentAudioDevice() const throw() { return currentAudioDevice; }
  179. const String getCurrentAudioDeviceType() const throw() { return currentDeviceType; }
  180. void setCurrentAudioDeviceType (const String& type,
  181. const bool treatAsChosenDevice);
  182. /** Closes the currently-open device.
  183. You can call restartLastAudioDevice() later to reopen it in the same state
  184. that it was just in.
  185. */
  186. void closeAudioDevice();
  187. /** Tries to reload the last audio device that was running.
  188. Note that this only reloads the last device that was running before
  189. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  190. and can only be called after a device has been opened with SetAudioDevice().
  191. If a device is already open, this call will do nothing.
  192. */
  193. void restartLastAudioDevice();
  194. //==============================================================================
  195. /** Gives the manager an audio callback to use.
  196. The manager will redirect callbacks from whatever audio device is currently
  197. in use to this callback object.
  198. You can pass 0 in here to stop callbacks being made.
  199. */
  200. void setAudioCallback (AudioIODeviceCallback* newCallback);
  201. //==============================================================================
  202. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  203. Returns a value between 0 and 1.0
  204. */
  205. double getCpuUsage() const;
  206. //==============================================================================
  207. /** Enables or disables a midi input device.
  208. The list of devices can be obtained with the MidiInput::getDevices() method.
  209. Any incoming messages from enabled input devices will be forwarded on to all the
  210. listeners that have been registered with the addMidiInputCallback() method. They
  211. can either register for messages from a particular device, or from just the
  212. "default" midi input.
  213. Routing the midi input via an AudioDeviceManager means that when a listener
  214. registers for the default midi input, this default device can be changed by the
  215. manager without the listeners having to know about it or re-register.
  216. It also means that a listener can stay registered for a midi input that is disabled
  217. or not present, so that when the input is re-enabled, the listener will start
  218. receiving messages again.
  219. @see addMidiInputCallback, isMidiInputEnabled
  220. */
  221. void setMidiInputEnabled (const String& midiInputDeviceName,
  222. const bool enabled);
  223. /** Returns true if a given midi input device is being used.
  224. @see setMidiInputEnabled
  225. */
  226. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  227. /** Registers a listener for callbacks when midi events arrive from a midi input.
  228. The device name can be empty to indicate that it wants events from whatever the
  229. current "default" device is. Or it can be the name of one of the midi input devices
  230. (see MidiInput::getDevices() for the names).
  231. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  232. events forwarded on to listeners.
  233. */
  234. void addMidiInputCallback (const String& midiInputDeviceName,
  235. MidiInputCallback* callback);
  236. /** Removes a listener that was previously registered with addMidiInputCallback().
  237. */
  238. void removeMidiInputCallback (const String& midiInputDeviceName,
  239. MidiInputCallback* callback);
  240. //==============================================================================
  241. /** Sets a midi output device to use as the default.
  242. The list of devices can be obtained with the MidiOutput::getDevices() method.
  243. The specified device will be opened automatically and can be retrieved with the
  244. getDefaultMidiOutput() method.
  245. Pass in an empty string to deselect all devices. For the default device, you
  246. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  247. @see getDefaultMidiOutput, getDefaultMidiOutputName
  248. */
  249. void setDefaultMidiOutput (const String& deviceName);
  250. /** Returns the name of the default midi output.
  251. @see setDefaultMidiOutput, getDefaultMidiOutput
  252. */
  253. const String getDefaultMidiOutputName() const throw() { return defaultMidiOutputName; }
  254. /** Returns the current default midi output device.
  255. If no device has been selected, or the device can't be opened, this will
  256. return 0.
  257. @see getDefaultMidiOutputName
  258. */
  259. MidiOutput* getDefaultMidiOutput() const throw() { return defaultMidiOutput; }
  260. /**
  261. */
  262. const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
  263. //==============================================================================
  264. /** Creates a list of available types.
  265. This will add a set of new AudioIODeviceType objects to the specified list, to
  266. represent each available types of device.
  267. You can override this if your app needs to do something specific, like avoid
  268. using DirectSound devices, etc.
  269. */
  270. virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
  271. //==============================================================================
  272. /** Plays a beep through the current audio device.
  273. This is here to allow the audio setup UI panels to easily include a "test"
  274. button so that the user can check where the audio is coming from.
  275. */
  276. void playTestSound();
  277. /** Turns on level-measuring.
  278. When enabled, the device manager will measure the peak input level
  279. across all channels, and you can get this level by calling getCurrentInputLevel().
  280. This is mainly intended for audio setup UI panels to use to create a mic
  281. level display, so that the user can check that they've selected the right
  282. device.
  283. A simple filter is used to make the level decay smoothly, but this is
  284. only intended for giving rough feedback, and not for any kind of accurate
  285. measurement.
  286. */
  287. void enableInputLevelMeasurement (const bool enableMeasurement);
  288. /** Returns the current input level.
  289. To use this, you must first enable it by calling enableInputLevelMeasurement().
  290. See enableInputLevelMeasurement() for more info.
  291. */
  292. double getCurrentInputLevel() const;
  293. //==============================================================================
  294. juce_UseDebuggingNewOperator
  295. private:
  296. //==============================================================================
  297. OwnedArray <AudioIODeviceType> availableDeviceTypes;
  298. OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
  299. AudioDeviceSetup currentSetup;
  300. AudioIODevice* currentAudioDevice;
  301. AudioIODeviceCallback* currentCallback;
  302. int numInputChansNeeded, numOutputChansNeeded;
  303. String currentDeviceType;
  304. BitArray inputChannels, outputChannels;
  305. XmlElement* lastExplicitSettings;
  306. mutable bool listNeedsScanning;
  307. bool useInputNames, inputLevelMeasurementEnabled;
  308. double inputLevel;
  309. AudioSampleBuffer* testSound;
  310. int testSoundPosition;
  311. StringArray midiInsFromXml;
  312. OwnedArray <MidiInput> enabledMidiInputs;
  313. Array <MidiInputCallback*> midiCallbacks;
  314. Array <MidiInput*> midiCallbackDevices;
  315. String defaultMidiOutputName;
  316. MidiOutput* defaultMidiOutput;
  317. CriticalSection audioCallbackLock, midiCallbackLock;
  318. double cpuUsageMs, timeToCpuScale;
  319. //==============================================================================
  320. class CallbackHandler : public AudioIODeviceCallback,
  321. public MidiInputCallback
  322. {
  323. public:
  324. AudioDeviceManager* owner;
  325. void audioDeviceIOCallback (const float** inputChannelData,
  326. int totalNumInputChannels,
  327. float** outputChannelData,
  328. int totalNumOutputChannels,
  329. int numSamples);
  330. void audioDeviceAboutToStart (AudioIODevice*);
  331. void audioDeviceStopped();
  332. void handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message);
  333. };
  334. CallbackHandler callbackHandler;
  335. friend class CallbackHandler;
  336. void audioDeviceIOCallbackInt (const float** inputChannelData,
  337. int totalNumInputChannels,
  338. float** outputChannelData,
  339. int totalNumOutputChannels,
  340. int numSamples);
  341. void audioDeviceAboutToStartInt (AudioIODevice* const device);
  342. void audioDeviceStoppedInt();
  343. void handleIncomingMidiMessageInt (MidiInput* source, const MidiMessage& message);
  344. const String restartDevice (int blockSizeToUse, double sampleRateToUse,
  345. const BitArray& ins, const BitArray& outs);
  346. void stopDevice();
  347. void updateXml();
  348. void createDeviceTypesIfNeeded();
  349. void scanDevicesIfNeeded();
  350. void deleteCurrentDevice();
  351. double chooseBestSampleRate (double preferred) const;
  352. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  353. void insertDefaultDeviceNames (AudioDeviceSetup& setup) const;
  354. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  355. AudioDeviceManager (const AudioDeviceManager&);
  356. const AudioDeviceManager& operator= (const AudioDeviceManager&);
  357. };
  358. #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__