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.

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