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.

304 lines
13KB

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