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.

390 lines
18KB

  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2015 ROLI Ltd.
  5. Copyright (C) 2017 Filipe Coelho <falktx@falktx.com>
  6. Permission is granted to use this software under the terms of the GNU
  7. General Public License as published by the Free Software Foundation;
  8. either version 2 of the License, or any later version.
  9. This program is distributed in the hope that it will be useful, but WITHOUT
  10. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. For a full copy of the GNU General Public License see the doc/GPL.txt file.
  13. ==============================================================================
  14. */
  15. #ifndef WATER_AUDIOPROCESSOR_H_INCLUDED
  16. #define WATER_AUDIOPROCESSOR_H_INCLUDED
  17. #include "../text/String.h"
  18. #include "../buffers/AudioSampleBuffer.h"
  19. #include "CarlaMutex.hpp"
  20. namespace water {
  21. //==============================================================================
  22. /**
  23. Base class for audio processing filters or plugins.
  24. This is intended to act as a base class of audio filter that is general enough to
  25. be wrapped as a VST, AU, RTAS, etc, or used internally.
  26. It is also used by the plugin hosting code as the wrapper around an instance
  27. of a loaded plugin.
  28. Derive your filter class from this base class, and if you're building a plugin,
  29. you should implement a global function called createPluginFilter() which creates
  30. and returns a new instance of your subclass.
  31. */
  32. class AudioProcessor
  33. {
  34. protected:
  35. //==============================================================================
  36. /** Constructor.
  37. This constructor will create a main input and output bus which are diabled
  38. by default. If you need more fine grain control then use the other
  39. constructors.
  40. */
  41. AudioProcessor();
  42. public:
  43. //==============================================================================
  44. /** Destructor. */
  45. virtual ~AudioProcessor();
  46. //==============================================================================
  47. /** Returns the name of this processor. */
  48. virtual const String getName() const = 0;
  49. //==============================================================================
  50. /** Called before playback starts, to let the filter prepare itself.
  51. The sample rate is the target sample rate, and will remain constant until
  52. playback stops.
  53. You can call getTotalNumInputChannels and getTotalNumOutputChannels
  54. or query the busLayout member variable to find out the number of
  55. channels your processBlock callback must process.
  56. The maximumExpectedSamplesPerBlock value is a strong hint about the maximum
  57. number of samples that will be provided in each block. You may want to use
  58. this value to resize internal buffers. You should program defensively in
  59. case a buggy host exceeds this value. The actual block sizes that the host
  60. uses may be different each time the callback happens: completely variable
  61. block sizes can be expected from some hosts.
  62. @see busLayout, getTotalNumInputChannels, getTotalNumOutputChannels
  63. */
  64. virtual void prepareToPlay (double sampleRate,
  65. int maximumExpectedSamplesPerBlock) = 0;
  66. /** Called after playback has stopped, to let the filter free up any resources it
  67. no longer needs.
  68. */
  69. virtual void releaseResources() = 0;
  70. /** Renders the next block.
  71. When this method is called, the buffer contains a number of channels which is
  72. at least as great as the maximum number of input and output channels that
  73. this filter is using. It will be filled with the filter's input data and
  74. should be replaced with the filter's output.
  75. So for example if your filter has a total of 2 input channels and 4 output
  76. channels, then the buffer will contain 4 channels, the first two being filled
  77. with the input data. Your filter should read these, do its processing, and
  78. replace the contents of all 4 channels with its output.
  79. Or if your filter has a total of 5 inputs and 2 outputs, the buffer will have 5
  80. channels, all filled with data, and your filter should overwrite the first 2 of
  81. these with its output. But be VERY careful not to write anything to the last 3
  82. channels, as these might be mapped to memory that the host assumes is read-only!
  83. If your plug-in has more than one input or output buses then the buffer passed
  84. to the processBlock methods will contain a bundle of all channels of each bus.
  85. Use AudiobusLayout::getBusBuffer to obtain an audio buffer for a
  86. particular bus.
  87. Note that if you have more outputs than inputs, then only those channels that
  88. correspond to an input channel are guaranteed to contain sensible data - e.g.
  89. in the case of 2 inputs and 4 outputs, the first two channels contain the input,
  90. but the last two channels may contain garbage, so you should be careful not to
  91. let this pass through without being overwritten or cleared.
  92. Also note that the buffer may have more channels than are strictly necessary,
  93. but you should only read/write from the ones that your filter is supposed to
  94. be using.
  95. The number of samples in these buffers is NOT guaranteed to be the same for every
  96. callback, and may be more or less than the estimated value given to prepareToPlay().
  97. Your code must be able to cope with variable-sized blocks, or you're going to get
  98. clicks and crashes!
  99. Also note that some hosts will occasionally decide to pass a buffer containing
  100. zero samples, so make sure that your algorithm can deal with that!
  101. If the filter is receiving a midi input, then the midiMessages array will be filled
  102. with the midi messages for this block. Each message's timestamp will indicate the
  103. message's time, as a number of samples from the start of the block.
  104. Any messages left in the midi buffer when this method has finished are assumed to
  105. be the filter's midi output. This means that your filter should be careful to
  106. clear any incoming messages from the array if it doesn't want them to be passed-on.
  107. Be very careful about what you do in this callback - it's going to be called by
  108. the audio thread, so any kind of interaction with the UI is absolutely
  109. out of the question. If you change a parameter in here and need to tell your UI to
  110. update itself, the best way is probably to inherit from a ChangeBroadcaster, let
  111. the UI components register as listeners, and then call sendChangeMessage() inside the
  112. processBlock() method to send out an asynchronous message. You could also use
  113. the AsyncUpdater class in a similar way.
  114. @see AudiobusLayout::getBusBuffer
  115. */
  116. virtual void processBlock (AudioSampleBuffer& buffer,
  117. MidiBuffer& midiMessages) = 0;
  118. /** Renders the next block when the processor is being bypassed.
  119. The default implementation of this method will pass-through any incoming audio, but
  120. you may override this method e.g. to add latency compensation to the data to match
  121. the processor's latency characteristics. This will avoid situations where bypassing
  122. will shift the signal forward in time, possibly creating pre-echo effects and odd timings.
  123. Another use for this method would be to cross-fade or morph between the wet (not bypassed)
  124. and dry (bypassed) signals.
  125. */
  126. virtual void processBlockBypassed (AudioSampleBuffer& buffer,
  127. MidiBuffer& midiMessages);
  128. #if 0
  129. //==============================================================================
  130. /** Returns the current AudioPlayHead object that should be used to find
  131. out the state and position of the playhead.
  132. You can ONLY call this from your processBlock() method! Calling it at other
  133. times will produce undefined behaviour, as the host may not have any context
  134. in which a time would make sense, and some hosts will almost certainly have
  135. multithreading issues if it's not called on the audio thread.
  136. The AudioPlayHead object that is returned can be used to get the details about
  137. the time of the start of the block currently being processed. But do not
  138. store this pointer or use it outside of the current audio callback, because
  139. the host may delete or re-use it.
  140. If the host can't or won't provide any time info, this will return nullptr.
  141. */
  142. AudioPlayHead* getPlayHead() const noexcept { return playHead; }
  143. #endif
  144. //==============================================================================
  145. /** Returns the total number of input channels.
  146. This method will return the total number of input channels by accumulating
  147. the number of channels on each input bus. The number of channels of the
  148. buffer passed to your processBlock callback will be equivalent to either
  149. getTotalNumInputChannels or getTotalNumOutputChannels - which ever
  150. is greater.
  151. Note that getTotalNumInputChannels is equivalent to
  152. getMainBusNumInputChannels if your processor does not have any sidechains
  153. or aux buses.
  154. */
  155. int getTotalNumInputChannels() const noexcept { return cachedTotalIns; }
  156. /** Returns the total number of output channels.
  157. This method will return the total number of output channels by accumulating
  158. the number of channels on each output bus. The number of channels of the
  159. buffer passed to your processBlock callback will be equivalent to either
  160. getTotalNumInputChannels or getTotalNumOutputChannels - which ever
  161. is greater.
  162. Note that getTotalNumOutputChannels is equivalent to
  163. getMainBusNumOutputChannels if your processor does not have any sidechains
  164. or aux buses.
  165. */
  166. int getTotalNumOutputChannels() const noexcept { return cachedTotalOuts; }
  167. //==============================================================================
  168. /** Returns the current sample rate.
  169. This can be called from your processBlock() method - it's not guaranteed
  170. to be valid at any other time, and may return 0 if it's unknown.
  171. */
  172. double getSampleRate() const noexcept { return currentSampleRate; }
  173. /** Returns the current typical block size that is being used.
  174. This can be called from your processBlock() method - it's not guaranteed
  175. to be valid at any other time.
  176. Remember it's not the ONLY block size that may be used when calling
  177. processBlock, it's just the normal one. The actual block sizes used may be
  178. larger or smaller than this, and will vary between successive calls.
  179. */
  180. int getBlockSize() const noexcept { return blockSize; }
  181. //==============================================================================
  182. /** This returns the number of samples delay that the filter imposes on the audio
  183. passing through it.
  184. The host will call this to find the latency - the filter itself should set this value
  185. by calling setLatencySamples() as soon as it can during its initialisation.
  186. */
  187. int getLatencySamples() const noexcept { return latencySamples; }
  188. /** The filter should call this to set the number of samples delay that it introduces.
  189. The filter should call this as soon as it can during initialisation, and can call it
  190. later if the value changes.
  191. */
  192. void setLatencySamples (int newLatency);
  193. /** Returns true if the processor wants midi messages. */
  194. virtual bool acceptsMidi() const = 0;
  195. /** Returns true if the processor produces midi messages. */
  196. virtual bool producesMidi() const = 0;
  197. /** Returns true if the processor supports MPE. */
  198. virtual bool supportsMPE() const { return false; }
  199. /** Returns true if this is a midi effect plug-in and does no audio processing. */
  200. virtual bool isMidiEffect() const { return false; }
  201. virtual const String getInputChannelName (int) const { return String(); }
  202. virtual const String getOutputChannelName (int) const { return String(); }
  203. //==============================================================================
  204. /** This returns a critical section that will automatically be locked while the host
  205. is calling the processBlock() method.
  206. Use it from your UI or other threads to lock access to variables that are used
  207. by the process callback, but obviously be careful not to keep it locked for
  208. too long, because that could cause stuttering playback. If you need to do something
  209. that'll take a long time and need the processing to stop while it happens, use the
  210. suspendProcessing() method instead.
  211. @see suspendProcessing
  212. */
  213. const CarlaRecursiveMutex& getCallbackLock() const noexcept { return callbackLock; }
  214. /** Enables and disables the processing callback.
  215. If you need to do something time-consuming on a thread and would like to make sure
  216. the audio processing callback doesn't happen until you've finished, use this
  217. to disable the callback and re-enable it again afterwards.
  218. E.g.
  219. @code
  220. void loadNewPatch()
  221. {
  222. suspendProcessing (true);
  223. ..do something that takes ages..
  224. suspendProcessing (false);
  225. }
  226. @endcode
  227. If the host tries to make an audio callback while processing is suspended, the
  228. filter will return an empty buffer, but won't block the audio thread like it would
  229. do if you use the getCallbackLock() critical section to synchronise access.
  230. Any code that calls processBlock() should call isSuspended() before doing so, and
  231. if the processor is suspended, it should avoid the call and emit silence or
  232. whatever is appropriate.
  233. @see getCallbackLock
  234. */
  235. void suspendProcessing (bool shouldBeSuspended);
  236. /** Returns true if processing is currently suspended.
  237. @see suspendProcessing
  238. */
  239. bool isSuspended() const noexcept { return suspended; }
  240. /** A plugin can override this to be told when it should reset any playing voices.
  241. The default implementation does nothing, but a host may call this to tell the
  242. plugin that it should stop any tails or sounds that have been left running.
  243. */
  244. virtual void reset();
  245. //==============================================================================
  246. /** Returns true if the processor is being run in an offline mode for rendering.
  247. If the processor is being run live on realtime signals, this returns false.
  248. If the mode is unknown, this will assume it's realtime and return false.
  249. This value may be unreliable until the prepareToPlay() method has been called,
  250. and could change each time prepareToPlay() is called.
  251. @see setNonRealtime()
  252. */
  253. bool isNonRealtime() const noexcept { return nonRealtime; }
  254. /** Called by the host to tell this processor whether it's being used in a non-realtime
  255. capacity for offline rendering or bouncing.
  256. */
  257. virtual void setNonRealtime (bool isNonRealtime) noexcept;
  258. #if 0
  259. //==============================================================================
  260. /** Tells the processor to use this playhead object.
  261. The processor will not take ownership of the object, so the caller must delete it when
  262. it is no longer being used.
  263. */
  264. virtual void setPlayHead (AudioPlayHead* newPlayHead);
  265. #endif
  266. //==============================================================================
  267. /** This is called by the processor to specify its details before being played. Use this
  268. version of the function if you are not interested in any sidechain and/or aux buses
  269. and do not care about the layout of channels. Otherwise use setRateAndBufferSizeDetails.*/
  270. void setPlayConfigDetails (int numIns, int numOuts, double sampleRate, int blockSize);
  271. /** This is called by the processor to specify its details before being played. You
  272. should call this function after having informed the processor about the channel
  273. and bus layouts via setBusesLayout.
  274. @see setBusesLayout
  275. */
  276. void setRateAndBufferSizeDetails (double sampleRate, int blockSize) noexcept;
  277. private:
  278. #if 0
  279. //==============================================================================
  280. /** @internal */
  281. AudioPlayHead* playHead;
  282. #endif
  283. //==============================================================================
  284. double currentSampleRate;
  285. int blockSize, latencySamples;
  286. bool suspended, nonRealtime;
  287. CarlaRecursiveMutex callbackLock;
  288. String cachedInputSpeakerArrString;
  289. String cachedOutputSpeakerArrString;
  290. int cachedTotalIns, cachedTotalOuts;
  291. void processBypassed (AudioSampleBuffer&, MidiBuffer&);
  292. CARLA_DECLARE_NON_COPY_CLASS (AudioProcessor)
  293. };
  294. }
  295. #endif // WATER_AUDIOPROCESSOR_H_INCLUDED