The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

521 lines
23KB

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