OpenShot Library | libopenshot-audio  0.2.0
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  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::getDevices() 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 addMidiInputCallback() method. They
318  can either register for messages from a particular device, or from just the
319  "default" 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 addMidiInputCallback, isMidiInputEnabled
330  */
331  void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
332 
333  /** Returns true if a given midi input device is being used.
334  @see setMidiInputEnabled
335  */
336  bool isMidiInputEnabled (const String& midiInputDeviceName) const;
337 
338  /** Registers a listener for callbacks when midi events arrive from a midi input.
339 
340  The device name can be empty to indicate that it wants to receive all incoming
341  events from all the enabled MIDI inputs. Or it can be the name of one of the
342  MIDI input devices if it just wants the events from that device. (see
343  MidiInput::getDevices() for the list of device names).
344 
345  Only devices which are enabled (see the setMidiInputEnabled() method) will have their
346  events forwarded on to listeners.
347  */
348  void addMidiInputCallback (const String& midiInputDeviceName,
349  MidiInputCallback* callback);
350 
351  /** Removes a listener that was previously registered with addMidiInputCallback(). */
352  void removeMidiInputCallback (const String& midiInputDeviceName,
353  MidiInputCallback* callback);
354 
355  //==============================================================================
356  /** Sets a midi output device to use as the default.
357 
358  The list of devices can be obtained with the MidiOutput::getDevices() method.
359 
360  The specified device will be opened automatically and can be retrieved with the
361  getDefaultMidiOutput() method.
362 
363  Pass in an empty string to deselect all devices. For the default device, you
364  can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
365 
366  @see getDefaultMidiOutput, getDefaultMidiOutputName
367  */
368  void setDefaultMidiOutput (const String& deviceName);
369 
370  /** Returns the name of the default midi output.
371  @see setDefaultMidiOutput, getDefaultMidiOutput
372  */
373  const String& getDefaultMidiOutputName() const noexcept { return defaultMidiOutputName; }
374 
375  /** Returns the current default midi output device.
376  If no device has been selected, or the device can't be opened, this will return nullptr.
377  @see getDefaultMidiOutputName
378  */
379  MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput.get(); }
380 
381  /** Returns a list of the types of device supported. */
382  const OwnedArray<AudioIODeviceType>& getAvailableDeviceTypes();
383 
384  //==============================================================================
385  /** Creates a list of available types.
386 
387  This will add a set of new AudioIODeviceType objects to the specified list, to
388  represent each available types of device.
389 
390  You can override this if your app needs to do something specific, like avoid
391  using DirectSound devices, etc.
392  */
393  virtual void createAudioDeviceTypes (OwnedArray<AudioIODeviceType>& types);
394 
395  /** Adds a new device type to the list of types.
396  The manager will take ownership of the object that is passed-in.
397  */
398  void addAudioDeviceType (AudioIODeviceType* newDeviceType);
399 
400  //==============================================================================
401  /** Plays a beep through the current audio device.
402 
403  This is here to allow the audio setup UI panels to easily include a "test"
404  button so that the user can check where the audio is coming from.
405  */
406  void playTestSound();
407 
408  //==============================================================================
409  /**
410  A simple reference-counted struct that holds a level-meter value that can be read
411  using getCurrentLevel().
412 
413  This is used to ensure that the level processing code is only executed when something
414  holds a reference to one of these objects and will be bypassed otherwise.
415 
416  @see getInputLevelGetter, getOutputLevelGetter
417  */
419  {
420  LevelMeter() noexcept;
421  double getCurrentLevel() const noexcept;
422 
424 
425  private:
426  friend class AudioDeviceManager;
427 
428  Atomic<float> level { 0 };
429  void updateLevel (const float* const*, int numChannels, int numSamples) noexcept;
430  };
431 
432  /** Returns a reference-counted object that can be used to get the current input level.
433 
434  You need to store this object locally to ensure that the reference count is incremented
435  and decremented properly. The current input level value can be read using getCurrentLevel().
436  */
437  LevelMeter::Ptr getInputLevelGetter() noexcept { return inputLevelGetter; }
438 
439  /** Returns a reference-counted object that can be used to get the current output level.
440 
441  You need to store this object locally to ensure that the reference count is incremented
442  and decremented properly. The current output level value can be read using getCurrentLevel().
443  */
444  LevelMeter::Ptr getOutputLevelGetter() noexcept { return outputLevelGetter; }
445 
446  //==============================================================================
447  /** Returns the a lock that can be used to synchronise access to the audio callback.
448  Obviously while this is locked, you're blocking the audio thread from running, so
449  it must only be used for very brief periods when absolutely necessary.
450  */
451  CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
452 
453  /** Returns the a lock that can be used to synchronise access to the midi callback.
454  Obviously while this is locked, you're blocking the midi system from running, so
455  it must only be used for very brief periods when absolutely necessary.
456  */
457  CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
458 
459  //==============================================================================
460  /** Returns the number of under- or over runs reported.
461 
462  This method will use the underlying device's native getXRunCount if it supports
463  it. Otherwise it will estimate the number of under-/overruns by measuring the
464  time it spent in the audio callback.
465  */
466  int getXRunCount() const noexcept;
467 
468 private:
469  //==============================================================================
470  OwnedArray<AudioIODeviceType> availableDeviceTypes;
471  OwnedArray<AudioDeviceSetup> lastDeviceTypeConfigs;
472 
473  AudioDeviceSetup currentSetup;
474  std::unique_ptr<AudioIODevice> currentAudioDevice;
476  int numInputChansNeeded = 0, numOutputChansNeeded = 2;
477  String preferredDeviceName, currentDeviceType;
478  BigInteger inputChannels, outputChannels;
479  std::unique_ptr<XmlElement> lastExplicitSettings;
480  mutable bool listNeedsScanning = true;
481  AudioBuffer<float> tempBuffer;
482 
483  struct MidiCallbackInfo
484  {
485  String deviceName;
486  MidiInputCallback* callback;
487  };
488 
489  StringArray midiInsFromXml;
490  OwnedArray<MidiInput> enabledMidiInputs;
491  Array<MidiCallbackInfo> midiCallbacks;
492 
493  String defaultMidiOutputName;
494  std::unique_ptr<MidiOutput> defaultMidiOutput;
495  CriticalSection audioCallbackLock, midiCallbackLock;
496 
497  std::unique_ptr<AudioBuffer<float>> testSound;
498  int testSoundPosition = 0;
499 
500  AudioProcessLoadMeasurer loadMeasurer;
501 
502  LevelMeter::Ptr inputLevelGetter { new LevelMeter() },
503  outputLevelGetter { new LevelMeter() };
504 
505  //==============================================================================
506  class CallbackHandler;
507  std::unique_ptr<CallbackHandler> callbackHandler;
508 
509  void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
510  float** outputChannelData, int totalNumOutputChannels, int numSamples);
511  void audioDeviceAboutToStartInt (AudioIODevice*);
512  void audioDeviceStoppedInt();
513  void audioDeviceErrorInt (const String&);
514  void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
515  void audioDeviceListChanged();
516 
517  String restartDevice (int blockSizeToUse, double sampleRateToUse,
518  const BigInteger& ins, const BigInteger& outs);
519  void stopDevice();
520 
521  void updateXml();
522 
523  void createDeviceTypesIfNeeded();
524  void scanDevicesIfNeeded();
525  void deleteCurrentDevice();
526  double chooseBestSampleRate (double preferred) const;
527  int chooseBestBufferSize (int preferred) const;
528  void insertDefaultDeviceNames (AudioDeviceSetup&) const;
529  String initialiseDefault (const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
530  String initialiseFromXML (const XmlElement&, bool selectDefaultDeviceOnFailure,
531  const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
532 
533  AudioIODeviceType* findType (const String& inputName, const String& outputName);
534  AudioIODeviceType* findType (const String& typeName);
535 
536  JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager)
537 };
538 
539 } // namespace juce
540 
541 /** @}*/
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.
A special array for holding a list of strings.
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
Returns the name of the default midi output.
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.
Controls a physical MIDI output device.
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.