Audio plugin host https://kx.studio/carla
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.

553 lines
25KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. //==============================================================================
  20. /**
  21. Manages the state of some audio and midi i/o devices.
  22. This class keeps tracks of a currently-selected audio device, through
  23. with which it continuously streams data from an audio callback, as well as
  24. one or more midi inputs.
  25. The idea is that your application will create one global instance of this object,
  26. and let it take care of creating and deleting specific types of audio devices
  27. internally. So when the device is changed, your callbacks will just keep running
  28. without having to worry about this.
  29. The manager can save and reload all of its device settings as XML, which
  30. makes it very easy for you to save and reload the audio setup of your
  31. application.
  32. And to make it easy to let the user change its settings, there's a component
  33. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  34. device selection/sample-rate/latency controls.
  35. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  36. call addAudioCallback() to register your audio callback with it, and use that to process
  37. your audio data.
  38. The manager also acts as a handy hub for incoming midi messages, allowing a
  39. listener to register for messages from either a specific midi device, or from whatever
  40. the current default midi input device is. The listener then doesn't have to worry about
  41. re-registering with different midi devices if they are changed or deleted.
  42. And yet another neat trick is that amount of CPU time being used is measured and
  43. available with the getCpuUsage() method.
  44. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  45. listeners whenever one of its settings is changed.
  46. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  47. @tags{Audio}
  48. */
  49. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  50. {
  51. public:
  52. //==============================================================================
  53. /** Creates a default AudioDeviceManager.
  54. Initially no audio device will be selected. You should call the initialise() method
  55. and register an audio callback with setAudioCallback() before it'll be able to
  56. actually make any noise.
  57. */
  58. AudioDeviceManager();
  59. /** Destructor. */
  60. ~AudioDeviceManager() override;
  61. //==============================================================================
  62. /**
  63. This structure holds a set of properties describing the current audio setup.
  64. An AudioDeviceManager uses this class to save/load its current settings, and to
  65. specify your preferred options when opening a device.
  66. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  67. */
  68. struct JUCE_API AudioDeviceSetup
  69. {
  70. /** The name of the audio device used for output.
  71. The name has to be one of the ones listed by the AudioDeviceManager's currently
  72. selected device type.
  73. This may be the same as the input device.
  74. An empty string indicates the default device.
  75. */
  76. String outputDeviceName;
  77. /** The name of the audio device used for input.
  78. This may be the same as the output device.
  79. An empty string indicates the default device.
  80. */
  81. String inputDeviceName;
  82. /** The current sample rate.
  83. This rate is used for both the input and output devices.
  84. A value of 0 indicates that you don't care what rate is used, and the
  85. device will choose a sensible rate for you.
  86. */
  87. double sampleRate = 0;
  88. /** The buffer size, in samples.
  89. This buffer size is used for both the input and output devices.
  90. A value of 0 indicates the default buffer size.
  91. */
  92. int bufferSize = 0;
  93. /** The set of active input channels.
  94. The bits that are set in this array indicate the channels of the
  95. input device that are active.
  96. If useDefaultInputChannels is true, this value is ignored.
  97. */
  98. BigInteger inputChannels;
  99. /** If this is true, it indicates that the inputChannels array
  100. should be ignored, and instead, the device's default channels
  101. should be used.
  102. */
  103. bool useDefaultInputChannels = true;
  104. /** The set of active output channels.
  105. The bits that are set in this array indicate the channels of the
  106. input device that are active.
  107. If useDefaultOutputChannels is true, this value is ignored.
  108. */
  109. BigInteger outputChannels;
  110. /** If this is true, it indicates that the outputChannels array
  111. should be ignored, and instead, the device's default channels
  112. should be used.
  113. */
  114. bool useDefaultOutputChannels = true;
  115. bool operator== (const AudioDeviceSetup&) const;
  116. bool operator!= (const AudioDeviceSetup&) const;
  117. };
  118. //==============================================================================
  119. /** Opens a set of audio devices ready for use.
  120. This will attempt to open either a default audio device, or one that was
  121. previously saved as XML.
  122. @param numInputChannelsNeeded the maximum number of input channels your app would like to
  123. use (the actual number of channels opened may be less than
  124. the number requested)
  125. @param numOutputChannelsNeeded the maximum number of output channels your app would like to
  126. use (the actual number of channels opened may be less than
  127. the number requested)
  128. @param savedState either a previously-saved state that was produced
  129. by createStateXml(), or nullptr if you want the manager
  130. to choose the best device to open.
  131. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  132. fails to open, then a default device will be used
  133. instead. If false, then on failure, no device is
  134. opened.
  135. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  136. name, then that will be used as the default device
  137. (assuming that there wasn't one specified in the XML).
  138. The string can actually be a simple wildcard, containing "*"
  139. and "?" characters
  140. @param preferredSetupOptions if this is non-null, the structure will be used as the
  141. set of preferred settings when opening the device. If you
  142. use this parameter, the preferredDefaultDeviceName
  143. field will be ignored
  144. @returns an error message if anything went wrong, or an empty string if it worked ok.
  145. */
  146. String initialise (int numInputChannelsNeeded,
  147. int numOutputChannelsNeeded,
  148. const XmlElement* savedState,
  149. bool selectDefaultDeviceOnFailure,
  150. const String& preferredDefaultDeviceName = String(),
  151. const AudioDeviceSetup* preferredSetupOptions = nullptr);
  152. /** Resets everything to a default device setup, clearing any stored settings. */
  153. String initialiseWithDefaultDevices (int numInputChannelsNeeded,
  154. int numOutputChannelsNeeded);
  155. /** Returns some XML representing the current state of the manager.
  156. This stores the current device, its samplerate, block size, etc, and
  157. can be restored later with initialise().
  158. Note that this can return a null pointer if no settings have been explicitly changed
  159. (i.e. if the device manager has just been left in its default state).
  160. */
  161. std::unique_ptr<XmlElement> createStateXml() const;
  162. //==============================================================================
  163. /** Returns the current device properties that are in use.
  164. @see setAudioDeviceSetup
  165. */
  166. AudioDeviceSetup getAudioDeviceSetup() const;
  167. /** Returns the current device properties that are in use.
  168. This is an old method, kept around for compatibility, but you should prefer the new
  169. version which returns the result rather than taking an out-parameter.
  170. @see getAudioDeviceSetup()
  171. */
  172. void getAudioDeviceSetup (AudioDeviceSetup& result) const;
  173. /** Changes the current device or its settings.
  174. If you want to change a device property, like the current sample rate or
  175. block size, you can call getAudioDeviceSetup() to retrieve the current
  176. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  177. and pass it back into this method to apply the new settings.
  178. @param newSetup the settings that you'd like to use
  179. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  180. settings will be taken as having been explicitly chosen by the
  181. user, and the next time createStateXml() is called, these settings
  182. will be returned. If it's false, then the device is treated as a
  183. temporary or default device, and a call to createStateXml() will
  184. return either the last settings that were made with treatAsChosenDevice
  185. as true, or the last XML settings that were passed into initialise().
  186. @returns an error message if anything went wrong, or an empty string if it worked ok.
  187. @see getAudioDeviceSetup
  188. */
  189. String setAudioDeviceSetup (const AudioDeviceSetup& newSetup, bool treatAsChosenDevice);
  190. /** Returns the currently-active audio device. */
  191. AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice.get(); }
  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, bool treatAsChosenDevice);
  207. /** Closes the currently-open device.
  208. You can call restartLastAudioDevice() later to reopen it in the same state
  209. that it was just in.
  210. */
  211. void closeAudioDevice();
  212. /** Tries to reload the last audio device that was running.
  213. Note that this only reloads the last device that was running before
  214. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  215. and can only be called after a device has been opened with SetAudioDevice().
  216. If a device is already open, this call will do nothing.
  217. */
  218. void restartLastAudioDevice();
  219. //==============================================================================
  220. /** Registers an audio callback to be used.
  221. The manager will redirect callbacks from whatever audio device is currently
  222. in use to all registered callback objects. If more than one callback is
  223. active, they will all be given the same input data, and their outputs will
  224. be summed.
  225. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  226. object before returning.
  227. To remove a callback, use removeAudioCallback().
  228. */
  229. void addAudioCallback (AudioIODeviceCallback* newCallback);
  230. /** Deregisters a previously added callback.
  231. If necessary, this method will invoke audioDeviceStopped() on the callback
  232. object before returning.
  233. @see addAudioCallback
  234. */
  235. void removeAudioCallback (AudioIODeviceCallback* callback);
  236. //==============================================================================
  237. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  238. @returns A value between 0 and 1.0 to indicate the approximate proportion of CPU
  239. time spent in the callbacks.
  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::getAvailableDevices() method.
  245. Any incoming messages from enabled input devices will be forwarded on to all the
  246. listeners that have been registered with the addMidiInputDeviceCallback() method. They
  247. can either register for messages from a particular device, or from just the "default"
  248. 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 addMidiInputDeviceCallback, isMidiInputDeviceEnabled
  256. */
  257. void setMidiInputDeviceEnabled (const String& deviceIdentifier, bool enabled);
  258. /** Returns true if a given midi input device is being used.
  259. @see setMidiInputDeviceEnabled
  260. */
  261. bool isMidiInputDeviceEnabled (const String& deviceIdentifier) const;
  262. /** Registers a listener for callbacks when midi events arrive from a midi input.
  263. The device identifier can be empty to indicate that it wants to receive all incoming
  264. events from all the enabled MIDI inputs. Or it can be the identifier of one of the
  265. MIDI input devices if it just wants the events from that device. (see
  266. MidiInput::getAvailableDevices() for the list of devices).
  267. Only devices which are enabled (see the setMidiInputDeviceEnabled() method) will have their
  268. events forwarded on to listeners.
  269. */
  270. void addMidiInputDeviceCallback (const String& deviceIdentifier,
  271. MidiInputCallback* callback);
  272. /** Removes a listener that was previously registered with addMidiInputDeviceCallback(). */
  273. void removeMidiInputDeviceCallback (const String& deviceIdentifier,
  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::getAvailableDevices() 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::getDefaultDevice().
  282. @see getDefaultMidiOutput, getDefaultMidiOutputIdentifier
  283. */
  284. void setDefaultMidiOutputDevice (const String& deviceIdentifier);
  285. /** Returns the name of the default midi output.
  286. @see setDefaultMidiOutputDevice, getDefaultMidiOutput
  287. */
  288. const String& getDefaultMidiOutputIdentifier() const noexcept { return defaultMidiOutputDeviceInfo.identifier; }
  289. /** Returns the current default midi output device. If no device has been selected, or the
  290. device can't be opened, this will return nullptr.
  291. @see getDefaultMidiOutputIdentifier
  292. */
  293. MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput.get(); }
  294. //==============================================================================
  295. /** Returns a list of the types of device supported. */
  296. const OwnedArray<AudioIODeviceType>& getAvailableDeviceTypes();
  297. /** Creates a list of available types.
  298. This will add a set of new AudioIODeviceType objects to the specified list, to
  299. represent each available types of device.
  300. You can override this if your app needs to do something specific, like avoid
  301. using DirectSound devices, etc.
  302. */
  303. virtual void createAudioDeviceTypes (OwnedArray<AudioIODeviceType>& types);
  304. /** Adds a new device type to the list of types. */
  305. void addAudioDeviceType (std::unique_ptr<AudioIODeviceType> newDeviceType);
  306. /** Removes a previously added device type from the manager. */
  307. void removeAudioDeviceType (AudioIODeviceType* deviceTypeToRemove);
  308. //==============================================================================
  309. /** Plays a beep through the current audio device.
  310. This is here to allow the audio setup UI panels to easily include a "test"
  311. button so that the user can check where the audio is coming from.
  312. */
  313. void playTestSound();
  314. //==============================================================================
  315. /**
  316. A simple reference-counted struct that holds a level-meter value that can be read
  317. using getCurrentLevel().
  318. This is used to ensure that the level processing code is only executed when something
  319. holds a reference to one of these objects and will be bypassed otherwise.
  320. @see getInputLevelGetter, getOutputLevelGetter
  321. */
  322. struct LevelMeter : public ReferenceCountedObject
  323. {
  324. LevelMeter() noexcept;
  325. double getCurrentLevel() const noexcept;
  326. using Ptr = ReferenceCountedObjectPtr<LevelMeter>;
  327. private:
  328. friend class AudioDeviceManager;
  329. Atomic<float> level { 0 };
  330. void updateLevel (const float* const*, int numChannels, int numSamples) noexcept;
  331. };
  332. /** Returns a reference-counted object that can be used to get the current input level.
  333. You need to store this object locally to ensure that the reference count is incremented
  334. and decremented properly. The current input level value can be read using getCurrentLevel().
  335. */
  336. LevelMeter::Ptr getInputLevelGetter() noexcept { return inputLevelGetter; }
  337. /** Returns a reference-counted object that can be used to get the current output level.
  338. You need to store this object locally to ensure that the reference count is incremented
  339. and decremented properly. The current output level value can be read using getCurrentLevel().
  340. */
  341. LevelMeter::Ptr getOutputLevelGetter() noexcept { return outputLevelGetter; }
  342. //==============================================================================
  343. /** Returns the a lock that can be used to synchronise access to the audio callback.
  344. Obviously while this is locked, you're blocking the audio thread from running, so
  345. it must only be used for very brief periods when absolutely necessary.
  346. */
  347. CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
  348. /** Returns the a lock that can be used to synchronise access to the midi callback.
  349. Obviously while this is locked, you're blocking the midi system from running, so
  350. it must only be used for very brief periods when absolutely necessary.
  351. */
  352. CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
  353. //==============================================================================
  354. /** Returns the number of under- or over runs reported.
  355. This method will use the underlying device's native getXRunCount if it supports
  356. it. Otherwise it will estimate the number of under-/overruns by measuring the
  357. time it spent in the audio callback.
  358. */
  359. int getXRunCount() const noexcept;
  360. //==============================================================================
  361. /** Deprecated. */
  362. void setMidiInputEnabled (const String&, bool);
  363. /** Deprecated. */
  364. bool isMidiInputEnabled (const String&) const;
  365. /** Deprecated. */
  366. void addMidiInputCallback (const String&, MidiInputCallback*);
  367. /** Deprecated. */
  368. void removeMidiInputCallback (const String&, MidiInputCallback*);
  369. /** Deprecated. */
  370. void setDefaultMidiOutput (const String&);
  371. /** Deprecated. */
  372. const String& getDefaultMidiOutputName() const noexcept { return defaultMidiOutputDeviceInfo.name; }
  373. private:
  374. //==============================================================================
  375. OwnedArray<AudioIODeviceType> availableDeviceTypes;
  376. OwnedArray<AudioDeviceSetup> lastDeviceTypeConfigs;
  377. AudioDeviceSetup currentSetup;
  378. std::unique_ptr<AudioIODevice> currentAudioDevice;
  379. Array<AudioIODeviceCallback*> callbacks;
  380. int numInputChansNeeded = 0, numOutputChansNeeded = 2;
  381. String preferredDeviceName, currentDeviceType;
  382. std::unique_ptr<XmlElement> lastExplicitSettings;
  383. mutable bool listNeedsScanning = true;
  384. AudioBuffer<float> tempBuffer;
  385. struct MidiCallbackInfo
  386. {
  387. String deviceIdentifier;
  388. MidiInputCallback* callback;
  389. };
  390. Array<MidiDeviceInfo> midiDeviceInfosFromXml;
  391. std::vector<std::unique_ptr<MidiInput>> enabledMidiInputs;
  392. Array<MidiCallbackInfo> midiCallbacks;
  393. MidiDeviceInfo defaultMidiOutputDeviceInfo;
  394. std::unique_ptr<MidiOutput> defaultMidiOutput;
  395. CriticalSection audioCallbackLock, midiCallbackLock;
  396. std::unique_ptr<AudioBuffer<float>> testSound;
  397. int testSoundPosition = 0;
  398. AudioProcessLoadMeasurer loadMeasurer;
  399. LevelMeter::Ptr inputLevelGetter { new LevelMeter() },
  400. outputLevelGetter { new LevelMeter() };
  401. //==============================================================================
  402. class CallbackHandler;
  403. std::unique_ptr<CallbackHandler> callbackHandler;
  404. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  405. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  406. void audioDeviceAboutToStartInt (AudioIODevice*);
  407. void audioDeviceStoppedInt();
  408. void audioDeviceErrorInt (const String&);
  409. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  410. void audioDeviceListChanged();
  411. String restartDevice (int blockSizeToUse, double sampleRateToUse,
  412. const BigInteger& ins, const BigInteger& outs);
  413. void stopDevice();
  414. void updateXml();
  415. void createDeviceTypesIfNeeded();
  416. void scanDevicesIfNeeded();
  417. void deleteCurrentDevice();
  418. double chooseBestSampleRate (double preferred) const;
  419. int chooseBestBufferSize (int preferred) const;
  420. void insertDefaultDeviceNames (AudioDeviceSetup&) const;
  421. String initialiseDefault (const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
  422. String initialiseFromXML (const XmlElement&, bool selectDefaultDeviceOnFailure,
  423. const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
  424. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  425. AudioIODeviceType* findType (const String& typeName);
  426. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager)
  427. };
  428. } // namespace juce