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.

228 lines
10KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2020 - 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 this technical preview, this file is not subject to commercial licensing.
  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. Performs stereo partitioned convolution of an input signal with an
  19. impulse response in the frequency domain, using the JUCE FFT class.
  20. This class provides some thread-safe functions to load impulse responses
  21. from audio files or memory on-the-fly without noticeable artefacts,
  22. performing resampling and trimming if necessary.
  23. The processing performed by this class is equivalent to the time domain
  24. convolution done in the FIRFilter class, with a FIRFilter::Coefficients
  25. object having the samples of the impulse response as its coefficients.
  26. However, in general it is more efficient to do frequency domain
  27. convolution when the size of the impulse response is 64 samples or
  28. greater.
  29. Note: The default operation of this class uses zero latency and a uniform
  30. partitioned algorithm. If the impulse response size is large, or if the
  31. algorithm is too CPU intensive, it is possible to use either a fixed
  32. latency version of the algorithm, or a simple non-uniform partitioned
  33. convolution algorithm.
  34. Threading: It is not safe to interleave calls to the methods of this
  35. class. If you need to load new impulse responses during processing the
  36. `load` calls must be synchronised with `process` calls, which in practice
  37. means making the `load` call from the audio thread. The
  38. `loadImpulseResponse` functions *are* wait-free and are therefore
  39. suitable for use in a realtime context.
  40. @see FIRFilter, FIRFilter::Coefficients, FFT
  41. @tags{DSP}
  42. */
  43. class JUCE_API Convolution
  44. {
  45. public:
  46. //==============================================================================
  47. /** Initialises an object for performing convolution in the frequency domain. */
  48. Convolution();
  49. /** Contains configuration information for a convolution with a fixed latency. */
  50. struct Latency { int latencyInSamples; };
  51. /** Initialises an object for performing convolution with a fixed latency.
  52. If the requested latency is zero, the actual latency will also be zero.
  53. For requested latencies greater than zero, the actual latency will
  54. always at least as large as the requested latency. Using a fixed
  55. non-zero latency can reduce the CPU consumption of the convolution
  56. algorithm.
  57. @param requiredLatency the minimum latency
  58. */
  59. explicit Convolution (const Latency& requiredLatency);
  60. /** Contains configuration information for a non-uniform convolution. */
  61. struct NonUniform { int headSizeInSamples; };
  62. /** Initialises an object for performing convolution in the frequency domain
  63. using a non-uniform partitioned algorithm.
  64. A requiredHeadSize of 256 samples or greater will improve the
  65. efficiency of the processing for IR sizes of 4096 samples or greater
  66. (recommended for reverberation IRs).
  67. @param requiredHeadSize the head IR size for two stage non-uniform
  68. partitioned convolution
  69. */
  70. explicit Convolution (const NonUniform& requiredHeadSize);
  71. ~Convolution() noexcept;
  72. //==============================================================================
  73. /** Must be called before loading any impulse response. This provides the
  74. maximumBufferSize and the sample rate required for any resampling.
  75. */
  76. void prepare (const ProcessSpec&);
  77. /** Resets the processing pipeline ready to start a new stream of data. */
  78. void reset() noexcept;
  79. /** Performs the filter operation on the given set of samples with optional
  80. stereo processing.
  81. */
  82. template <typename ProcessContext,
  83. std::enable_if_t<std::is_same<typename ProcessContext::SampleType, float>::value, int> = 0>
  84. void process (const ProcessContext& context) noexcept
  85. {
  86. processSamples (context.getInputBlock(), context.getOutputBlock(), context.isBypassed);
  87. }
  88. //==============================================================================
  89. enum class Stereo { yes, no };
  90. enum class Trim { yes, no };
  91. enum class Normalise { yes, no };
  92. //==============================================================================
  93. /** This function loads an impulse response audio file from memory, added in a
  94. JUCE project with the Projucer as binary data. It can load any of the audio
  95. formats registered in JUCE, and performs some resampling and pre-processing
  96. as well if needed.
  97. Note: Don't try to use this function on float samples, since the data is
  98. expected to be an audio file in its binary format. Be sure that the original
  99. data remains constant throughout the lifetime of the Convolution object, as
  100. the loading process will happen on a background thread once this function has
  101. returned.
  102. @param sourceData the block of data to use as the stream's source
  103. @param sourceDataSize the number of bytes in the source data block
  104. @param isStereo selects either stereo or mono
  105. @param requiresTrimming optionally trim the start and the end of the impulse response
  106. @param size the expected size for the impulse response after loading, can be
  107. set to 0 to requesting the original impulse response size
  108. @param requiresNormalisation optionally normalise the impulse response amplitude
  109. */
  110. void loadImpulseResponse (const void* sourceData, size_t sourceDataSize,
  111. Stereo isStereo, Trim requiresTrimming, size_t size,
  112. Normalise requiresNormalisation = Normalise::yes);
  113. /** This function loads an impulse response from an audio file. It can load any
  114. of the audio formats registered in JUCE, and performs some resampling and
  115. pre-processing as well if needed.
  116. @param fileImpulseResponse the location of the audio file
  117. @param isStereo selects either stereo or mono
  118. @param requiresTrimming optionally trim the start and the end of the impulse response
  119. @param size the expected size for the impulse response after loading, can be
  120. set to 0 to requesting the original impulse response size
  121. @param requiresNormalisation optionally normalise the impulse response amplitude
  122. */
  123. void loadImpulseResponse (const File& fileImpulseResponse,
  124. Stereo isStereo, Trim requiresTrimming, size_t size,
  125. Normalise requiresNormalisation = Normalise::yes);
  126. /** This function loads an impulse response from an audio buffer.
  127. To avoid memory allocation on the audio thread, this function takes
  128. ownership of the buffer passed in.
  129. If calling this function during processing, make sure that the buffer is
  130. not allocated on the audio thread (be careful of accidental copies!).
  131. If you need to pass arbitrary/generated buffers it's recommended to
  132. create these buffers on a separate thread and to use some wait-free
  133. construct (a lock-free queue or a SpinLock/GenericScopedTryLock combination)
  134. to transfer ownership to the audio thread without allocating.
  135. @param buffer the AudioBuffer to use
  136. @param bufferSampleRate the sampleRate of the data in the AudioBuffer
  137. @param isStereo selects either stereo or mono
  138. @param requiresTrimming optionally trim the start and the end of the impulse response
  139. @param requiresNormalisation optionally normalise the impulse response amplitude
  140. */
  141. void loadImpulseResponse (AudioBuffer<float>&& buffer, double bufferSampleRate,
  142. Stereo isStereo, Trim requiresTrimming, Normalise requiresNormalisation);
  143. /** This function returns the size of the current IR in samples. */
  144. int getCurrentIRSize() const;
  145. /** This function returns the current latency of the process in samples.
  146. Note: This is the latency of the convolution engine, not the latency
  147. associated with the current impulse response choice that has to be
  148. considered separately (linear phase filters, for eaxmple).
  149. */
  150. int getLatency() const;
  151. private:
  152. //==============================================================================
  153. void processSamples (const AudioBlock<const float>&, AudioBlock<float>&, bool isBypassed) noexcept;
  154. class Mixer
  155. {
  156. public:
  157. void prepare (const ProcessSpec&);
  158. template <typename ProcessWet>
  159. void processSamples (const AudioBlock<const float>&,
  160. AudioBlock<float>&,
  161. bool isBypassed,
  162. ProcessWet&&) noexcept;
  163. void reset();
  164. private:
  165. std::array<SmoothedValue<float>, 2> volumeDry, volumeWet;
  166. AudioBlock<float> dryBlock;
  167. HeapBlock<char> dryBlockStorage;
  168. double sampleRate = 0;
  169. bool currentIsBypassed = false;
  170. };
  171. //==============================================================================
  172. class Impl;
  173. std::unique_ptr<Impl> pimpl;
  174. //==============================================================================
  175. Mixer mixer;
  176. bool isActive = false;
  177. //==============================================================================
  178. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Convolution)
  179. };
  180. } // namespace dsp
  181. } // namespace juce