OpenShot Library | OpenShotAudio  0.2.1
juce_AudioDeviceManager.h
1 
2 /** @weakgroup juce_audio_devices-audio_io
3  * @{
4  */
5 /*
6  ==============================================================================
7 
8  This file is part of the JUCE library.
9  Copyright (c) 2017 - ROLI Ltd.
10 
11  JUCE is an open source library subject to commercial or open-source
12  licensing.
13 
14  The code included in this file is provided under the terms of the ISC license
15  http://www.isc.org/downloads/software-support-policy/isc-license. Permission
16  To use, copy, modify, and/or distribute this software for any purpose with or
17  without fee is hereby granted provided that the above copyright notice and
18  this permission notice appear in all copies.
19 
20  JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
21  EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
22  DISCLAIMED.
23 
24  ==============================================================================
25 */
26 
27 namespace juce
28 {
29 
30 //==============================================================================
31 /**
32  Manages the state of some audio and midi i/o devices.
33 
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 
38  The idea is that your application will create one global instance of this object,
39  and let it take care of creating and deleting specific types of audio devices
40  internally. So when the device is changed, your callbacks will just keep running
41  without having to worry about this.
42 
43  The manager can save and reload all of its device settings as XML, which
44  makes it very easy for you to save and reload the audio setup of your
45  application.
46 
47  And to make it easy to let the user change its settings, there's a component
48  to do just that - the AudioDeviceSelectorComponent class, which contains a set of
49  device selection/sample-rate/latency controls.
50 
51  To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
52  call addAudioCallback() to register your audio callback with it, and use that to process
53  your audio data.
54 
55  The manager also acts as a handy hub for incoming midi messages, allowing a
56  listener to register for messages from either a specific midi device, or from whatever
57  the current default midi input device is. The listener then doesn't have to worry about
58  re-registering with different midi devices if they are changed or deleted.
59 
60  And yet another neat trick is that amount of CPU time being used is measured and
61  available with the getCpuUsage() method.
62 
63  The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
64  listeners whenever one of its settings is changed.
65 
66  @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
67 
68  @tags{Audio}
69 */
71 {
72 public:
73  //==============================================================================
74  /** Creates a default AudioDeviceManager.
75 
76  Initially no audio device will be selected. You should call the initialise() method
77  and register an audio callback with setAudioCallback() before it'll be able to
78  actually make any noise.
79  */
81 
82  /** Destructor. */
83  ~AudioDeviceManager() override;
84 
85  //==============================================================================
86  /**
87  This structure holds a set of properties describing the current audio setup.
88 
89  An AudioDeviceManager uses this class to save/load its current settings, and to
90  specify your preferred options when opening a device.
91 
92  @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
93  */
95  {
96  /** The name of the audio device used for output.
97  The name has to be one of the ones listed by the AudioDeviceManager's currently
98  selected device type.
99  This may be the same as the input device.
100  An empty string indicates the default device.
101  */
103 
104  /** The name of the audio device used for input.
105  This may be the same as the output device.
106  An empty string indicates the default device.
107  */
109 
110  /** The current sample rate.
111  This rate is used for both the input and output devices.
112  A value of 0 indicates that you don't care what rate is used, and the
113  device will choose a sensible rate for you.
114  */
115  double sampleRate = 0;
116 
117  /** The buffer size, in samples.
118  This buffer size is used for both the input and output devices.
119  A value of 0 indicates the default buffer size.
120  */
121  int bufferSize = 0;
122 
123  /** The set of active input channels.
124  The bits that are set in this array indicate the channels of the
125  input device that are active.
126  If useDefaultInputChannels is true, this value is ignored.
127  */
129 
130  /** If this is true, it indicates that the inputChannels array
131  should be ignored, and instead, the device's default channels
132  should be used.
133  */
134  bool useDefaultInputChannels = true;
135 
136  /** The set of active output channels.
137  The bits that are set in this array indicate the channels of the
138  input device that are active.
139  If useDefaultOutputChannels is true, this value is ignored.
140  */
142 
143  /** If this is true, it indicates that the outputChannels array
144  should be ignored, and instead, the device's default channels
145  should be used.
146  */
147  bool useDefaultOutputChannels = true;
148 
149  bool operator== (const AudioDeviceSetup&) const;
150  bool operator!= (const AudioDeviceSetup&) const;
151  };
152 
153 
154  //==============================================================================
155  /** Opens a set of audio devices ready for use.
156 
157  This will attempt to open either a default audio device, or one that was
158  previously saved as XML.
159 
160  @param numInputChannelsNeeded the maximum number of input channels your app would like to
161  use (the actual number of channels opened may be less than
162  the number requested)
163  @param numOutputChannelsNeeded the maximum number of output channels your app would like to
164  use (the actual number of channels opened may be less than
165  the number requested)
166  @param savedState either a previously-saved state that was produced
167  by createStateXml(), or nullptr if you want the manager
168  to choose the best device to open.
169  @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
170  fails to open, then a default device will be used
171  instead. If false, then on failure, no device is
172  opened.
173  @param preferredDefaultDeviceName if this is not empty, and there's a device with this
174  name, then that will be used as the default device
175  (assuming that there wasn't one specified in the XML).
176  The string can actually be a simple wildcard, containing "*"
177  and "?" characters
178  @param preferredSetupOptions if this is non-null, the structure will be used as the
179  set of preferred settings when opening the device. If you
180  use this parameter, the preferredDefaultDeviceName
181  field will be ignored
182 
183  @returns an error message if anything went wrong, or an empty string if it worked ok.
184  */
185  String initialise (int numInputChannelsNeeded,
186  int numOutputChannelsNeeded,
187  const XmlElement* savedState,
188  bool selectDefaultDeviceOnFailure,
189  const String& preferredDefaultDeviceName = String(),
190  const AudioDeviceSetup* preferredSetupOptions = nullptr);
191 
192  /** Resets everything to a default device setup, clearing any stored settings. */
193  String initialiseWithDefaultDevices (int numInputChannelsNeeded,
194  int numOutputChannelsNeeded);
195 
196  /** Returns some XML representing the current state of the manager.
197 
198  This stores the current device, its samplerate, block size, etc, and
199  can be restored later with initialise().
200 
201  Note that this can return a null pointer if no settings have been explicitly changed
202  (i.e. if the device manager has just been left in its default state).
203  */
204  std::unique_ptr<XmlElement> createStateXml() const;
205 
206  //==============================================================================
207  /** Returns the current device properties that are in use.
208  @see setAudioDeviceSetup
209  */
210  AudioDeviceSetup getAudioDeviceSetup() const;
211 
212  /** Returns the current device properties that are in use.
213  This is an old method, kept around for compatibility, but you should prefer the new
214  version which returns the result rather than taking an out-parameter.
215  @see getAudioDeviceSetup()
216  */
217  void getAudioDeviceSetup (AudioDeviceSetup& result) const;
218 
219  /** Changes the current device or its settings.
220 
221  If you want to change a device property, like the current sample rate or
222  block size, you can call getAudioDeviceSetup() to retrieve the current
223  settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
224  and pass it back into this method to apply the new settings.
225 
226  @param newSetup the settings that you'd like to use
227  @param treatAsChosenDevice if this is true and if the device opens correctly, these new
228  settings will be taken as having been explicitly chosen by the
229  user, and the next time createStateXml() is called, these settings
230  will be returned. If it's false, then the device is treated as a
231  temporary or default device, and a call to createStateXml() will
232  return either the last settings that were made with treatAsChosenDevice
233  as true, or the last XML settings that were passed into initialise().
234  @returns an error message if anything went wrong, or an empty string if it worked ok.
235 
236  @see getAudioDeviceSetup
237  */
238  String setAudioDeviceSetup (const AudioDeviceSetup& newSetup, bool treatAsChosenDevice);
239 
240 
241  /** Returns the currently-active audio device. */
242  AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice.get(); }
243 
244  /** Returns the type of audio device currently in use.
245  @see setCurrentAudioDeviceType
246  */
247  String getCurrentAudioDeviceType() const { return currentDeviceType; }
248 
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.
252  */
253  AudioIODeviceType* getCurrentDeviceTypeObject() const;
254 
255  /** Changes the class of audio device being used.
256 
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.
259 
260  For a list of types, see getAvailableDeviceTypes().
261  */
262  void setCurrentAudioDeviceType (const String& type, bool treatAsChosenDevice);
263 
264  /** Closes the currently-open device.
265  You can call restartLastAudioDevice() later to reopen it in the same state
266  that it was just in.
267  */
268  void closeAudioDevice();
269 
270  /** Tries to reload the last audio device that was running.
271 
272  Note that this only reloads the last device that was running before
273  closeAudioDevice() was called - it doesn't reload any kind of saved-state,
274  and can only be called after a device has been opened with SetAudioDevice().
275 
276  If a device is already open, this call will do nothing.
277  */
278  void restartLastAudioDevice();
279 
280  //==============================================================================
281  /** Registers an audio callback to be used.
282 
283  The manager will redirect callbacks from whatever audio device is currently
284  in use to all registered callback objects. If more than one callback is
285  active, they will all be given the same input data, and their outputs will
286  be summed.
287 
288  If necessary, this method will invoke audioDeviceAboutToStart() on the callback
289  object before returning.
290 
291  To remove a callback, use removeAudioCallback().
292  */
293  void addAudioCallback (AudioIODeviceCallback* newCallback);
294 
295  /** Deregisters a previously added callback.
296 
297  If necessary, this method will invoke audioDeviceStopped() on the callback
298  object before returning.
299 
300  @see addAudioCallback
301  */
302  void removeAudioCallback (AudioIODeviceCallback* callback);
303 
304  //==============================================================================
305  /** Returns the average proportion of available CPU being spent inside the audio callbacks.
306  @returns A value between 0 and 1.0 to indicate the approximate proportion of CPU
307  time spent in the callbacks.
308  */
309  double getCpuUsage() const;
310 
311  //==============================================================================
312  /** Enables or disables a midi input device.
313 
314  The list of devices can be obtained with the MidiInput::getAvailableDevices() method.
315 
316  Any incoming messages from enabled input devices will be forwarded on to all the
317  listeners that have been registered with the addMidiInputDeviceCallback() method. They
318  can either register for messages from a particular device, or from just the "default"
319  midi input.
320 
321  Routing the midi input via an AudioDeviceManager means that when a listener
322  registers for the default midi input, this default device can be changed by the
323  manager without the listeners having to know about it or re-register.
324 
325  It also means that a listener can stay registered for a midi input that is disabled
326  or not present, so that when the input is re-enabled, the listener will start
327  receiving messages again.
328 
329  @see addMidiInputDeviceCallback, isMidiInputDeviceEnabled
330  */
331  void setMidiInputDeviceEnabled (const String& deviceIdentifier, bool enabled);
332 
333  /** Returns true if a given midi input device is being used.
334 
335  @see setMidiInputDeviceEnabled
336  */
337  bool isMidiInputDeviceEnabled (const String& deviceIdentifier) const;
338 
339  /** Registers a listener for callbacks when midi events arrive from a midi input.
340 
341  The device identifier can be empty to indicate that it wants to receive all incoming
342  events from all the enabled MIDI inputs. Or it can be the identifier of one of the
343  MIDI input devices if it just wants the events from that device. (see
344  MidiInput::getAvailableDevices() for the list of devices).
345 
346  Only devices which are enabled (see the setMidiInputDeviceEnabled() method) will have their
347  events forwarded on to listeners.
348  */
349  void addMidiInputDeviceCallback (const String& deviceIdentifier,
350  MidiInputCallback* callback);
351 
352  /** Removes a listener that was previously registered with addMidiInputDeviceCallback(). */
353  void removeMidiInputDeviceCallback (const String& deviceIdentifier,
354  MidiInputCallback* callback);
355 
356  //==============================================================================
357  /** Sets a midi output device to use as the default.
358 
359  The list of devices can be obtained with the MidiOutput::getAvailableDevices() method.
360 
361  The specified device will be opened automatically and can be retrieved with the
362  getDefaultMidiOutput() method.
363 
364  Pass in an empty string to deselect all devices. For the default device, you
365  can use MidiOutput::getDefaultDevice().
366 
367  @see getDefaultMidiOutput, getDefaultMidiOutputIdentifier
368  */
369  void setDefaultMidiOutputDevice (const String& deviceIdentifier);
370 
371  /** Returns the name of the default midi output.
372 
373  @see setDefaultMidiOutputDevice, getDefaultMidiOutput
374  */
375  const String& getDefaultMidiOutputIdentifier() const noexcept { return defaultMidiOutputDeviceInfo.identifier; }
376 
377  /** Returns the current default midi output device. If no device has been selected, or the
378  device can't be opened, this will return nullptr.
379 
380  @see getDefaultMidiOutputIdentifier
381  */
382  MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput.get(); }
383 
384  //==============================================================================
385  /** Returns a list of the types of device supported. */
386  const OwnedArray<AudioIODeviceType>& getAvailableDeviceTypes();
387 
388  /** Creates a list of available types.
389 
390  This will add a set of new AudioIODeviceType objects to the specified list, to
391  represent each available types of device.
392 
393  You can override this if your app needs to do something specific, like avoid
394  using DirectSound devices, etc.
395  */
396  virtual void createAudioDeviceTypes (OwnedArray<AudioIODeviceType>& types);
397 
398  /** Adds a new device type to the list of types. */
399  void addAudioDeviceType (std::unique_ptr<AudioIODeviceType> newDeviceType);
400 
401  /** Removes a previously added device type from the manager. */
402  void removeAudioDeviceType (AudioIODeviceType* deviceTypeToRemove);
403 
404  //==============================================================================
405  /** Plays a beep through the current audio device.
406 
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.
409  */
410  void playTestSound();
411 
412  //==============================================================================
413  /**
414  A simple reference-counted struct that holds a level-meter value that can be read
415  using getCurrentLevel().
416 
417  This is used to ensure that the level processing code is only executed when something
418  holds a reference to one of these objects and will be bypassed otherwise.
419 
420  @see getInputLevelGetter, getOutputLevelGetter
421  */
423  {
424  LevelMeter() noexcept;
425  double getCurrentLevel() const noexcept;
426 
428 
429  private:
430  friend class AudioDeviceManager;
431 
432  Atomic<float> level { 0 };
433  void updateLevel (const float* const*, int numChannels, int numSamples) noexcept;
434  };
435 
436  /** Returns a reference-counted object that can be used to get the current input level.
437 
438  You need to store this object locally to ensure that the reference count is incremented
439  and decremented properly. The current input level value can be read using getCurrentLevel().
440  */
441  LevelMeter::Ptr getInputLevelGetter() noexcept { return inputLevelGetter; }
442 
443  /** Returns a reference-counted object that can be used to get the current output level.
444 
445  You need to store this object locally to ensure that the reference count is incremented
446  and decremented properly. The current output level value can be read using getCurrentLevel().
447  */
448  LevelMeter::Ptr getOutputLevelGetter() noexcept { return outputLevelGetter; }
449 
450  //==============================================================================
451  /** Returns the a lock that can be used to synchronise access to the audio callback.
452  Obviously while this is locked, you're blocking the audio thread from running, so
453  it must only be used for very brief periods when absolutely necessary.
454  */
455  CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
456 
457  /** Returns the a lock that can be used to synchronise access to the midi callback.
458  Obviously while this is locked, you're blocking the midi system from running, so
459  it must only be used for very brief periods when absolutely necessary.
460  */
461  CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
462 
463  //==============================================================================
464  /** Returns the number of under- or over runs reported.
465 
466  This method will use the underlying device's native getXRunCount if it supports
467  it. Otherwise it will estimate the number of under-/overruns by measuring the
468  time it spent in the audio callback.
469  */
470  int getXRunCount() const noexcept;
471 
472  //==============================================================================
473  /** Deprecated. */
474  void setMidiInputEnabled (const String&, bool);
475  /** Deprecated. */
476  bool isMidiInputEnabled (const String&) const;
477  /** Deprecated. */
478  void addMidiInputCallback (const String&, MidiInputCallback*);
479  /** Deprecated. */
480  void removeMidiInputCallback (const String&, MidiInputCallback*);
481  /** Deprecated. */
482  void setDefaultMidiOutput (const String&);
483  /** Deprecated. */
484  const String& getDefaultMidiOutputName() const noexcept { return defaultMidiOutputDeviceInfo.name; }
485 
486 private:
487  //==============================================================================
488  OwnedArray<AudioIODeviceType> availableDeviceTypes;
489  OwnedArray<AudioDeviceSetup> lastDeviceTypeConfigs;
490 
491  AudioDeviceSetup currentSetup;
492  std::unique_ptr<AudioIODevice> currentAudioDevice;
494  int numInputChansNeeded = 0, numOutputChansNeeded = 2;
495  String preferredDeviceName, currentDeviceType;
496  std::unique_ptr<XmlElement> lastExplicitSettings;
497  mutable bool listNeedsScanning = true;
498  AudioBuffer<float> tempBuffer;
499 
500  struct MidiCallbackInfo
501  {
502  String deviceIdentifier;
503  MidiInputCallback* callback;
504  };
505 
506  Array<MidiDeviceInfo> midiDeviceInfosFromXml;
507  std::vector<std::unique_ptr<MidiInput>> enabledMidiInputs;
508  Array<MidiCallbackInfo> midiCallbacks;
509 
510  MidiDeviceInfo defaultMidiOutputDeviceInfo;
511  std::unique_ptr<MidiOutput> defaultMidiOutput;
512  CriticalSection audioCallbackLock, midiCallbackLock;
513 
514  std::unique_ptr<AudioBuffer<float>> testSound;
515  int testSoundPosition = 0;
516 
517  AudioProcessLoadMeasurer loadMeasurer;
518 
519  LevelMeter::Ptr inputLevelGetter { new LevelMeter() },
520  outputLevelGetter { new LevelMeter() };
521 
522  //==============================================================================
523  class CallbackHandler;
524  std::unique_ptr<CallbackHandler> callbackHandler;
525 
526  void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
527  float** outputChannelData, int totalNumOutputChannels, int numSamples);
528  void audioDeviceAboutToStartInt (AudioIODevice*);
529  void audioDeviceStoppedInt();
530  void audioDeviceErrorInt (const String&);
531  void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
532  void audioDeviceListChanged();
533 
534  String restartDevice (int blockSizeToUse, double sampleRateToUse,
535  const BigInteger& ins, const BigInteger& outs);
536  void stopDevice();
537 
538  void updateXml();
539 
540  void createDeviceTypesIfNeeded();
541  void scanDevicesIfNeeded();
542  void deleteCurrentDevice();
543  double chooseBestSampleRate (double preferred) const;
544  int chooseBestBufferSize (int preferred) const;
545  void insertDefaultDeviceNames (AudioDeviceSetup&) const;
546  String initialiseDefault (const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
547  String initialiseFromXML (const XmlElement&, bool selectDefaultDeviceOnFailure,
548  const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
549 
550  AudioIODeviceType* findType (const String& inputName, const String& outputName);
551  AudioIODeviceType* findType (const String& typeName);
552 
553  JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager)
554 };
555 
556 } // namespace juce
557 
558 /** @}*/
LevelMeter::Ptr getOutputLevelGetter() noexcept
Returns a reference-counted object that can be used to get the current output level.
One of these is passed to an AudioIODevice object to stream the audio data in and out...
BigInteger outputChannels
The set of active output channels.
#define JUCE_API
This macro is added to all JUCE public class declarations.
Represents a midi input device.
Encapsulates a MIDI message.
String getCurrentAudioDeviceType() const
Returns the type of audio device currently in use.
String outputDeviceName
The name of the audio device used for output.
Used to build a tree of elements representing an XML document.
AudioIODevice * getCurrentAudioDevice() const noexcept
Returns the currently-active audio device.
CriticalSection & getMidiCallbackLock() noexcept
Returns the a lock that can be used to synchronise access to the midi callback.
CriticalSection & getAudioCallbackLock() noexcept
Returns the a lock that can be used to synchronise access to the audio callback.
The JUCE String class!
Definition: juce_String.h:42
BigInteger inputChannels
The set of active input channels.
An arbitrarily large integer class.
const String & getDefaultMidiOutputName() const noexcept
Deprecated.
This struct contains information about a MIDI input or output device.
Represents a type of audio driver, such as DirectSound, ASIO, CoreAudio, etc.
Holds a list of ChangeListeners, and sends messages to them when instructed.
String inputDeviceName
The name of the audio device used for input.
Holds a resizable array of primitive or copy-by-value objects.
Definition: juce_Array.h:59
Base class for an audio device with synchronised input and output channels.
This structure holds a set of properties describing the current audio setup.
Receives incoming messages from a physical MIDI input device.
Maintains an ongoing measurement of the proportion of time which is being spent inside an audio callb...
A re-entrant mutex.
Represents a midi output device.
const String & getDefaultMidiOutputIdentifier() const noexcept
Returns the name of the default midi output.
MidiOutput * getDefaultMidiOutput() const noexcept
Returns the current default midi output device.
An array designed for holding objects.
A base class which provides methods for reference-counting.
A simple reference-counted struct that holds a level-meter value that can be read using getCurrentLev...
Manages the state of some audio and midi i/o devices.
LevelMeter::Ptr getInputLevelGetter() noexcept
Returns a reference-counted object that can be used to get the current input level.