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.

311 lines
13KB

  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. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. namespace dsp
  21. {
  22. /**
  23. Used by the Convolution to dispatch engine-update messages on a background
  24. thread.
  25. May be shared between multiple Convolution instances.
  26. @tags{DSP}
  27. */
  28. class JUCE_API ConvolutionMessageQueue
  29. {
  30. public:
  31. /** Initialises the queue to a default size.
  32. If your Convolution is updated very frequently, or you are sharing
  33. this queue between multiple Convolutions, consider using the alternative
  34. constructor taking an explicit size argument.
  35. */
  36. ConvolutionMessageQueue();
  37. ~ConvolutionMessageQueue() noexcept;
  38. /** Initialises the queue with the specified number of entries.
  39. In general, the number of required entries scales with the number
  40. of Convolutions sharing the same Queue, and the frequency of updates
  41. to those Convolutions.
  42. */
  43. explicit ConvolutionMessageQueue (int numEntries);
  44. ConvolutionMessageQueue (ConvolutionMessageQueue&&) noexcept;
  45. ConvolutionMessageQueue& operator= (ConvolutionMessageQueue&&) noexcept;
  46. ConvolutionMessageQueue (const ConvolutionMessageQueue&) = delete;
  47. ConvolutionMessageQueue& operator= (const ConvolutionMessageQueue&) = delete;
  48. private:
  49. struct Impl;
  50. std::unique_ptr<Impl> pimpl;
  51. friend class Convolution;
  52. };
  53. /**
  54. Performs stereo partitioned convolution of an input signal with an
  55. impulse response in the frequency domain, using the JUCE FFT class.
  56. This class provides some thread-safe functions to load impulse responses
  57. from audio files or memory on-the-fly without noticeable artefacts,
  58. performing resampling and trimming if necessary.
  59. The processing performed by this class is equivalent to the time domain
  60. convolution done in the FIRFilter class, with a FIRFilter::Coefficients
  61. object having the samples of the impulse response as its coefficients.
  62. However, in general it is more efficient to do frequency domain
  63. convolution when the size of the impulse response is 64 samples or
  64. greater.
  65. Note: The default operation of this class uses zero latency and a uniform
  66. partitioned algorithm. If the impulse response size is large, or if the
  67. algorithm is too CPU intensive, it is possible to use either a fixed
  68. latency version of the algorithm, or a simple non-uniform partitioned
  69. convolution algorithm.
  70. Threading: It is not safe to interleave calls to the methods of this
  71. class. If you need to load new impulse responses during processing the
  72. load() calls must be synchronised with process() calls, which in practice
  73. means making the load() call from the audio thread. The
  74. loadImpulseResponse() functions *are* wait-free and are therefore
  75. suitable for use in a realtime context.
  76. @see FIRFilter, FIRFilter::Coefficients, FFT
  77. @tags{DSP}
  78. */
  79. class JUCE_API Convolution
  80. {
  81. public:
  82. //==============================================================================
  83. /** Initialises an object for performing convolution in the frequency domain. */
  84. Convolution();
  85. /** Initialises a convolution engine using a shared background message queue.
  86. IMPORTANT: the queue *must* remain alive throughout the lifetime of the
  87. Convolution.
  88. */
  89. explicit Convolution (ConvolutionMessageQueue& queue);
  90. /** Contains configuration information for a convolution with a fixed latency. */
  91. struct Latency { int latencyInSamples; };
  92. /** Initialises an object for performing convolution with a fixed latency.
  93. If the requested latency is zero, the actual latency will also be zero.
  94. For requested latencies greater than zero, the actual latency will
  95. always at least as large as the requested latency. Using a fixed
  96. non-zero latency can reduce the CPU consumption of the convolution
  97. algorithm.
  98. @param requiredLatency the minimum latency
  99. */
  100. explicit Convolution (const Latency& requiredLatency);
  101. /** Contains configuration information for a non-uniform convolution. */
  102. struct NonUniform { int headSizeInSamples; };
  103. /** Initialises an object for performing convolution in the frequency domain
  104. using a non-uniform partitioned algorithm.
  105. A requiredHeadSize of 256 samples or greater will improve the
  106. efficiency of the processing for IR sizes of 4096 samples or greater
  107. (recommended for reverberation IRs).
  108. @param requiredHeadSize the head IR size for two stage non-uniform
  109. partitioned convolution
  110. */
  111. explicit Convolution (const NonUniform& requiredHeadSize);
  112. /** Behaves the same as the constructor taking a single Latency argument,
  113. but with a shared background message queue.
  114. IMPORTANT: the queue *must* remain alive throughout the lifetime of the
  115. Convolution.
  116. */
  117. Convolution (const Latency&, ConvolutionMessageQueue&);
  118. /** Behaves the same as the constructor taking a single NonUniform argument,
  119. but with a shared background message queue.
  120. IMPORTANT: the queue *must* remain alive throughout the lifetime of the
  121. Convolution.
  122. */
  123. Convolution (const NonUniform&, ConvolutionMessageQueue&);
  124. ~Convolution() noexcept;
  125. //==============================================================================
  126. /** Must be called before first calling process.
  127. In general, calls to loadImpulseResponse() load the impulse response (IR)
  128. asynchronously. The IR will become active once it has been completely loaded
  129. and processed, which may take some time.
  130. Calling prepare() will ensure that the IR supplied to the most recent call to
  131. loadImpulseResponse() is fully initialised. This IR will then be active during
  132. the next call to process(). It is recommended to call loadImpulseResponse() *before*
  133. prepare() if a specific IR must be active during the first process() call.
  134. */
  135. void prepare (const ProcessSpec&);
  136. /** Resets the processing pipeline ready to start a new stream of data. */
  137. void reset() noexcept;
  138. /** Performs the filter operation on the given set of samples with optional
  139. stereo processing.
  140. */
  141. template <typename ProcessContext,
  142. std::enable_if_t<std::is_same<typename ProcessContext::SampleType, float>::value, int> = 0>
  143. void process (const ProcessContext& context) noexcept
  144. {
  145. processSamples (context.getInputBlock(), context.getOutputBlock(), context.isBypassed);
  146. }
  147. //==============================================================================
  148. enum class Stereo { no, yes };
  149. enum class Trim { no, yes };
  150. enum class Normalise { no, yes };
  151. //==============================================================================
  152. /** This function loads an impulse response audio file from memory, added in a
  153. JUCE project with the Projucer as binary data. It can load any of the audio
  154. formats registered in JUCE, and performs some resampling and pre-processing
  155. as well if needed.
  156. Note: Don't try to use this function on float samples, since the data is
  157. expected to be an audio file in its binary format. Be sure that the original
  158. data remains constant throughout the lifetime of the Convolution object, as
  159. the loading process will happen on a background thread once this function has
  160. returned.
  161. @param sourceData the block of data to use as the stream's source
  162. @param sourceDataSize the number of bytes in the source data block
  163. @param isStereo selects either stereo or mono
  164. @param requiresTrimming optionally trim the start and the end of the impulse response
  165. @param size the expected size for the impulse response after loading, can be
  166. set to 0 to requesting the original impulse response size
  167. @param requiresNormalisation optionally normalise the impulse response amplitude
  168. */
  169. void loadImpulseResponse (const void* sourceData, size_t sourceDataSize,
  170. Stereo isStereo, Trim requiresTrimming, size_t size,
  171. Normalise requiresNormalisation = Normalise::yes);
  172. /** This function loads an impulse response from an audio file. It can load any
  173. of the audio formats registered in JUCE, and performs some resampling and
  174. pre-processing as well if needed.
  175. @param fileImpulseResponse the location of the audio file
  176. @param isStereo selects either stereo or mono
  177. @param requiresTrimming optionally trim the start and the end of the impulse response
  178. @param size the expected size for the impulse response after loading, can be
  179. set to 0 to requesting the original impulse response size
  180. @param requiresNormalisation optionally normalise the impulse response amplitude
  181. */
  182. void loadImpulseResponse (const File& fileImpulseResponse,
  183. Stereo isStereo, Trim requiresTrimming, size_t size,
  184. Normalise requiresNormalisation = Normalise::yes);
  185. /** This function loads an impulse response from an audio buffer.
  186. To avoid memory allocation on the audio thread, this function takes
  187. ownership of the buffer passed in.
  188. If calling this function during processing, make sure that the buffer is
  189. not allocated on the audio thread (be careful of accidental copies!).
  190. If you need to pass arbitrary/generated buffers it's recommended to
  191. create these buffers on a separate thread and to use some wait-free
  192. construct (a lock-free queue or a SpinLock/GenericScopedTryLock combination)
  193. to transfer ownership to the audio thread without allocating.
  194. @param buffer the AudioBuffer to use
  195. @param bufferSampleRate the sampleRate of the data in the AudioBuffer
  196. @param isStereo selects either stereo or mono
  197. @param requiresTrimming optionally trim the start and the end of the impulse response
  198. @param requiresNormalisation optionally normalise the impulse response amplitude
  199. */
  200. void loadImpulseResponse (AudioBuffer<float>&& buffer, double bufferSampleRate,
  201. Stereo isStereo, Trim requiresTrimming, Normalise requiresNormalisation);
  202. /** This function returns the size of the current IR in samples. */
  203. int getCurrentIRSize() const;
  204. /** This function returns the current latency of the process in samples.
  205. Note: This is the latency of the convolution engine, not the latency
  206. associated with the current impulse response choice that has to be
  207. considered separately (linear phase filters, for example).
  208. */
  209. int getLatency() const;
  210. private:
  211. //==============================================================================
  212. Convolution (const Latency&,
  213. const NonUniform&,
  214. OptionalScopedPointer<ConvolutionMessageQueue>&&);
  215. void processSamples (const AudioBlock<const float>&, AudioBlock<float>&, bool isBypassed) noexcept;
  216. class Mixer
  217. {
  218. public:
  219. void prepare (const ProcessSpec&);
  220. template <typename ProcessWet>
  221. void processSamples (const AudioBlock<const float>&,
  222. AudioBlock<float>&,
  223. bool isBypassed,
  224. ProcessWet&&) noexcept;
  225. void reset();
  226. private:
  227. std::array<SmoothedValue<float>, 2> volumeDry, volumeWet;
  228. AudioBlock<float> dryBlock;
  229. HeapBlock<char> dryBlockStorage;
  230. double sampleRate = 0;
  231. bool currentIsBypassed = false;
  232. };
  233. //==============================================================================
  234. class Impl;
  235. std::unique_ptr<Impl> pimpl;
  236. //==============================================================================
  237. Mixer mixer;
  238. bool isActive = false;
  239. //==============================================================================
  240. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Convolution)
  241. };
  242. } // namespace dsp
  243. } // namespace juce