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.

516 lines
23KB

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