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

9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #ifndef JUCE_AUDIODEVICEMANAGER_H_INCLUDED
  18. #define JUCE_AUDIODEVICEMANAGER_H_INCLUDED
  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. */
  48. class JUCE_API AudioDeviceManager : public ChangeBroadcaster
  49. {
  50. public:
  51. //==============================================================================
  52. /** Creates a default AudioDeviceManager.
  53. Initially no audio device will be selected. You should call the initialise() method
  54. and register an audio callback with setAudioCallback() before it'll be able to
  55. actually make any noise.
  56. */
  57. AudioDeviceManager();
  58. /** Destructor. */
  59. ~AudioDeviceManager();
  60. //==============================================================================
  61. /**
  62. This structure holds a set of properties describing the current audio setup.
  63. An AudioDeviceManager uses this class to save/load its current settings, and to
  64. specify your preferred options when opening a device.
  65. @see AudioDeviceManager::setAudioDeviceSetup(), AudioDeviceManager::initialise()
  66. */
  67. struct JUCE_API AudioDeviceSetup
  68. {
  69. /** Creates an AudioDeviceSetup object.
  70. The default constructor sets all the member variables to indicate default values.
  71. You can then fill-in any values you want to before passing the object to
  72. AudioDeviceManager::initialise().
  73. */
  74. AudioDeviceSetup();
  75. bool operator== (const AudioDeviceSetup& other) const;
  76. /** The name of the audio device used for output.
  77. The name has to be one of the ones listed by the AudioDeviceManager's currently
  78. selected device type.
  79. This may be the same as the input device.
  80. An empty string indicates the default device.
  81. */
  82. String outputDeviceName;
  83. /** The name of the audio device used for input.
  84. This may be the same as the output device.
  85. An empty string indicates the default device.
  86. */
  87. String inputDeviceName;
  88. /** The current sample rate.
  89. This rate is used for both the input and output devices.
  90. A value of 0 indicates that you don't care what rate is used, and the
  91. device will choose a sensible rate for you.
  92. */
  93. double sampleRate;
  94. /** The buffer size, in samples.
  95. This buffer size is used for both the input and output devices.
  96. A value of 0 indicates the default buffer size.
  97. */
  98. int bufferSize;
  99. /** The set of active input channels.
  100. The bits that are set in this array indicate the channels of the
  101. input device that are active.
  102. If useDefaultInputChannels is true, this value is ignored.
  103. */
  104. BigInteger inputChannels;
  105. /** If this is true, it indicates that the inputChannels array
  106. should be ignored, and instead, the device's default channels
  107. should be used.
  108. */
  109. bool useDefaultInputChannels;
  110. /** The set of active output channels.
  111. The bits that are set in this array indicate the channels of the
  112. input device that are active.
  113. If useDefaultOutputChannels is true, this value is ignored.
  114. */
  115. BigInteger outputChannels;
  116. /** If this is true, it indicates that the outputChannels array
  117. should be ignored, and instead, the device's default channels
  118. should be used.
  119. */
  120. bool useDefaultOutputChannels;
  121. };
  122. //==============================================================================
  123. /** Opens a set of audio devices ready for use.
  124. This will attempt to open either a default audio device, or one that was
  125. previously saved as XML.
  126. @param numInputChannelsNeeded the maximum number of input channels your app would like to
  127. use (the actual number of channels opened may be less than
  128. the number requested)
  129. @param numOutputChannelsNeeded the maximum number of output channels your app would like to
  130. use (the actual number of channels opened may be less than
  131. the number requested)
  132. @param savedState either a previously-saved state that was produced
  133. by createStateXml(), or nullptr if you want the manager
  134. to choose the best device to open.
  135. @param selectDefaultDeviceOnFailure if true, then if the device specified in the XML
  136. fails to open, then a default device will be used
  137. instead. If false, then on failure, no device is
  138. opened.
  139. @param preferredDefaultDeviceName if this is not empty, and there's a device with this
  140. name, then that will be used as the default device
  141. (assuming that there wasn't one specified in the XML).
  142. The string can actually be a simple wildcard, containing "*"
  143. and "?" characters
  144. @param preferredSetupOptions if this is non-null, the structure will be used as the
  145. set of preferred settings when opening the device. If you
  146. use this parameter, the preferredDefaultDeviceName
  147. field will be ignored
  148. @returns an error message if anything went wrong, or an empty string if it worked ok.
  149. */
  150. String initialise (int numInputChannelsNeeded,
  151. int numOutputChannelsNeeded,
  152. const XmlElement* savedState,
  153. bool selectDefaultDeviceOnFailure,
  154. const String& preferredDefaultDeviceName = String(),
  155. const AudioDeviceSetup* preferredSetupOptions = nullptr);
  156. /** Resets everything to a default device setup, clearing any stored settings. */
  157. String initialiseWithDefaultDevices (int numInputChannelsNeeded,
  158. int numOutputChannelsNeeded);
  159. /** Returns some XML representing the current state of the manager.
  160. This stores the current device, its samplerate, block size, etc, and
  161. can be restored later with initialise().
  162. Note that this can return a null pointer if no settings have been explicitly changed
  163. (i.e. if the device manager has just been left in its default state).
  164. */
  165. XmlElement* createStateXml() const;
  166. //==============================================================================
  167. /** Returns the current device properties that are in use.
  168. @see setAudioDeviceSetup
  169. */
  170. void getAudioDeviceSetup (AudioDeviceSetup& result);
  171. /** Changes the current device or its settings.
  172. If you want to change a device property, like the current sample rate or
  173. block size, you can call getAudioDeviceSetup() to retrieve the current
  174. settings, then tweak the appropriate fields in the AudioDeviceSetup structure,
  175. and pass it back into this method to apply the new settings.
  176. @param newSetup the settings that you'd like to use
  177. @param treatAsChosenDevice if this is true and if the device opens correctly, these new
  178. settings will be taken as having been explicitly chosen by the
  179. user, and the next time createStateXml() is called, these settings
  180. will be returned. If it's false, then the device is treated as a
  181. temporary or default device, and a call to createStateXml() will
  182. return either the last settings that were made with treatAsChosenDevice
  183. as true, or the last XML settings that were passed into initialise().
  184. @returns an error message if anything went wrong, or an empty string if it worked ok.
  185. @see getAudioDeviceSetup
  186. */
  187. String setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  188. bool treatAsChosenDevice);
  189. /** Returns the currently-active audio device. */
  190. AudioIODevice* getCurrentAudioDevice() const noexcept { return currentAudioDevice; }
  191. /** Returns the type of audio device currently in use.
  192. @see setCurrentAudioDeviceType
  193. */
  194. String getCurrentAudioDeviceType() const { return currentDeviceType; }
  195. /** Returns the currently active audio device type object.
  196. Don't keep a copy of this pointer - it's owned by the device manager and could
  197. change at any time.
  198. */
  199. AudioIODeviceType* getCurrentDeviceTypeObject() const;
  200. /** Changes the class of audio device being used.
  201. This switches between, e.g. ASIO and DirectSound. On the Mac you probably won't ever call
  202. this because there's only one type: CoreAudio.
  203. For a list of types, see getAvailableDeviceTypes().
  204. */
  205. void setCurrentAudioDeviceType (const String& type,
  206. 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::getDevices() method.
  245. Any incoming messages from enabled input devices will be forwarded on to all the
  246. listeners that have been registered with the addMidiInputCallback() method. They
  247. can either register for messages from a particular device, or from just the
  248. "default" 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 addMidiInputCallback, isMidiInputEnabled
  256. */
  257. void setMidiInputEnabled (const String& midiInputDeviceName, bool enabled);
  258. /** Returns true if a given midi input device is being used.
  259. @see setMidiInputEnabled
  260. */
  261. bool isMidiInputEnabled (const String& midiInputDeviceName) const;
  262. /** Registers a listener for callbacks when midi events arrive from a midi input.
  263. The device name 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 name of one of the
  265. MIDI input devices if it just wants the events from that device. (see
  266. MidiInput::getDevices() for the list of device names).
  267. Only devices which are enabled (see the setMidiInputEnabled() method) will have their
  268. events forwarded on to listeners.
  269. */
  270. void addMidiInputCallback (const String& midiInputDeviceName,
  271. MidiInputCallback* callback);
  272. /** Removes a listener that was previously registered with addMidiInputCallback(). */
  273. void removeMidiInputCallback (const String& midiInputDeviceName,
  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::getDevices() 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::getDevices() [MidiOutput::getDefaultDeviceIndex()].
  282. @see getDefaultMidiOutput, getDefaultMidiOutputName
  283. */
  284. void setDefaultMidiOutput (const String& deviceName);
  285. /** Returns the name of the default midi output.
  286. @see setDefaultMidiOutput, getDefaultMidiOutput
  287. */
  288. const String& getDefaultMidiOutputName() const noexcept { return defaultMidiOutputName; }
  289. /** Returns the current default midi output device.
  290. If no device has been selected, or the device can't be opened, this will return nullptr.
  291. @see getDefaultMidiOutputName
  292. */
  293. MidiOutput* getDefaultMidiOutput() const noexcept { return defaultMidiOutput; }
  294. /** Returns a list of the types of device supported. */
  295. const OwnedArray<AudioIODeviceType>& getAvailableDeviceTypes();
  296. //==============================================================================
  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. The manager will take ownership of the object that is passed-in.
  306. */
  307. void addAudioDeviceType (AudioIODeviceType* newDeviceType);
  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. /** Plays a sound from a file. */
  315. void playSound (const File& file);
  316. /** Convenient method to play sound from a JUCE resource. */
  317. void playSound (const void* resourceData, size_t resourceSize);
  318. /** Plays the sound from an audio format reader.
  319. If deleteWhenFinished is true then the format reader will be
  320. automatically deleted once the sound has finished playing.
  321. */
  322. void playSound (AudioFormatReader* buffer, bool deleteWhenFinished = false);
  323. /** Plays the sound from a positionable audio source.
  324. This will output the sound coming from a positionable audio source.
  325. This gives you slightly more control over the sound playback compared
  326. to the other playSound methods. For example, if you would like to
  327. stop the sound prematurely you can call this method with a
  328. TransportAudioSource and then call audioSource->stop. Note that,
  329. you must call audioSource->start to start the playback, if your
  330. audioSource is a TransportAudioSource.
  331. The audio device manager will not hold any references to this audio
  332. source once the audio source has stopped playing for any reason,
  333. for example when the sound has finished playing or when you have
  334. called audioSource->stop. Therefore, calling audioSource->start() on
  335. a finished audioSource will not restart the sound again. If this is
  336. desired simply call playSound with the same audioSource again.
  337. @param audioSource the audio source to play
  338. @param deleteWhenFinished If this is true then the audio source will
  339. be deleted once the device manager has finished playing.
  340. */
  341. void playSound (PositionableAudioSource* audioSource, bool deleteWhenFinished = false);
  342. /** Plays the sound from an audio sample buffer.
  343. This will output the sound contained in an audio sample buffer. If
  344. deleteWhenFinished is true then the audio sample buffer will be
  345. automatically deleted once the sound has finished playing.
  346. If playOnAllOutputChannels is true, then if there are more output channels
  347. than buffer channels, then the ones that are available will be re-used on
  348. multiple outputs so that something is sent to all output channels. If it
  349. is false, then the buffer will just be played on the first output channels.
  350. */
  351. void playSound (AudioSampleBuffer* buffer,
  352. bool deleteWhenFinished = false,
  353. bool playOnAllOutputChannels = false);
  354. //==============================================================================
  355. /** Turns on level-measuring.
  356. When enabled, the device manager will measure the peak input level
  357. across all channels, and you can get this level by calling getCurrentInputLevel().
  358. This is mainly intended for audio setup UI panels to use to create a mic
  359. level display, so that the user can check that they've selected the right
  360. device.
  361. A simple filter is used to make the level decay smoothly, but this is
  362. only intended for giving rough feedback, and not for any kind of accurate
  363. measurement.
  364. */
  365. void enableInputLevelMeasurement (bool enableMeasurement);
  366. /** Returns the current input level.
  367. To use this, you must first enable it by calling enableInputLevelMeasurement().
  368. See enableInputLevelMeasurement() for more info.
  369. */
  370. double getCurrentInputLevel() const;
  371. /** Returns the a lock that can be used to synchronise access to the audio callback.
  372. Obviously while this is locked, you're blocking the audio thread from running, so
  373. it must only be used for very brief periods when absolutely necessary.
  374. */
  375. CriticalSection& getAudioCallbackLock() noexcept { return audioCallbackLock; }
  376. /** Returns the a lock that can be used to synchronise access to the midi callback.
  377. Obviously while this is locked, you're blocking the midi system from running, so
  378. it must only be used for very brief periods when absolutely necessary.
  379. */
  380. CriticalSection& getMidiCallbackLock() noexcept { return midiCallbackLock; }
  381. private:
  382. //==============================================================================
  383. OwnedArray<AudioIODeviceType> availableDeviceTypes;
  384. OwnedArray<AudioDeviceSetup> lastDeviceTypeConfigs;
  385. AudioDeviceSetup currentSetup;
  386. ScopedPointer<AudioIODevice> currentAudioDevice;
  387. Array<AudioIODeviceCallback*> callbacks;
  388. int numInputChansNeeded, numOutputChansNeeded;
  389. String currentDeviceType;
  390. BigInteger inputChannels, outputChannels;
  391. ScopedPointer<XmlElement> lastExplicitSettings;
  392. mutable bool listNeedsScanning;
  393. Atomic<int> inputLevelMeasurementEnabledCount;
  394. double inputLevel;
  395. AudioSampleBuffer tempBuffer;
  396. struct MidiCallbackInfo
  397. {
  398. String deviceName;
  399. MidiInputCallback* callback;
  400. };
  401. StringArray midiInsFromXml;
  402. OwnedArray<MidiInput> enabledMidiInputs;
  403. Array<MidiCallbackInfo> midiCallbacks;
  404. String defaultMidiOutputName;
  405. ScopedPointer<MidiOutput> defaultMidiOutput;
  406. CriticalSection audioCallbackLock, midiCallbackLock;
  407. double cpuUsageMs, timeToCpuScale;
  408. //==============================================================================
  409. class CallbackHandler;
  410. friend class CallbackHandler;
  411. friend struct ContainerDeletePolicy<CallbackHandler>;
  412. ScopedPointer<CallbackHandler> callbackHandler;
  413. void audioDeviceIOCallbackInt (const float** inputChannelData, int totalNumInputChannels,
  414. float** outputChannelData, int totalNumOutputChannels, int numSamples);
  415. void audioDeviceAboutToStartInt (AudioIODevice*);
  416. void audioDeviceStoppedInt();
  417. void audioDeviceErrorInt (const String&);
  418. void handleIncomingMidiMessageInt (MidiInput*, const MidiMessage&);
  419. void audioDeviceListChanged();
  420. String restartDevice (int blockSizeToUse, double sampleRateToUse,
  421. const BigInteger& ins, const BigInteger& outs);
  422. void stopDevice();
  423. void updateXml();
  424. void createDeviceTypesIfNeeded();
  425. void scanDevicesIfNeeded();
  426. void deleteCurrentDevice();
  427. double chooseBestSampleRate (double preferred) const;
  428. int chooseBestBufferSize (int preferred) const;
  429. void insertDefaultDeviceNames (AudioDeviceSetup&) const;
  430. String initialiseDefault (const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
  431. String initialiseFromXML (const XmlElement&, bool selectDefaultDeviceOnFailure,
  432. const String& preferredDefaultDeviceName, const AudioDeviceSetup*);
  433. AudioIODeviceType* findType (const String& inputName, const String& outputName);
  434. AudioIODeviceType* findType (const String& typeName);
  435. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceManager)
  436. };
  437. #endif // JUCE_AUDIODEVICEMANAGER_H_INCLUDED