Fix crash when host does not support midi-in; Add missing file
[juce-lv2.git] / juce / source / src / audio / devices / juce_AudioDeviceManager.h
blobca65342b26d424c25282cbdbcdac1962d7bad534
1 /*
2 ==============================================================================
4 This file is part of the JUCE library - "Jules' Utility Class Extensions"
5 Copyright 2004-11 by Raw Material Software Ltd.
7 ------------------------------------------------------------------------------
9 JUCE can be redistributed and/or modified under the terms of the GNU General
10 Public License (Version 2), as published by the Free Software Foundation.
11 A copy of the license is included in the JUCE distribution, or can be found
12 online at www.gnu.org/licenses.
14 JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 ------------------------------------------------------------------------------
20 To release a closed-source product which uses JUCE, commercial licenses are
21 available: visit www.rawmaterialsoftware.com/juce for more information.
23 ==============================================================================
26 #ifndef __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
27 #define __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__
29 #include "juce_AudioIODeviceType.h"
30 #include "../midi/juce_MidiInput.h"
31 #include "../midi/juce_MidiOutput.h"
32 #include "../../text/juce_XmlElement.h"
33 #include "../../events/juce_ChangeBroadcaster.h"
34 #include "../dsp/juce_AudioSampleBuffer.h"
35 #include "../../containers/juce_OwnedArray.h"
38 //==============================================================================
39 /**
40 Manages the state of some audio and midi i/o devices.
42 This class keeps tracks of a currently-selected audio device, through
43 with which it continuously streams data from an audio callback, as well as
44 one or more midi inputs.
46 The idea is that your application will create one global instance of this object,
47 and let it take care of creating and deleting specific types of audio devices
48 internally. So when the device is changed, your callbacks will just keep running
49 without having to worry about this.
51 The manager can save and reload all of its device settings as XML, which
52 makes it very easy for you to save and reload the audio setup of your
53 application.
55 And to make it easy to let the user change its settings, there's a component
56 to do just that - the AudioDeviceSelectorComponent class, which contains a set of
57 device selection/sample-rate/latency controls.
59 To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
60 call addAudioCallback() to register your audio callback with it, and use that to process
61 your audio data.
63 The manager also acts as a handy hub for incoming midi messages, allowing a
64 listener to register for messages from either a specific midi device, or from whatever
65 the current default midi input device is. The listener then doesn't have to worry about
66 re-registering with different midi devices if they are changed or deleted.
68 And yet another neat trick is that amount of CPU time being used is measured and
69 available with the getCpuUsage() method.
71 The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
72 listeners whenever one of its settings is changed.
74 @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
76 class JUCE_API AudioDeviceManager : public ChangeBroadcaster
78 public:
79 //==============================================================================
80 /** Creates a default AudioDeviceManager.
82 Initially no audio device will be selected. You should call the initialise() method
83 and register an audio callback with setAudioCallback() before it'll be able to
84 actually make any noise.
86 AudioDeviceManager();
88 /** Destructor. */
89 ~AudioDeviceManager();
91 //==============================================================================
92 /**
93 This structure holds a set of properties describing the current audio setup.
95 An AudioDeviceManager uses this class to save/load its current settings, and to
96 specify your preferred options when opening a device.
98 @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
100 struct JUCE_API AudioDeviceSetup
102 /** Creates an AudioDeviceSetup object.
104 The default constructor sets all the member variables to indicate default values.
105 You can then fill-in any values you want to before passing the object to
106 AudioDeviceManager::initialise().
108 AudioDeviceSetup();
110 bool operator== (const AudioDeviceSetup& other) const;
112 /** The name of the audio device used for output.
113 The name has to be one of the ones listed by the AudioDeviceManager's currently
114 selected device type.
115 This may be the same as the input device.
116 An empty string indicates the default device.
118 String outputDeviceName;
120 /** The name of the audio device used for input.
121 This may be the same as the output device.
122 An empty string indicates the default device.
124 String inputDeviceName;
126 /** The current sample rate.
127 This rate is used for both the input and output devices.
128 A value of 0 indicates the default rate.
130 double sampleRate;
132 /** The buffer size, in samples.
133 This buffer size is used for both the input and output devices.
134 A value of 0 indicates the default buffer size.
136 int bufferSize;
138 /** The set of active input channels.
139 The bits that are set in this array indicate the channels of the
140 input device that are active.
141 If useDefaultInputChannels is true, this value is ignored.
143 BigInteger inputChannels;
145 /** If this is true, it indicates that the inputChannels array
146 should be ignored, and instead, the device's default channels
147 should be used.
149 bool useDefaultInputChannels;
151 /** The set of active output channels.
152 The bits that are set in this array indicate the channels of the
153 input device that are active.
154 If useDefaultOutputChannels is true, this value is ignored.
156 BigInteger outputChannels;
158 /** If this is true, it indicates that the outputChannels array
159 should be ignored, and instead, the device's default channels
160 should be used.
162 bool useDefaultOutputChannels;
166 //==============================================================================
167 /** Opens a set of audio devices ready for use.
169 This will attempt to open either a default audio device, or one that was
170 previously saved as XML.
172 @param numInputChannelsNeeded a minimum number of input channels needed
173 by your app.
174 @param numOutputChannelsNeeded a minimum number of output channels to open
175 @param savedState either a previously-saved state that was produced
176 by createStateXml(), or 0 if you want the manager
177 to choose the best device to open.
178 @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
179 fails to open, then a default device will be used
180 instead. If false, then on failure, no device is
181 opened.
182 @param preferredDefaultDeviceName if this is not empty, and there's a device with this
183 name, then that will be used as the default device
184 (assuming that there wasn't one specified in the XML).
185 The string can actually be a simple wildcard, containing "*"
186 and "?" characters
187 @param preferredSetupOptions if this is non-null, the structure will be used as the
188 set of preferred settings when opening the device. If you
189 use this parameter, the preferredDefaultDeviceName
190 field will be ignored
192 @returns an error message if anything went wrong, or an empty string if it worked ok.
194 String initialise (int numInputChannelsNeeded,
195 int numOutputChannelsNeeded,
196 const XmlElement* savedState,
197 bool selectDefaultDeviceOnFailure,
198 const String& preferredDefaultDeviceName = String::empty,
199 const AudioDeviceSetup* preferredSetupOptions = 0);
201 /** Returns some XML representing the current state of the manager.
203 This stores the current device, its samplerate, block size, etc, and
204 can be restored later with initialise().
206 Note that this can return a null pointer if no settings have been explicitly changed
207 (i.e. if the device manager has just been left in its default state).
209 XmlElement* createStateXml() const;
211 //==============================================================================
212 /** Returns the current device properties that are in use.
214 @see setAudioDeviceSetup
216 void getAudioDeviceSetup (AudioDeviceSetup& setup);
218 /** Changes the current device or its settings.
220 If you want to change a device property, like the current sample rate or
221 block size, you can call getAudioDeviceSetup() to retrieve the current
222 settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
223 and pass it back into this method to apply the new settings.
225 @param newSetup the settings that you'd like to use
226 @param treatAsChosenDevice if this is true and if the device opens correctly, these new
227 settings will be taken as having been explicitly chosen by the
228 user, and the next time createStateXml() is called, these settings
229 will be returned. If it's false, then the device is treated as a
230 temporary or default device, and a call to createStateXml() will
231 return either the last settings that were made with treatAsChosenDevice
232 as true, or the last XML settings that were passed into initialise().
233 @returns an error message if anything went wrong, or an empty string if it worked ok.
235 @see getAudioDeviceSetup
237 String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
238 bool treatAsChosenDevice);
241 /** Returns the currently-active audio device. */
242 AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice; }
244 /** Returns the type of audio device currently in use.
245 @see setCurrentAudioDeviceType
247 String getCurrentAudioDeviceType() const { return currentDeviceType; }
249 /** Returns the currently active audio device type object.
250 Don't keep a copy of this pointer - it's owned by the device manager and could
251 change at any time.
253 AudioIODeviceType* getCurrentDeviceTypeObject() const;
255 /** Changes the class of audio device being used.
257 This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
258 this because there's only one type: CoreAudio.
260 For a list of types, see getAvailableDeviceTypes().
262 void setCurrentAudioDeviceType (const String& type,
263 bool treatAsChosenDevice);
266 /** Closes the currently-open device.
268 You can call restartLastAudioDevice() later to reopen it in the same state
269 that it was just in.
271 void closeAudioDevice();
273 /** Tries to reload the last audio device that was running.
275 Note that this only reloads the last device that was running before
276 closeAudioDevice() was called - it doesn't reload any kind of saved-state,
277 and can only be called after a device has been opened with SetAudioDevice().
279 If a device is already open, this call will do nothing.
281 void restartLastAudioDevice();
283 //==============================================================================
284 /** Registers an audio callback to be used.
286 The manager will redirect callbacks from whatever audio device is currently
287 in use to all registered callback objects. If more than one callback is
288 active, they will all be given the same input data, and their outputs will
289 be summed.
291 If necessary, this method will invoke audioDeviceAboutToStart() on the callback
292 object before returning.
294 To remove a callback, use removeAudioCallback().
296 void addAudioCallback (AudioIODeviceCallback* newCallback);
298 /** Deregisters a previously added callback.
300 If necessary, this method will invoke audioDeviceStopped() on the callback
301 object before returning.
303 @see addAudioCallback
305 void removeAudioCallback (AudioIODeviceCallback* callback);
307 //==============================================================================
308 /** Returns the average proportion of available CPU being spent inside the audio callbacks.
310 Returns a value between 0 and 1.0
312 double getCpuUsage() const;
314 //==============================================================================
315 /** Enables or disables a midi input device.
317 The list of devices can be obtained with the MidiInput::getDevices() method.
319 Any incoming messages from enabled input devices will be forwarded on to all the
320 listeners that have been registered with the addMidiInputCallback() method. They
321 can either register for messages from a particular device, or from just the
322 "default" midi input.
324 Routing the midi input via an AudioDeviceManager means that when a listener
325 registers for the default midi input, this default device can be changed by the
326 manager without the listeners having to know about it or re-register.
328 It also means that a listener can stay registered for a midi input that is disabled
329 or not present, so that when the input is re-enabled, the listener will start
330 receiving messages again.
332 @see addMidiInputCallback, isMidiInputEnabled
334 void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
336 /** Returns true if a given midi input device is being used.
338 @see setMidiInputEnabled
340 bool isMidiInputEnabled (const String& midiInputDeviceName) const;
342 /** Registers a listener for callbacks when midi events arrive from a midi input.
344 The device name can be empty to indicate that it wants events from whatever the
345 current "default" device is. Or it can be the name of one of the midi input devices
346 (see MidiInput::getDevices() for the names).
348 Only devices which are enabled (see the setMidiInputEnabled() method) will have their
349 events forwarded on to listeners.
351 void addMidiInputCallback (const String& midiInputDeviceName,
352 MidiInputCallback* callback);
354 /** Removes a listener that was previously registered with addMidiInputCallback().
356 void removeMidiInputCallback (const String& midiInputDeviceName,
357 MidiInputCallback* callback);
359 //==============================================================================
360 /** Sets a midi output device to use as the default.
362 The list of devices can be obtained with the MidiOutput::getDevices() method.
364 The specified device will be opened automatically and can be retrieved with the
365 getDefaultMidiOutput() method.
367 Pass in an empty string to deselect all devices. For the default device, you
368 can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
370 @see getDefaultMidiOutput, getDefaultMidiOutputName
372 void setDefaultMidiOutput (const String& deviceName);
374 /** Returns the name of the default midi output.
376 @see setDefaultMidiOutput, getDefaultMidiOutput
378 String getDefaultMidiOutputName() const { return defaultMidiOutputName; }
380 /** Returns the current default midi output device.
382 If no device has been selected, or the device can't be opened, this will
383 return 0.
385 @see getDefaultMidiOutputName
387 MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput; }
389 /** Returns a list of the types of device supported.
391 const OwnedArray <AudioIODeviceType>& getAvailableDeviceTypes();
393 //==============================================================================
394 /** Creates a list of available types.
396 This will add a set of new AudioIODeviceType objects to the specified list, to
397 represent each available types of device.
399 You can override this if your app needs to do something specific, like avoid
400 using DirectSound devices, etc.
402 virtual void createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& types);
404 //==============================================================================
405 /** Plays a beep through the current audio device.
407 This is here to allow the audio setup UI panels to easily include a "test"
408 button so that the user can check where the audio is coming from.
410 void playTestSound();
412 /** Turns on level-measuring.
414 When enabled, the device manager will measure the peak input level
415 across all channels, and you can get this level by calling getCurrentInputLevel().
417 This is mainly intended for audio setup UI panels to use to create a mic
418 level display, so that the user can check that they've selected the right
419 device.
421 A simple filter is used to make the level decay smoothly, but this is
422 only intended for giving rough feedback, and not for any kind of accurate
423 measurement.
425 void enableInputLevelMeasurement (bool enableMeasurement);
427 /** Returns the current input level.
429 To use this, you must first enable it by calling enableInputLevelMeasurement().
431 See enableInputLevelMeasurement() for more info.
433 double getCurrentInputLevel() const;
435 /** Returns the a lock that can be used to synchronise access to the audio callback.
436 Obviously while this is locked, you're blocking the audio thread from running, so
437 it must only be used for very brief periods when absolutely necessary.
439 CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
441 /** Returns the a lock that can be used to synchronise access to the midi callback.
442 Obviously while this is locked, you're blocking the midi system from running, so
443 it must only be used for very brief periods when absolutely necessary.
445 CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
447 private:
448 //==============================================================================
449 OwnedArray <AudioIODeviceType> availableDeviceTypes;
450 OwnedArray <AudioDeviceSetup> lastDeviceTypeConfigs;
452 AudioDeviceSetup currentSetup;
453 ScopedPointer <AudioIODevice> currentAudioDevice;
454 Array <AudioIODeviceCallback*> callbacks;
455 int numInputChansNeeded, numOutputChansNeeded;
456 String currentDeviceType;
457 BigInteger inputChannels, outputChannels;
458 ScopedPointer <XmlElement> lastExplicitSettings;
459 mutable bool listNeedsScanning;
460 bool useInputNames;
461 int inputLevelMeasurementEnabledCount;
462 double inputLevel;
463 ScopedPointer <AudioSampleBuffer> testSound;
464 int testSoundPosition;
465 AudioSampleBuffer tempBuffer;
467 StringArray midiInsFromXml;
468 OwnedArray <MidiInput> enabledMidiInputs;
469 Array <MidiInputCallback*> midiCallbacks;
470 StringArray midiCallbackDevices;
471 String defaultMidiOutputName;
472 ScopedPointer <MidiOutput> defaultMidiOutput;
473 CriticalSection audioCallbackLock, midiCallbackLock;
475 double cpuUsageMs, timeToCpuScale;
477 //==============================================================================
478 class CallbackHandler : public AudioIODeviceCallback,
479 public MidiInputCallback,
480 public AudioIODeviceType::Listener
482 public:
483 void audioDeviceIOCallback (const float**, int, float**, int, int);
484 void audioDeviceAboutToStart (AudioIODevice*);
485 void audioDeviceStopped();
486 void handleIncomingMidiMessage (MidiInput*, const MidiMessage&);
487 void audioDeviceListChanged();
489 AudioDeviceManager* owner;
492 CallbackHandler callbackHandler;
493 friend class CallbackHandler;
495 void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
496 float** outputChannelData, int totalNumOutputChannels, int numSamples);
497 void audioDeviceAboutToStartInt (AudioIODevice*);
498 void audioDeviceStoppedInt();
499 void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
500 void audioDeviceListChanged();
502 String restartDevice (int blockSizeToUse, double sampleRateToUse,
503 const BigInteger& ins, const BigInteger& outs);
504 void stopDevice();
506 void updateXml();
508 void createDeviceTypesIfNeeded();
509 void scanDevicesIfNeeded();
510 void deleteCurrentDevice();
511 double chooseBestSampleRate (double preferred) const;
512 int chooseBestBufferSize (int preferred) const;
513 void insertDefaultDeviceNames (AudioDeviceSetup&) const;
515 AudioIODeviceType* findType (const String& inputName, const String& outputName);
517 JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager);
520 #endif // __JUCE_AUDIODEVICEMANAGER_JUCEHEADER__