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.

juce_AudioDeviceManager.h 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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. */
  75. String outputDeviceName;
  76. /** The name of the audio device used for input.
  77. This may be the same as the output device.
  78. */
  79. String inputDeviceName;
  80. /** The current sample rate.
  81. This rate is used for both the input and output devices.
  82. A value of 0 indicates that you don't care what rate is used, and the
  83. device will choose a sensible rate for you.
  84. */
  85. double sampleRate = 0;
  86. /** The buffer size, in samples.
  87. This buffer size is used for both the input and output devices.
  88. A value of 0 indicates the default buffer size.
  89. */
  90. int bufferSize = 0;
  91. /** The set of active input channels.
  92. The bits that are set in this array indicate the channels of the
  93. input device that are active.
  94. If useDefaultInputChannels is true, this value is ignored.
  95. */
  96. BigInteger inputChannels;
  97. /** If this is true, it indicates that the inputChannels array
  98. should be ignored, and instead, the device's default channels
  99. should be used.
  100. */
  101. bool useDefaultInputChannels = true;
  102. /** The set of active output channels.
  103. The bits that are set in this array indicate the channels of the
  104. input device that are active.
  105. If useDefaultOutputChannels is true, this value is ignored.
  106. */
  107. BigInteger outputChannels;
  108. /** If this is true, it indicates that the outputChannels array
  109. should be ignored, and instead, the device's default channels
  110. should be used.
  111. */
  112. bool useDefaultOutputChannels = true;
  113. bool operator== (const AudioDeviceSetup&) const;
  114. bool operator!= (const AudioDeviceSetup&) const;
  115. };
  116. //==============================================================================
  117. /** Opens a set of audio devices ready for use.
  118. This will attempt to open either a default audio device, or one that was
  119. previously saved as XML.
  120. @param numInputChannelsNeeded the maximum number of input channels your app would like to
  121. use (the actual number of channels opened may be less than
  122. the number requested)
  123. @param numOutputChannelsNeeded the maximum number of output channels your app would like to
  124. use (the actual number of channels opened may be less than
  125. the number requested)
  126. @param savedState either a previously-saved state that was produced
  127. by createStateXml(), or nullptr if you want the manager
  128. to choose the best device to open.
  129. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  130. fails to open, then a default device will be used
  131. instead. If false, then on failure, no device is
  132. opened.
  133. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  134. name, then that will be used as the default device
  135. (assuming that there wasn't one specified in the XML).
  136. The string can actually be a simple wildcard, containing "*"
  137. and "?" characters
  138. @param preferredSetupOptions if this is non-null, the structure will be used as the
  139. set of preferred settings when opening the device. If you
  140. use this parameter, the preferredDefaultDeviceName
  141. field will be ignored. If you set the outputDeviceName
  142. or inputDeviceName data members of the AudioDeviceSetup
  143. to empty strings, then a default device will be used.
  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. If you don't need an input or output device, set the
  180. inputDeviceName or outputDeviceName data members respectively
  181. to empty strings. Note that this behaviour differs from
  182. the behaviour of initialise().
  183. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  184. settings will be taken as having been explicitly chosen by the
  185. user, and the next time createStateXml() is called, these settings
  186. will be returned. If it's false, then the device is treated as a
  187. temporary or default device, and a call to createStateXml() will
  188. return either the last settings that were made with treatAsChosenDevice
  189. as true, or the last XML settings that were passed into initialise().
  190. @returns an error message if anything went wrong, or an empty string if it worked ok.
  191. @see getAudioDeviceSetup
  192. */
  193. String setAudioDeviceSetup (const AudioDeviceSetup& newSetup, bool treatAsChosenDevice);
  194. /** Returns the currently-active audio device. */
  195. AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice.get(); }
  196. /** Returns the type of audio device currently in use.
  197. @see setCurrentAudioDeviceType
  198. */
  199. String getCurrentAudioDeviceType() const { return currentDeviceType; }
  200. /** Returns the currently active audio device type object.
  201. Don't keep a copy of this pointer - it's owned by the device manager and could
  202. change at any time.
  203. */
  204. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  205. /** Changes the class of audio device being used.
  206. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  207. this because there's only one type: CoreAudio.
  208. For a list of types, see getAvailableDeviceTypes().
  209. */
  210. void setCurrentAudioDeviceType (const String& type, bool treatAsChosenDevice);
  211. /** Closes the currently-open device.
  212. You can call restartLastAudioDevice() later to reopen it in the same state
  213. that it was just in.
  214. */
  215. void closeAudioDevice();
  216. /** Tries to reload the last audio device that was running.
  217. Note that this only reloads the last device that was running before
  218. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  219. and can only be called after a device has been opened with setAudioDeviceSetup().
  220. If a device is already open, this call will do nothing.
  221. */
  222. void restartLastAudioDevice();
  223. //==============================================================================
  224. /** Registers an audio callback to be used.
  225. The manager will redirect callbacks from whatever audio device is currently
  226. in use to all registered callback objects. If more than one callback is
  227. active, they will all be given the same input data, and their outputs will
  228. be summed.
  229. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  230. object before returning.
  231. To remove a callback, use removeAudioCallback().
  232. */
  233. void addAudioCallback (AudioIODeviceCallback* newCallback);
  234. /** Deregisters a previously added callback.
  235. If necessary, this method will invoke audioDeviceStopped() on the callback
  236. object before returning.
  237. @see addAudioCallback
  238. */
  239. void removeAudioCallback (AudioIODeviceCallback* callback);
  240. //==============================================================================
  241. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  242. @returns A value between 0 and 1.0 to indicate the approximate proportion of CPU
  243. time spent in the callbacks.
  244. */
  245. double getCpuUsage() const;
  246. //==============================================================================
  247. /** Enables or disables a midi input device.
  248. The list of devices can be obtained with the MidiInput::getAvailableDevices() method.
  249. Any incoming messages from enabled input devices will be forwarded on to all the
  250. listeners that have been registered with the addMidiInputDeviceCallback() method. They
  251. can either register for messages from a particular device, or from just the "default"
  252. midi input.
  253. Routing the midi input via an AudioDeviceManager means that when a listener
  254. registers for the default midi input, this default device can be changed by the
  255. manager without the listeners having to know about it or re-register.
  256. It also means that a listener can stay registered for a midi input that is disabled
  257. or not present, so that when the input is re-enabled, the listener will start
  258. receiving messages again.
  259. @see addMidiInputDeviceCallback, isMidiInputDeviceEnabled
  260. */
  261. void setMidiInputDeviceEnabled (const String& deviceIdentifier, bool enabled);
  262. /** Returns true if a given midi input device is being used.
  263. @see setMidiInputDeviceEnabled
  264. */
  265. bool isMidiInputDeviceEnabled (const String& deviceIdentifier) const;
  266. /** Registers a listener for callbacks when midi events arrive from a midi input.
  267. The device identifier can be empty to indicate that it wants to receive all incoming
  268. events from all the enabled MIDI inputs. Or it can be the identifier of one of the
  269. MIDI input devices if it just wants the events from that device. (see
  270. MidiInput::getAvailableDevices() for the list of devices).
  271. Only devices which are enabled (see the setMidiInputDeviceEnabled() method) will have their
  272. events forwarded on to listeners.
  273. */
  274. void addMidiInputDeviceCallback (const String& deviceIdentifier,
  275. MidiInputCallback* callback);
  276. /** Removes a listener that was previously registered with addMidiInputDeviceCallback(). */
  277. void removeMidiInputDeviceCallback (const String& deviceIdentifier,
  278. MidiInputCallback* callback);
  279. //==============================================================================
  280. /** Sets a midi output device to use as the default.
  281. The list of devices can be obtained with the MidiOutput::getAvailableDevices() method.
  282. The specified device will be opened automatically and can be retrieved with the
  283. getDefaultMidiOutput() method.
  284. Pass in an empty string to deselect all devices. For the default device, you
  285. can use MidiOutput::getDefaultDevice().
  286. @see getDefaultMidiOutput, getDefaultMidiOutputIdentifier
  287. */
  288. void setDefaultMidiOutputDevice (const String& deviceIdentifier);
  289. /** Returns the name of the default midi output.
  290. @see setDefaultMidiOutputDevice, getDefaultMidiOutput
  291. */
  292. const String& getDefaultMidiOutputIdentifier() const noexcept { return defaultMidiOutputDeviceInfo.identifier; }
  293. /** Returns the current default midi output device. If no device has been selected, or the
  294. device can't be opened, this will return nullptr.
  295. @see getDefaultMidiOutputIdentifier
  296. */
  297. MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput.get(); }
  298. //==============================================================================
  299. /** Returns a list of the types of device supported. */
  300. const OwnedArray<AudioIODeviceType>& getAvailableDeviceTypes();
  301. /** Creates a list of available types.
  302. This will add a set of new AudioIODeviceType objects to the specified list, to
  303. represent each available types of device.
  304. You can override this if your app needs to do something specific, like avoid
  305. using DirectSound devices, etc.
  306. */
  307. virtual void createAudioDeviceTypes (OwnedArray<AudioIODeviceType>& types);
  308. /** Adds a new device type to the list of types. */
  309. void addAudioDeviceType (std::unique_ptr<AudioIODeviceType> newDeviceType);
  310. /** Removes a previously added device type from the manager. */
  311. void removeAudioDeviceType (AudioIODeviceType* deviceTypeToRemove);
  312. //==============================================================================
  313. /** Plays a beep through the current audio device.
  314. This is here to allow the audio setup UI panels to easily include a "test"
  315. button so that the user can check where the audio is coming from.
  316. */
  317. void playTestSound();
  318. //==============================================================================
  319. /**
  320. A simple reference-counted struct that holds a level-meter value that can be read
  321. using getCurrentLevel().
  322. This is used to ensure that the level processing code is only executed when something
  323. holds a reference to one of these objects and will be bypassed otherwise.
  324. @see getInputLevelGetter, getOutputLevelGetter
  325. */
  326. struct LevelMeter : public ReferenceCountedObject
  327. {
  328. LevelMeter() noexcept;
  329. double getCurrentLevel() const noexcept;
  330. using Ptr = ReferenceCountedObjectPtr<LevelMeter>;
  331. private:
  332. friend class AudioDeviceManager;
  333. Atomic<float> level { 0 };
  334. void updateLevel (const float* const*, int numChannels, int numSamples) noexcept;
  335. };
  336. /** Returns a reference-counted object that can be used to get the current input level.
  337. You need to store this object locally to ensure that the reference count is incremented
  338. and decremented properly. The current input level value can be read using getCurrentLevel().
  339. */
  340. LevelMeter::Ptr getInputLevelGetter() noexcept { return inputLevelGetter; }
  341. /** Returns a reference-counted object that can be used to get the current output level.
  342. You need to store this object locally to ensure that the reference count is incremented
  343. and decremented properly. The current output level value can be read using getCurrentLevel().
  344. */
  345. LevelMeter::Ptr getOutputLevelGetter() noexcept { return outputLevelGetter; }
  346. //==============================================================================
  347. /** Returns the a lock that can be used to synchronise access to the audio callback.
  348. Obviously while this is locked, you're blocking the audio thread from running, so
  349. it must only be used for very brief periods when absolutely necessary.
  350. */
  351. CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
  352. /** Returns the a lock that can be used to synchronise access to the midi callback.
  353. Obviously while this is locked, you're blocking the midi system from running, so
  354. it must only be used for very brief periods when absolutely necessary.
  355. */
  356. CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
  357. //==============================================================================
  358. /** Returns the number of under- or over runs reported.
  359. This method will use the underlying device's native getXRunCount if it supports
  360. it. Otherwise it will estimate the number of under-/overruns by measuring the
  361. time it spent in the audio callback.
  362. */
  363. int getXRunCount() const noexcept;
  364. //==============================================================================
  365. #ifndef DOXYGEN
  366. [[deprecated ("Use setMidiInputDeviceEnabled instead.")]]
  367. void setMidiInputEnabled (const String&, bool);
  368. [[deprecated ("Use isMidiInputDeviceEnabled instead.")]]
  369. bool isMidiInputEnabled (const String&) const;
  370. [[deprecated ("Use addMidiInputDeviceCallback instead.")]]
  371. void addMidiInputCallback (const String&, MidiInputCallback*);
  372. [[deprecated ("Use removeMidiInputDeviceCallback instead.")]]
  373. void removeMidiInputCallback (const String&, MidiInputCallback*);
  374. [[deprecated ("Use setDefaultMidiOutputDevice instead.")]]
  375. void setDefaultMidiOutput (const String&);
  376. [[deprecated ("Use getDefaultMidiOutputIdentifier instead.")]]
  377. const String& getDefaultMidiOutputName() const noexcept { return defaultMidiOutputDeviceInfo.name; }
  378. #endif
  379. private:
  380. //==============================================================================
  381. OwnedArray<AudioIODeviceType> availableDeviceTypes;
  382. OwnedArray<AudioDeviceSetup> lastDeviceTypeConfigs;
  383. AudioDeviceSetup currentSetup;
  384. std::unique_ptr<AudioIODevice> currentAudioDevice;
  385. Array<AudioIODeviceCallback*> callbacks;
  386. int numInputChansNeeded = 0, numOutputChansNeeded = 2;
  387. String preferredDeviceName, currentDeviceType;
  388. std::unique_ptr<XmlElement> lastExplicitSettings;
  389. mutable bool listNeedsScanning = true;
  390. AudioBuffer<float> tempBuffer;
  391. struct MidiCallbackInfo
  392. {
  393. String deviceIdentifier;
  394. MidiInputCallback* callback;
  395. };
  396. Array<MidiDeviceInfo> midiDeviceInfosFromXml;
  397. std::vector<std::unique_ptr<MidiInput>> enabledMidiInputs;
  398. Array<MidiCallbackInfo> midiCallbacks;
  399. MidiDeviceInfo defaultMidiOutputDeviceInfo;
  400. std::unique_ptr<MidiOutput> defaultMidiOutput;
  401. CriticalSection audioCallbackLock, midiCallbackLock;
  402. std::unique_ptr<AudioBuffer<float>> testSound;
  403. int testSoundPosition = 0;
  404. AudioProcessLoadMeasurer loadMeasurer;
  405. LevelMeter::Ptr inputLevelGetter { new LevelMeter() },
  406. outputLevelGetter { new LevelMeter() };
  407. //==============================================================================
  408. class CallbackHandler;
  409. std::unique_ptr<CallbackHandler> callbackHandler;
  410. void audioDeviceIOCallbackInt (const float** inputChannelData,
  411. int totalNumInputChannels,
  412. float** outputChannelData,
  413. int totalNumOutputChannels,
  414. int numSamples,
  415. const AudioIODeviceCallbackContext& context);
  416. void audioDeviceAboutToStartInt (AudioIODevice*);
  417. void audioDeviceStoppedInt();
  418. void audioDeviceErrorInt (const String&);
  419. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  420. void audioDeviceListChanged();
  421. String restartDevice (int blockSizeToUse, double sampleRateToUse,
  422. const BigInteger& ins, const BigInteger& outs);
  423. void stopDevice();
  424. void updateXml();
  425. void updateCurrentSetup();
  426. void createDeviceTypesIfNeeded();
  427. void scanDevicesIfNeeded();
  428. void deleteCurrentDevice();
  429. double chooseBestSampleRate (double preferred) const;
  430. int chooseBestBufferSize (int preferred) const;
  431. void insertDefaultDeviceNames (AudioDeviceSetup&) const;
  432. String initialiseDefault (const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
  433. String initialiseFromXML (const XmlElement&, bool selectDefaultDeviceOnFailure,
  434. const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
  435. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  436. AudioIODeviceType* findType (const String& typeName);
  437. void pickCurrentDeviceTypeWithDevices();
  438. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager)
  439. };
  440. } // namespace juce