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.

532 lines
24KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. #ifndef JUCE_AUDIODEVICEMANAGER_H_INCLUDED
  24. #define JUCE_AUDIODEVICEMANAGER_H_INCLUDED
  25. //==============================================================================
  26. /**
  27. Manages the state of some audio and midi i/o devices.
  28. This class keeps tracks of a currently-selected audio device, through
  29. with which it continuously streams data from an audio callback, as well as
  30. one or more midi inputs.
  31. The idea is that your application will create one global instance of this object,
  32. and let it take care of creating and deleting specific types of audio devices
  33. internally. So when the device is changed, your callbacks will just keep running
  34. without having to worry about this.
  35. The manager can save and reload all of its device settings as XML, which
  36. makes it very easy for you to save and reload the audio setup of your
  37. application.
  38. And to make it easy to let the user change its settings, there's a component
  39. to do just that - the AudioDeviceSelectorComponent class, which contains a set of
  40. device selection/sample-rate/latency controls.
  41. To use an AudioDeviceManager, create one, and use initialise() to set it up. Then
  42. call addAudioCallback() to register your audio callback with it, and use that to process
  43. your audio data.
  44. The manager also acts as a handy hub for incoming midi messages, allowing a
  45. listener to register for messages from either a specific midi device, or from whatever
  46. the current default midi input device is. The listener then doesn't have to worry about
  47. re-registering with different midi devices if they are changed or deleted.
  48. And yet another neat trick is that amount of CPU time being used is measured and
  49. available with the getCpuUsage() method.
  50. The AudioDeviceManager is a ChangeBroadcaster, and will send a change message to
  51. listeners whenever one of its settings is changed.
  52. @see AudioDeviceSelectorComponent, AudioIODevice, AudioIODeviceType
  53. */
  54. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  55. {
  56. public:
  57. //==============================================================================
  58. /** Creates a default AudioDeviceManager.
  59. Initially no audio device will be selected. You should call the initialise() method
  60. and register an audio callback with setAudioCallback() before it'll be able to
  61. actually make any noise.
  62. */
  63. AudioDeviceManager();
  64. /** Destructor. */
  65. ~AudioDeviceManager();
  66. //==============================================================================
  67. /**
  68. This structure holds a set of properties describing the current audio setup.
  69. An AudioDeviceManager uses this class to save/load its current settings, and to
  70. specify your preferred options when opening a device.
  71. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  72. */
  73. struct JUCE_API AudioDeviceSetup
  74. {
  75. /** Creates an AudioDeviceSetup object.
  76. The default constructor sets all the member variables to indicate default values.
  77. You can then fill-in any values you want to before passing the object to
  78. AudioDeviceManager::initialise().
  79. */
  80. AudioDeviceSetup();
  81. bool operator== (const AudioDeviceSetup& other) const;
  82. /** The name of the audio device used for output.
  83. The name has to be one of the ones listed by the AudioDeviceManager's currently
  84. selected device type.
  85. This may be the same as the input device.
  86. An empty string indicates the default device.
  87. */
  88. String outputDeviceName;
  89. /** The name of the audio device used for input.
  90. This may be the same as the output device.
  91. An empty string indicates the default device.
  92. */
  93. String inputDeviceName;
  94. /** The current sample rate.
  95. This rate is used for both the input and output devices.
  96. A value of 0 indicates that you don't care what rate is used, and the
  97. device will choose a sensible rate for you.
  98. */
  99. double sampleRate;
  100. /** The buffer size, in samples.
  101. This buffer size is used for both the input and output devices.
  102. A value of 0 indicates the default buffer size.
  103. */
  104. int bufferSize;
  105. /** The set of active input channels.
  106. The bits that are set in this array indicate the channels of the
  107. input device that are active.
  108. If useDefaultInputChannels is true, this value is ignored.
  109. */
  110. BigInteger inputChannels;
  111. /** If this is true, it indicates that the inputChannels array
  112. should be ignored, and instead, the device's default channels
  113. should be used.
  114. */
  115. bool useDefaultInputChannels;
  116. /** The set of active output channels.
  117. The bits that are set in this array indicate the channels of the
  118. input device that are active.
  119. If useDefaultOutputChannels is true, this value is ignored.
  120. */
  121. BigInteger outputChannels;
  122. /** If this is true, it indicates that the outputChannels array
  123. should be ignored, and instead, the device's default channels
  124. should be used.
  125. */
  126. bool useDefaultOutputChannels;
  127. };
  128. //==============================================================================
  129. /** Opens a set of audio devices ready for use.
  130. This will attempt to open either a default audio device, or one that was
  131. previously saved as XML.
  132. @param numInputChannelsNeeded the maximum number of input channels your app would like to
  133. use (the actual number of channels opened may be less than
  134. the number requested)
  135. @param numOutputChannelsNeeded the maximum number of output channels your app would like to
  136. use (the actual number of channels opened may be less than
  137. the number requested)
  138. @param savedState either a previously-saved state that was produced
  139. by createStateXml(), or nullptr if you want the manager
  140. to choose the best device to open.
  141. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  142. fails to open, then a default device will be used
  143. instead. If false, then on failure, no device is
  144. opened.
  145. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  146. name, then that will be used as the default device
  147. (assuming that there wasn't one specified in the XML).
  148. The string can actually be a simple wildcard, containing "*"
  149. and "?" characters
  150. @param preferredSetupOptions if this is non-null, the structure will be used as the
  151. set of preferred settings when opening the device. If you
  152. use this parameter, the preferredDefaultDeviceName
  153. field will be ignored
  154. @returns an error message if anything went wrong, or an empty string if it worked ok.
  155. */
  156. String initialise (int numInputChannelsNeeded,
  157. int numOutputChannelsNeeded,
  158. const XmlElement* savedState,
  159. bool selectDefaultDeviceOnFailure,
  160. const String& preferredDefaultDeviceName = String(),
  161. const AudioDeviceSetup* preferredSetupOptions = nullptr);
  162. /** Resets everything to a default device setup, clearing any stored settings. */
  163. String initialiseWithDefaultDevices (int numInputChannelsNeeded,
  164. int numOutputChannelsNeeded);
  165. /** Returns some XML representing the current state of the manager.
  166. This stores the current device, its samplerate, block size, etc, and
  167. can be restored later with initialise().
  168. Note that this can return a null pointer if no settings have been explicitly changed
  169. (i.e. if the device manager has just been left in its default state).
  170. */
  171. XmlElement* createStateXml() const;
  172. //==============================================================================
  173. /** Returns the current device properties that are in use.
  174. @see setAudioDeviceSetup
  175. */
  176. void getAudioDeviceSetup (AudioDeviceSetup& result) const;
  177. /** Changes the current device or its settings.
  178. If you want to change a device property, like the current sample rate or
  179. block size, you can call getAudioDeviceSetup() to retrieve the current
  180. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  181. and pass it back into this method to apply the new settings.
  182. @param newSetup the settings that you'd like to use
  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,
  194. bool treatAsChosenDevice);
  195. /** Returns the currently-active audio device. */
  196. AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice; }
  197. /** Returns the type of audio device currently in use.
  198. @see setCurrentAudioDeviceType
  199. */
  200. String getCurrentAudioDeviceType() const { return currentDeviceType; }
  201. /** Returns the currently active audio device type object.
  202. Don't keep a copy of this pointer - it's owned by the device manager and could
  203. change at any time.
  204. */
  205. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  206. /** Changes the class of audio device being used.
  207. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  208. this because there's only one type: CoreAudio.
  209. For a list of types, see getAvailableDeviceTypes().
  210. */
  211. void setCurrentAudioDeviceType (const String& type,
  212. bool treatAsChosenDevice);
  213. /** Closes the currently-open device.
  214. You can call restartLastAudioDevice() later to reopen it in the same state
  215. that it was just in.
  216. */
  217. void closeAudioDevice();
  218. /** Tries to reload the last audio device that was running.
  219. Note that this only reloads the last device that was running before
  220. closeAudioDevice() was called - it doesn't reload any kind of saved-state,
  221. and can only be called after a device has been opened with SetAudioDevice().
  222. If a device is already open, this call will do nothing.
  223. */
  224. void restartLastAudioDevice();
  225. //==============================================================================
  226. /** Registers an audio callback to be used.
  227. The manager will redirect callbacks from whatever audio device is currently
  228. in use to all registered callback objects. If more than one callback is
  229. active, they will all be given the same input data, and their outputs will
  230. be summed.
  231. If necessary, this method will invoke audioDeviceAboutToStart() on the callback
  232. object before returning.
  233. To remove a callback, use removeAudioCallback().
  234. */
  235. void addAudioCallback (AudioIODeviceCallback* newCallback);
  236. /** Deregisters a previously added callback.
  237. If necessary, this method will invoke audioDeviceStopped() on the callback
  238. object before returning.
  239. @see addAudioCallback
  240. */
  241. void removeAudioCallback (AudioIODeviceCallback* callback);
  242. //==============================================================================
  243. /** Returns the average proportion of available CPU being spent inside the audio callbacks.
  244. @returns A value between 0 and 1.0 to indicate the approximate proportion of CPU
  245. time spent in the callbacks.
  246. */
  247. double getCpuUsage() const;
  248. //==============================================================================
  249. /** Enables or disables a midi input device.
  250. The list of devices can be obtained with the MidiInput::getDevices() method.
  251. Any incoming messages from enabled input devices will be forwarded on to all the
  252. listeners that have been registered with the addMidiInputCallback() method. They
  253. can either register for messages from a particular device, or from just the
  254. "default" midi input.
  255. Routing the midi input via an AudioDeviceManager means that when a listener
  256. registers for the default midi input, this default device can be changed by the
  257. manager without the listeners having to know about it or re-register.
  258. It also means that a listener can stay registered for a midi input that is disabled
  259. or not present, so that when the input is re-enabled, the listener will start
  260. receiving messages again.
  261. @see addMidiInputCallback, isMidiInputEnabled
  262. */
  263. void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
  264. /** Returns true if a given midi input device is being used.
  265. @see setMidiInputEnabled
  266. */
  267. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  268. /** Registers a listener for callbacks when midi events arrive from a midi input.
  269. The device name can be empty to indicate that it wants to receive all incoming
  270. events from all the enabled MIDI inputs. Or it can be the name of one of the
  271. MIDI input devices if it just wants the events from that device. (see
  272. MidiInput::getDevices() for the list of device names).
  273. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  274. events forwarded on to listeners.
  275. */
  276. void addMidiInputCallback (const String& midiInputDeviceName,
  277. MidiInputCallback* callback);
  278. /** Removes a listener that was previously registered with addMidiInputCallback(). */
  279. void removeMidiInputCallback (const String& midiInputDeviceName,
  280. MidiInputCallback* callback);
  281. //==============================================================================
  282. /** Sets a midi output device to use as the default.
  283. The list of devices can be obtained with the MidiOutput::getDevices() method.
  284. The specified device will be opened automatically and can be retrieved with the
  285. getDefaultMidiOutput() method.
  286. Pass in an empty string to deselect all devices. For the default device, you
  287. can use MidiOutput::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  288. @see getDefaultMidiOutput, getDefaultMidiOutputName
  289. */
  290. void setDefaultMidiOutput (const String& deviceName);
  291. /** Returns the name of the default midi output.
  292. @see setDefaultMidiOutput, getDefaultMidiOutput
  293. */
  294. const String& getDefaultMidiOutputName() const noexcept { return defaultMidiOutputName; }
  295. /** Returns the current default midi output device.
  296. If no device has been selected, or the device can't be opened, this will return nullptr.
  297. @see getDefaultMidiOutputName
  298. */
  299. MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput; }
  300. /** Returns a list of the types of device supported. */
  301. const OwnedArray<AudioIODeviceType>& getAvailableDeviceTypes();
  302. //==============================================================================
  303. /** Creates a list of available types.
  304. This will add a set of new AudioIODeviceType objects to the specified list, to
  305. represent each available types of device.
  306. You can override this if your app needs to do something specific, like avoid
  307. using DirectSound devices, etc.
  308. */
  309. virtual void createAudioDeviceTypes (OwnedArray<AudioIODeviceType>& types);
  310. /** Adds a new device type to the list of types.
  311. The manager will take ownership of the object that is passed-in.
  312. */
  313. void addAudioDeviceType (AudioIODeviceType* newDeviceType);
  314. //==============================================================================
  315. /** Plays a beep through the current audio device.
  316. This is here to allow the audio setup UI panels to easily include a "test"
  317. button so that the user can check where the audio is coming from.
  318. */
  319. void playTestSound();
  320. //==============================================================================
  321. /** Turns on level-measuring for input channels.
  322. @see getCurrentInputLevel()
  323. */
  324. void enableInputLevelMeasurement (bool enableMeasurement) noexcept;
  325. /** Turns on level-measuring for output channels.
  326. @see getCurrentOutputLevel()
  327. */
  328. void enableOutputLevelMeasurement (bool enableMeasurement) noexcept;
  329. /** Returns the current input level.
  330. To use this, you must first enable it by calling enableInputLevelMeasurement().
  331. @see enableInputLevelMeasurement()
  332. */
  333. double getCurrentInputLevel() const noexcept;
  334. /** Returns the current output level.
  335. To use this, you must first enable it by calling enableOutputLevelMeasurement().
  336. @see enableOutputLevelMeasurement()
  337. */
  338. double getCurrentOutputLevel() const noexcept;
  339. /** Returns the a lock that can be used to synchronise access to the audio callback.
  340. Obviously while this is locked, you're blocking the audio thread from running, so
  341. it must only be used for very brief periods when absolutely necessary.
  342. */
  343. CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
  344. /** Returns the a lock that can be used to synchronise access to the midi callback.
  345. Obviously while this is locked, you're blocking the midi system from running, so
  346. it must only be used for very brief periods when absolutely necessary.
  347. */
  348. CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
  349. private:
  350. //==============================================================================
  351. OwnedArray<AudioIODeviceType> availableDeviceTypes;
  352. OwnedArray<AudioDeviceSetup> lastDeviceTypeConfigs;
  353. AudioDeviceSetup currentSetup;
  354. ScopedPointer<AudioIODevice> currentAudioDevice;
  355. Array<AudioIODeviceCallback*> callbacks;
  356. int numInputChansNeeded, numOutputChansNeeded;
  357. String currentDeviceType;
  358. BigInteger inputChannels, outputChannels;
  359. ScopedPointer<XmlElement> lastExplicitSettings;
  360. mutable bool listNeedsScanning;
  361. AudioSampleBuffer tempBuffer;
  362. struct MidiCallbackInfo
  363. {
  364. String deviceName;
  365. MidiInputCallback* callback;
  366. };
  367. StringArray midiInsFromXml;
  368. OwnedArray<MidiInput> enabledMidiInputs;
  369. Array<MidiCallbackInfo> midiCallbacks;
  370. String defaultMidiOutputName;
  371. ScopedPointer<MidiOutput> defaultMidiOutput;
  372. CriticalSection audioCallbackLock, midiCallbackLock;
  373. ScopedPointer<AudioSampleBuffer> testSound;
  374. int testSoundPosition;
  375. double cpuUsageMs, timeToCpuScale;
  376. struct LevelMeter
  377. {
  378. LevelMeter() noexcept;
  379. void updateLevel (const float* const*, int numChannels, int numSamples) noexcept;
  380. void setEnabled (bool) noexcept;
  381. double getCurrentLevel() const noexcept;
  382. Atomic<int> enabled;
  383. double level;
  384. };
  385. LevelMeter inputLevelMeter, outputLevelMeter;
  386. //==============================================================================
  387. class CallbackHandler;
  388. friend class CallbackHandler;
  389. friend struct ContainerDeletePolicy<CallbackHandler>;
  390. ScopedPointer<CallbackHandler> callbackHandler;
  391. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  392. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  393. void audioDeviceAboutToStartInt (AudioIODevice*);
  394. void audioDeviceStoppedInt();
  395. void audioDeviceErrorInt (const String&);
  396. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  397. void audioDeviceListChanged();
  398. String restartDevice (int blockSizeToUse, double sampleRateToUse,
  399. const BigInteger& ins, const BigInteger& outs);
  400. void stopDevice();
  401. void updateXml();
  402. void createDeviceTypesIfNeeded();
  403. void scanDevicesIfNeeded();
  404. void deleteCurrentDevice();
  405. double chooseBestSampleRate (double preferred) const;
  406. int chooseBestBufferSize (int preferred) const;
  407. void insertDefaultDeviceNames (AudioDeviceSetup&) const;
  408. String initialiseDefault (const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
  409. String initialiseFromXML (const XmlElement&, bool selectDefaultDeviceOnFailure,
  410. const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
  411. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  412. AudioIODeviceType* findType (const String& typeName);
  413. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager)
  414. };
  415. #endif // JUCE_AUDIODEVICEMANAGER_H_INCLUDED