build(deps): vendor JUCE 7.0.12

This commit is contained in:
2026-09-08 14:55:21 +02:00
parent 5b99f51bd1
commit d6705ab29f
3591 changed files with 1218267 additions and 0 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,307 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce::dsp
{
/**
Used by the Convolution to dispatch engine-update messages on a background
thread.
May be shared between multiple Convolution instances.
@tags{DSP}
*/
class JUCE_API ConvolutionMessageQueue
{
public:
/** Initialises the queue to a default size.
If your Convolution is updated very frequently, or you are sharing
this queue between multiple Convolutions, consider using the alternative
constructor taking an explicit size argument.
*/
ConvolutionMessageQueue();
~ConvolutionMessageQueue() noexcept;
/** Initialises the queue with the specified number of entries.
In general, the number of required entries scales with the number
of Convolutions sharing the same Queue, and the frequency of updates
to those Convolutions.
*/
explicit ConvolutionMessageQueue (int numEntries);
ConvolutionMessageQueue (ConvolutionMessageQueue&&) noexcept;
ConvolutionMessageQueue& operator= (ConvolutionMessageQueue&&) noexcept;
ConvolutionMessageQueue (const ConvolutionMessageQueue&) = delete;
ConvolutionMessageQueue& operator= (const ConvolutionMessageQueue&) = delete;
private:
struct Impl;
std::unique_ptr<Impl> pimpl;
friend class Convolution;
};
/**
Performs stereo partitioned convolution of an input signal with an
impulse response in the frequency domain, using the JUCE FFT class.
This class provides some thread-safe functions to load impulse responses
from audio files or memory on-the-fly without noticeable artefacts,
performing resampling and trimming if necessary.
The processing performed by this class is equivalent to the time domain
convolution done in the FIRFilter class, with a FIRFilter::Coefficients
object having the samples of the impulse response as its coefficients.
However, in general it is more efficient to do frequency domain
convolution when the size of the impulse response is 64 samples or
greater.
Note: The default operation of this class uses zero latency and a uniform
partitioned algorithm. If the impulse response size is large, or if the
algorithm is too CPU intensive, it is possible to use either a fixed
latency version of the algorithm, or a simple non-uniform partitioned
convolution algorithm.
Threading: It is not safe to interleave calls to the methods of this
class. If you need to load new impulse responses during processing the
load() calls must be synchronised with process() calls, which in practice
means making the load() call from the audio thread. The
loadImpulseResponse() functions *are* wait-free and are therefore
suitable for use in a realtime context.
@see FIRFilter, FIRFilter::Coefficients, FFT
@tags{DSP}
*/
class JUCE_API Convolution
{
public:
//==============================================================================
/** Initialises an object for performing convolution in the frequency domain. */
Convolution();
/** Initialises a convolution engine using a shared background message queue.
IMPORTANT: the queue *must* remain alive throughout the lifetime of the
Convolution.
*/
explicit Convolution (ConvolutionMessageQueue& queue);
/** Contains configuration information for a convolution with a fixed latency. */
struct Latency { int latencyInSamples; };
/** Initialises an object for performing convolution with a fixed latency.
If the requested latency is zero, the actual latency will also be zero.
For requested latencies greater than zero, the actual latency will
always at least as large as the requested latency. Using a fixed
non-zero latency can reduce the CPU consumption of the convolution
algorithm.
@param requiredLatency the minimum latency
*/
explicit Convolution (const Latency& requiredLatency);
/** Contains configuration information for a non-uniform convolution. */
struct NonUniform { int headSizeInSamples; };
/** Initialises an object for performing convolution in the frequency domain
using a non-uniform partitioned algorithm.
A requiredHeadSize of 256 samples or greater will improve the
efficiency of the processing for IR sizes of 4096 samples or greater
(recommended for reverberation IRs).
@param requiredHeadSize the head IR size for two stage non-uniform
partitioned convolution
*/
explicit Convolution (const NonUniform& requiredHeadSize);
/** Behaves the same as the constructor taking a single Latency argument,
but with a shared background message queue.
IMPORTANT: the queue *must* remain alive throughout the lifetime of the
Convolution.
*/
Convolution (const Latency&, ConvolutionMessageQueue&);
/** Behaves the same as the constructor taking a single NonUniform argument,
but with a shared background message queue.
IMPORTANT: the queue *must* remain alive throughout the lifetime of the
Convolution.
*/
Convolution (const NonUniform&, ConvolutionMessageQueue&);
~Convolution() noexcept;
//==============================================================================
/** Must be called before first calling process.
In general, calls to loadImpulseResponse() load the impulse response (IR)
asynchronously. The IR will become active once it has been completely loaded
and processed, which may take some time.
Calling prepare() will ensure that the IR supplied to the most recent call to
loadImpulseResponse() is fully initialised. This IR will then be active during
the next call to process(). It is recommended to call loadImpulseResponse() *before*
prepare() if a specific IR must be active during the first process() call.
*/
void prepare (const ProcessSpec&);
/** Resets the processing pipeline ready to start a new stream of data. */
void reset() noexcept;
/** Performs the filter operation on the given set of samples with optional
stereo processing.
*/
template <typename ProcessContext,
std::enable_if_t<std::is_same_v<typename ProcessContext::SampleType, float>, int> = 0>
void process (const ProcessContext& context) noexcept
{
processSamples (context.getInputBlock(), context.getOutputBlock(), context.isBypassed);
}
//==============================================================================
enum class Stereo { no, yes };
enum class Trim { no, yes };
enum class Normalise { no, yes };
//==============================================================================
/** This function loads an impulse response audio file from memory, added in a
JUCE project with the Projucer as binary data. It can load any of the audio
formats registered in JUCE, and performs some resampling and pre-processing
as well if needed.
Note: Don't try to use this function on float samples, since the data is
expected to be an audio file in its binary format. Be sure that the original
data remains constant throughout the lifetime of the Convolution object, as
the loading process will happen on a background thread once this function has
returned.
@param sourceData the block of data to use as the stream's source
@param sourceDataSize the number of bytes in the source data block
@param isStereo selects either stereo or mono
@param requiresTrimming optionally trim the start and the end of the impulse response
@param size the expected size for the impulse response after loading, can be
set to 0 to requesting the original impulse response size
@param requiresNormalisation optionally normalise the impulse response amplitude
*/
void loadImpulseResponse (const void* sourceData, size_t sourceDataSize,
Stereo isStereo, Trim requiresTrimming, size_t size,
Normalise requiresNormalisation = Normalise::yes);
/** This function loads an impulse response from an audio file. It can load any
of the audio formats registered in JUCE, and performs some resampling and
pre-processing as well if needed.
@param fileImpulseResponse the location of the audio file
@param isStereo selects either stereo or mono
@param requiresTrimming optionally trim the start and the end of the impulse response
@param size the expected size for the impulse response after loading, can be
set to 0 to requesting the original impulse response size
@param requiresNormalisation optionally normalise the impulse response amplitude
*/
void loadImpulseResponse (const File& fileImpulseResponse,
Stereo isStereo, Trim requiresTrimming, size_t size,
Normalise requiresNormalisation = Normalise::yes);
/** This function loads an impulse response from an audio buffer.
To avoid memory allocation on the audio thread, this function takes
ownership of the buffer passed in.
If calling this function during processing, make sure that the buffer is
not allocated on the audio thread (be careful of accidental copies!).
If you need to pass arbitrary/generated buffers it's recommended to
create these buffers on a separate thread and to use some wait-free
construct (a lock-free queue or a SpinLock/GenericScopedTryLock combination)
to transfer ownership to the audio thread without allocating.
@param buffer the AudioBuffer to use
@param bufferSampleRate the sampleRate of the data in the AudioBuffer
@param isStereo selects either stereo or mono
@param requiresTrimming optionally trim the start and the end of the impulse response
@param requiresNormalisation optionally normalise the impulse response amplitude
*/
void loadImpulseResponse (AudioBuffer<float>&& buffer, double bufferSampleRate,
Stereo isStereo, Trim requiresTrimming, Normalise requiresNormalisation);
/** This function returns the size of the current IR in samples. */
int getCurrentIRSize() const;
/** This function returns the current latency of the process in samples.
Note: This is the latency of the convolution engine, not the latency
associated with the current impulse response choice that has to be
considered separately (linear phase filters, for example).
*/
int getLatency() const;
private:
//==============================================================================
Convolution (const Latency&,
const NonUniform&,
OptionalScopedPointer<ConvolutionMessageQueue>&&);
void processSamples (const AudioBlock<const float>&, AudioBlock<float>&, bool isBypassed) noexcept;
class Mixer
{
public:
void prepare (const ProcessSpec&);
template <typename ProcessWet>
void processSamples (const AudioBlock<const float>&,
AudioBlock<float>&,
bool isBypassed,
ProcessWet&&) noexcept;
void reset();
private:
std::array<SmoothedValue<float>, 2> volumeDry, volumeWet;
AudioBlock<float> dryBlock;
HeapBlock<char> dryBlockStorage;
double sampleRate = 0;
bool currentIsBypassed = false;
};
//==============================================================================
class Impl;
std::unique_ptr<Impl> pimpl;
//==============================================================================
Mixer mixer;
bool isActive = false;
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Convolution)
};
} // namespace juce::dsp
@@ -0,0 +1,578 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#if JUCE_ENABLE_ALLOCATION_HOOKS
#define JUCE_FAIL_ON_ALLOCATION_IN_SCOPE const UnitTestAllocationChecker checker (*this)
#else
#define JUCE_FAIL_ON_ALLOCATION_IN_SCOPE
#endif
namespace juce::dsp
{
namespace
{
class ConvolutionTest final : public UnitTest
{
template <typename Callback>
static void nTimes (int n, Callback&& callback)
{
for (auto i = 0; i < n; ++i)
callback();
}
static AudioBuffer<float> makeRamp (int length)
{
AudioBuffer<float> result (1, length);
result.clear();
const auto writePtr = result.getWritePointer (0);
std::fill (writePtr, writePtr + length, 1.0f);
result.applyGainRamp (0, length, 1.0f, 0.0f);
return result;
}
static AudioBuffer<float> makeStereoRamp (int length)
{
AudioBuffer<float> result (2, length);
result.clear();
auto* const* channels = result.getArrayOfWritePointers();
std::for_each (channels, channels + result.getNumChannels(), [length] (auto* channel)
{
std::fill (channel, channel + length, 1.0f);
});
result.applyGainRamp (0, 0, length, 1.0f, 0.0f);
result.applyGainRamp (1, 0, length, 0.0f, 1.0f);
return result;
}
static void addDiracImpulse (const AudioBlock<float>& block)
{
block.clear();
for (size_t channel = 0; channel != block.getNumChannels(); ++channel)
block.setSample ((int) channel, 0, 1.0f);
}
void checkForNans (const AudioBlock<float>& block)
{
for (size_t channel = 0; channel != block.getNumChannels(); ++channel)
for (size_t sample = 0; sample != block.getNumSamples(); ++sample)
expect (! std::isnan (block.getSample ((int) channel, (int) sample)));
}
void checkAllChannelsNonZero (const AudioBlock<float>& block)
{
for (size_t i = 0; i != block.getNumChannels(); ++i)
{
const auto* channel = block.getChannelPointer (i);
expect (std::any_of (channel, channel + block.getNumSamples(), [] (float sample)
{
return ! approximatelyEqual (sample, 0.0f);
}));
}
}
template <typename T>
void nonAllocatingExpectWithinAbsoluteError (const T& a, const T& b, const T& error)
{
expect (std::abs (a - b) < error);
}
enum class InitSequence { prepareThenLoad, loadThenPrepare };
void checkLatency (const Convolution& convolution, const Convolution::Latency& latency)
{
const auto reportedLatency = convolution.getLatency();
if (latency.latencyInSamples == 0)
expect (reportedLatency == 0);
expect (reportedLatency >= latency.latencyInSamples);
}
void checkLatency (const Convolution&, const Convolution::NonUniform&) {}
template <typename ConvolutionConfig>
void testConvolution (const ProcessSpec& spec,
const ConvolutionConfig& config,
const AudioBuffer<float>& ir,
double irSampleRate,
Convolution::Stereo stereo,
Convolution::Trim trim,
Convolution::Normalise normalise,
const AudioBlock<const float>& expectedResult,
InitSequence initSequence)
{
AudioBuffer<float> buffer (static_cast<int> (spec.numChannels),
static_cast<int> (spec.maximumBlockSize));
AudioBlock<float> block { buffer };
ProcessContextReplacing<float> context { block };
const auto numBlocksPerSecond = (int) std::ceil (spec.sampleRate / spec.maximumBlockSize);
const auto numBlocksForImpulse = (int) std::ceil ((double) expectedResult.getNumSamples() / spec.maximumBlockSize);
AudioBuffer<float> outBuffer (static_cast<int> (spec.numChannels),
numBlocksForImpulse * static_cast<int> (spec.maximumBlockSize));
Convolution convolution (config);
auto copiedIr = ir;
if (initSequence == InitSequence::loadThenPrepare)
convolution.loadImpulseResponse (std::move (copiedIr), irSampleRate, stereo, trim, normalise);
convolution.prepare (spec);
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
if (initSequence == InitSequence::prepareThenLoad)
convolution.loadImpulseResponse (std::move (copiedIr), irSampleRate, stereo, trim, normalise);
checkLatency (convolution, config);
auto processBlocksWithDiracImpulse = [&]
{
for (auto i = 0; i != numBlocksForImpulse; ++i)
{
if (i == 0)
addDiracImpulse (block);
else
block.clear();
convolution.process (context);
for (auto c = 0; c != static_cast<int> (spec.numChannels); ++c)
{
outBuffer.copyFrom (c,
i * static_cast<int> (spec.maximumBlockSize),
block.getChannelPointer (static_cast<size_t> (c)),
static_cast<int> (spec.maximumBlockSize));
}
}
};
// If we load an IR while the convolution is already running, we'll need to wait
// for it to be loaded on a background thread
if (initSequence == InitSequence::prepareThenLoad)
{
const auto time = Time::getMillisecondCounter();
// Wait 10 seconds to load the impulse response
while (Time::getMillisecondCounter() - time < 10'000)
{
processBlocksWithDiracImpulse();
// Check if the impulse response was loaded
if (! approximatelyEqual (block.getSample (0, 1), 0.0f))
break;
}
}
// At this point, our convolution should be loaded and the current IR size should
// match the expected result size
expect (convolution.getCurrentIRSize() == static_cast<int> (expectedResult.getNumSamples()));
// Make sure we get any smoothing out of the way
nTimes (numBlocksPerSecond, processBlocksWithDiracImpulse);
nTimes (5, [&]
{
processBlocksWithDiracImpulse();
const auto actualLatency = static_cast<size_t> (convolution.getLatency());
// The output should be the same as the IR
for (size_t c = 0; c != static_cast<size_t> (expectedResult.getNumChannels()); ++c)
{
for (size_t i = 0; i != static_cast<size_t> (expectedResult.getNumSamples()); ++i)
{
const auto equivalentSample = i + actualLatency;
if (static_cast<int> (equivalentSample) >= outBuffer.getNumSamples())
continue;
nonAllocatingExpectWithinAbsoluteError (outBuffer.getSample ((int) c, (int) equivalentSample),
expectedResult.getSample ((int) c, (int) i),
0.01f);
}
}
});
}
template <typename ConvolutionConfig>
void testConvolution (const ProcessSpec& spec,
const ConvolutionConfig& config,
const AudioBuffer<float>& ir,
double irSampleRate,
Convolution::Stereo stereo,
Convolution::Trim trim,
Convolution::Normalise normalise,
const AudioBlock<const float>& expectedResult)
{
for (const auto sequence : { InitSequence::prepareThenLoad, InitSequence::loadThenPrepare })
testConvolution (spec, config, ir, irSampleRate, stereo, trim, normalise, expectedResult, sequence);
}
public:
ConvolutionTest()
: UnitTest ("Convolution", UnitTestCategories::dsp)
{}
void runTest() override
{
const ProcessSpec spec { 44100.0, 512, 2 };
AudioBuffer<float> buffer (static_cast<int> (spec.numChannels),
static_cast<int> (spec.maximumBlockSize));
AudioBlock<float> block { buffer };
ProcessContextReplacing<float> context { block };
const auto impulseData = []
{
Random random;
AudioBuffer<float> result (2, 1000);
for (auto channel = 0; channel != result.getNumChannels(); ++channel)
for (auto sample = 0; sample != result.getNumSamples(); ++sample)
result.setSample (channel, sample, random.nextFloat());
return result;
}();
beginTest ("Impulse responses can be loaded without allocating on the audio thread");
{
Convolution convolution;
convolution.prepare (spec);
auto copy = impulseData;
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
nTimes (100, [&]
{
convolution.loadImpulseResponse (std::move (copy),
1000,
Convolution::Stereo::yes,
Convolution::Trim::yes,
Convolution::Normalise::no);
addDiracImpulse (block);
convolution.process (context);
checkForNans (block);
});
}
beginTest ("Convolution can be reset without allocating on the audio thread");
{
Convolution convolution;
convolution.prepare (spec);
auto copy = impulseData;
convolution.loadImpulseResponse (std::move (copy),
1000,
Convolution::Stereo::yes,
Convolution::Trim::yes,
Convolution::Normalise::yes);
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
nTimes (100, [&]
{
addDiracImpulse (block);
convolution.reset();
convolution.process (context);
convolution.reset();
});
checkForNans (block);
}
beginTest ("Completely empty IRs don't crash");
{
AudioBuffer<float> emptyBuffer;
Convolution convolution;
convolution.prepare (spec);
auto copy = impulseData;
convolution.loadImpulseResponse (std::move (copy),
2000,
Convolution::Stereo::yes,
Convolution::Trim::yes,
Convolution::Normalise::yes);
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
nTimes (100, [&]
{
addDiracImpulse (block);
convolution.reset();
convolution.process (context);
convolution.reset();
});
checkForNans (block);
}
beginTest ("Convolutions can cope with a change in samplerate and blocksize");
{
Convolution convolution;
auto copy = impulseData;
convolution.loadImpulseResponse (std::move (copy),
2000,
Convolution::Stereo::yes,
Convolution::Trim::no,
Convolution::Normalise::yes);
const dsp::ProcessSpec specs[] = { { 96'000.0, 1024, 2 },
{ 48'000.0, 512, 2 },
{ 44'100.0, 256, 2 } };
for (const auto& thisSpec : specs)
{
convolution.prepare (thisSpec);
expectWithinAbsoluteError ((double) convolution.getCurrentIRSize(),
thisSpec.sampleRate * 0.5,
1.0);
juce::AudioBuffer<float> thisBuffer ((int) thisSpec.numChannels,
(int) thisSpec.maximumBlockSize);
AudioBlock<float> thisBlock { thisBuffer };
ProcessContextReplacing<float> thisContext { thisBlock };
nTimes (100, [&]
{
addDiracImpulse (thisBlock);
convolution.process (thisContext);
checkForNans (thisBlock);
checkAllChannelsNonZero (thisBlock);
});
}
}
beginTest ("Short uniform convolutions work");
{
const auto ramp = makeRamp (static_cast<int> (spec.maximumBlockSize) / 2);
testConvolution (spec,
Convolution::Latency { 0 },
ramp,
spec.sampleRate,
Convolution::Stereo::yes,
Convolution::Trim::yes,
Convolution::Normalise::no,
ramp);
}
beginTest ("Longer uniform convolutions work");
{
const auto ramp = makeRamp (static_cast<int> (spec.maximumBlockSize) * 8);
testConvolution (spec,
Convolution::Latency { 0 },
ramp,
spec.sampleRate,
Convolution::Stereo::yes,
Convolution::Trim::yes,
Convolution::Normalise::no,
ramp);
}
beginTest ("Normalisation works");
{
const auto ramp = makeRamp (static_cast<int> (spec.maximumBlockSize) * 8);
auto copy = ramp;
const auto channels = copy.getArrayOfWritePointers();
const auto numChannels = copy.getNumChannels();
const auto numSamples = copy.getNumSamples();
const auto factor = 0.125f / std::sqrt (std::accumulate (channels, channels + numChannels, 0.0f,
[numSamples] (auto max, auto* channel)
{
return juce::jmax (max, std::accumulate (channel, channel + numSamples, 0.0f,
[] (auto sum, auto sample)
{
return sum + sample * sample;
}));
}));
std::for_each (channels, channels + numChannels, [factor, numSamples] (auto* channel)
{
FloatVectorOperations::multiply (channel, factor, numSamples);
});
testConvolution (spec,
Convolution::Latency { 0 },
ramp,
spec.sampleRate,
Convolution::Stereo::yes,
Convolution::Trim::yes,
Convolution::Normalise::yes,
copy);
}
beginTest ("Stereo convolutions work");
{
const auto ramp = makeStereoRamp (static_cast<int> (spec.maximumBlockSize) * 5);
testConvolution (spec,
Convolution::Latency { 0 },
ramp,
spec.sampleRate,
Convolution::Stereo::yes,
Convolution::Trim::yes,
Convolution::Normalise::no,
ramp);
}
beginTest ("Stereo IRs only use first channel if stereo is disabled");
{
const auto length = static_cast<int> (spec.maximumBlockSize) * 5;
const auto ramp = makeStereoRamp (length);
const float* channels[] { ramp.getReadPointer (0), ramp.getReadPointer (0) };
testConvolution (spec,
Convolution::Latency { 0 },
ramp,
spec.sampleRate,
Convolution::Stereo::no,
Convolution::Trim::yes,
Convolution::Normalise::no,
AudioBlock<const float> (channels, numElementsInArray (channels), (size_t) length));
}
beginTest ("IRs with extra silence are trimmed appropriately");
{
const auto length = static_cast<int> (spec.maximumBlockSize) * 3;
const auto ramp = makeRamp (length);
AudioBuffer<float> paddedRamp (ramp.getNumChannels(), ramp.getNumSamples() * 2);
paddedRamp.clear();
const auto offset = (paddedRamp.getNumSamples() - ramp.getNumSamples()) / 2;
for (auto channel = 0; channel != ramp.getNumChannels(); ++channel)
paddedRamp.copyFrom (channel, offset, ramp.getReadPointer (channel), length);
testConvolution (spec,
Convolution::Latency { 0 },
paddedRamp,
spec.sampleRate,
Convolution::Stereo::no,
Convolution::Trim::yes,
Convolution::Normalise::no,
ramp);
}
beginTest ("IRs are resampled if their sample rate is different to the playback rate");
{
for (const auto resampleRatio : { 0.1, 0.5, 2.0, 10.0 })
{
const auto length = static_cast<int> (spec.maximumBlockSize) * 2;
const auto ramp = makeStereoRamp (length);
const auto resampled = [&]
{
AudioBuffer<float> original = ramp;
MemoryAudioSource memorySource (original, false);
ResamplingAudioSource resamplingSource (&memorySource, false, original.getNumChannels());
const auto finalSize = roundToInt (original.getNumSamples() / resampleRatio);
resamplingSource.setResamplingRatio (resampleRatio);
resamplingSource.prepareToPlay (finalSize, spec.sampleRate * resampleRatio);
AudioBuffer<float> result (original.getNumChannels(), finalSize);
resamplingSource.getNextAudioBlock ({ &result, 0, result.getNumSamples() });
result.applyGain ((float) resampleRatio);
return result;
}();
testConvolution (spec,
Convolution::Latency { 0 },
ramp,
spec.sampleRate * resampleRatio,
Convolution::Stereo::yes,
Convolution::Trim::yes,
Convolution::Normalise::no,
resampled);
}
}
beginTest ("Non-uniform convolutions work");
{
const auto ramp = makeRamp (static_cast<int> (spec.maximumBlockSize) * 8);
for (auto headSize : { spec.maximumBlockSize / 2, spec.maximumBlockSize, spec.maximumBlockSize * 9 })
{
testConvolution (spec,
Convolution::NonUniform { static_cast<int> (headSize) },
ramp,
spec.sampleRate,
Convolution::Stereo::yes,
Convolution::Trim::yes,
Convolution::Normalise::no,
ramp);
}
}
beginTest ("Convolutions with latency work");
{
const auto ramp = makeRamp (static_cast<int> (spec.maximumBlockSize) * 8);
using BlockSize = decltype (spec.maximumBlockSize);
for (auto latency : { static_cast<BlockSize> (0),
spec.maximumBlockSize / 3,
spec.maximumBlockSize,
spec.maximumBlockSize * 2,
static_cast<BlockSize> (spec.maximumBlockSize * 2.5) })
{
testConvolution (spec,
Convolution::Latency { static_cast<int> (latency) },
ramp,
spec.sampleRate,
Convolution::Stereo::yes,
Convolution::Trim::yes,
Convolution::Normalise::no,
ramp);
}
}
}
};
ConvolutionTest convolutionUnitTest;
}
} // namespace juce::dsp
#undef JUCE_FAIL_ON_ALLOCATION_IN_SCOPE
+998
View File
@@ -0,0 +1,998 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce::dsp
{
struct FFT::Instance
{
virtual ~Instance() = default;
virtual void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept = 0;
virtual void performRealOnlyForwardTransform (float*, bool) const noexcept = 0;
virtual void performRealOnlyInverseTransform (float*) const noexcept = 0;
};
struct FFT::Engine
{
Engine (int priorityToUse) : enginePriority (priorityToUse)
{
auto& list = getEngines();
list.add (this);
std::sort (list.begin(), list.end(), [] (Engine* a, Engine* b) { return b->enginePriority < a->enginePriority; });
}
virtual ~Engine() = default;
virtual FFT::Instance* create (int order) const = 0;
//==============================================================================
static FFT::Instance* createBestEngineForPlatform (int order)
{
for (auto* engine : getEngines())
if (auto* instance = engine->create (order))
return instance;
jassertfalse; // This should never happen as the fallback engine should always work!
return nullptr;
}
private:
static Array<Engine*>& getEngines()
{
static Array<Engine*> engines;
return engines;
}
int enginePriority; // used so that faster engines have priority over slower ones
};
template <typename InstanceToUse>
struct FFT::EngineImpl : public FFT::Engine
{
EngineImpl() : FFT::Engine (InstanceToUse::priority) {}
FFT::Instance* create (int order) const override { return InstanceToUse::create (order); }
};
//==============================================================================
//==============================================================================
struct FFTFallback final : public FFT::Instance
{
// this should have the least priority of all engines
static constexpr int priority = -1;
static FFTFallback* create (int order)
{
return new FFTFallback (order);
}
FFTFallback (int order)
{
configForward.reset (new FFTConfig (1 << order, false));
configInverse.reset (new FFTConfig (1 << order, true));
size = 1 << order;
}
void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept override
{
if (size == 1)
{
*output = *input;
return;
}
const SpinLock::ScopedLockType sl (processLock);
jassert (configForward != nullptr);
if (inverse)
{
configInverse->perform (input, output);
const float scaleFactor = 1.0f / (float) size;
for (int i = 0; i < size; ++i)
output[i] *= scaleFactor;
}
else
{
configForward->perform (input, output);
}
}
const size_t maxFFTScratchSpaceToAlloca = 256 * 1024;
void performRealOnlyForwardTransform (float* d, bool) const noexcept override
{
if (size == 1)
return;
const size_t scratchSize = 16 + (size_t) size * sizeof (Complex<float>);
if (scratchSize < maxFFTScratchSpaceToAlloca)
{
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6255)
performRealOnlyForwardTransform (static_cast<Complex<float>*> (alloca (scratchSize)), d);
JUCE_END_IGNORE_WARNINGS_MSVC
}
else
{
HeapBlock<char> heapSpace (scratchSize);
performRealOnlyForwardTransform (unalignedPointerCast<Complex<float>*> (heapSpace.getData()), d);
}
}
void performRealOnlyInverseTransform (float* d) const noexcept override
{
if (size == 1)
return;
const size_t scratchSize = 16 + (size_t) size * sizeof (Complex<float>);
if (scratchSize < maxFFTScratchSpaceToAlloca)
{
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6255)
performRealOnlyInverseTransform (static_cast<Complex<float>*> (alloca (scratchSize)), d);
JUCE_END_IGNORE_WARNINGS_MSVC
}
else
{
HeapBlock<char> heapSpace (scratchSize);
performRealOnlyInverseTransform (unalignedPointerCast<Complex<float>*> (heapSpace.getData()), d);
}
}
void performRealOnlyForwardTransform (Complex<float>* scratch, float* d) const noexcept
{
for (int i = 0; i < size; ++i)
scratch[i] = { d[i], 0 };
perform (scratch, reinterpret_cast<Complex<float>*> (d), false);
}
void performRealOnlyInverseTransform (Complex<float>* scratch, float* d) const noexcept
{
auto* input = reinterpret_cast<Complex<float>*> (d);
for (int i = size >> 1; i < size; ++i)
input[i] = std::conj (input[size - i]);
perform (input, scratch, true);
for (int i = 0; i < size; ++i)
{
d[i] = scratch[i].real();
d[i + size] = scratch[i].imag();
}
}
//==============================================================================
struct FFTConfig
{
FFTConfig (int sizeOfFFT, bool isInverse)
: fftSize (sizeOfFFT), inverse (isInverse), twiddleTable ((size_t) sizeOfFFT)
{
auto inverseFactor = (inverse ? 2.0 : -2.0) * MathConstants<double>::pi / (double) fftSize;
if (fftSize <= 4)
{
for (int i = 0; i < fftSize; ++i)
{
auto phase = i * inverseFactor;
twiddleTable[i] = { (float) std::cos (phase),
(float) std::sin (phase) };
}
}
else
{
for (int i = 0; i < fftSize / 4; ++i)
{
auto phase = i * inverseFactor;
twiddleTable[i] = { (float) std::cos (phase),
(float) std::sin (phase) };
}
for (int i = fftSize / 4; i < fftSize / 2; ++i)
{
auto other = twiddleTable[i - fftSize / 4];
twiddleTable[i] = { inverse ? -other.imag() : other.imag(),
inverse ? other.real() : -other.real() };
}
twiddleTable[fftSize / 2].real (-1.0f);
twiddleTable[fftSize / 2].imag (0.0f);
for (int i = fftSize / 2; i < fftSize; ++i)
{
auto index = fftSize / 2 - (i - fftSize / 2);
twiddleTable[i] = conj (twiddleTable[index]);
}
}
auto root = (int) std::sqrt ((double) fftSize);
int divisor = 4, n = fftSize;
for (int i = 0; i < numElementsInArray (factors); ++i)
{
while ((n % divisor) != 0)
{
if (divisor == 2) divisor = 3;
else if (divisor == 4) divisor = 2;
else divisor += 2;
if (divisor > root)
divisor = n;
}
n /= divisor;
jassert (divisor == 1 || divisor == 2 || divisor == 4);
factors[i].radix = divisor;
factors[i].length = n;
}
}
void perform (const Complex<float>* input, Complex<float>* output) const noexcept
{
perform (input, output, 1, 1, factors);
}
const int fftSize;
const bool inverse;
struct Factor { int radix, length; };
Factor factors[32];
HeapBlock<Complex<float>> twiddleTable;
void perform (const Complex<float>* input, Complex<float>* output, int stride, int strideIn, const Factor* facs) const noexcept
{
auto factor = *facs++;
auto* originalOutput = output;
auto* outputEnd = output + factor.radix * factor.length;
if (stride == 1 && factor.radix <= 5)
{
for (int i = 0; i < factor.radix; ++i)
perform (input + stride * strideIn * i, output + i * factor.length, stride * factor.radix, strideIn, facs);
butterfly (factor, output, stride);
return;
}
if (factor.length == 1)
{
do
{
*output++ = *input;
input += stride * strideIn;
}
while (output < outputEnd);
}
else
{
do
{
perform (input, output, stride * factor.radix, strideIn, facs);
input += stride * strideIn;
output += factor.length;
}
while (output < outputEnd);
}
butterfly (factor, originalOutput, stride);
}
void butterfly (const Factor factor, Complex<float>* data, int stride) const noexcept
{
switch (factor.radix)
{
case 1: break;
case 2: butterfly2 (data, stride, factor.length); return;
case 4: butterfly4 (data, stride, factor.length); return;
default: jassertfalse; break;
}
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6255)
auto* scratch = static_cast<Complex<float>*> (alloca ((size_t) factor.radix * sizeof (Complex<float>)));
JUCE_END_IGNORE_WARNINGS_MSVC
for (int i = 0; i < factor.length; ++i)
{
for (int k = i, q1 = 0; q1 < factor.radix; ++q1)
{
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6386)
scratch[q1] = data[k];
JUCE_END_IGNORE_WARNINGS_MSVC
k += factor.length;
}
for (int k = i, q1 = 0; q1 < factor.radix; ++q1)
{
int twiddleIndex = 0;
data[k] = scratch[0];
for (int q = 1; q < factor.radix; ++q)
{
twiddleIndex += stride * k;
if (twiddleIndex >= fftSize)
twiddleIndex -= fftSize;
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6385)
data[k] += scratch[q] * twiddleTable[twiddleIndex];
JUCE_END_IGNORE_WARNINGS_MSVC
}
k += factor.length;
}
}
}
void butterfly2 (Complex<float>* data, const int stride, const int length) const noexcept
{
auto* dataEnd = data + length;
auto* tw = twiddleTable.getData();
for (int i = length; --i >= 0;)
{
auto s = *dataEnd;
s *= (*tw);
tw += stride;
*dataEnd++ = *data - s;
*data++ += s;
}
}
void butterfly4 (Complex<float>* data, const int stride, const int length) const noexcept
{
auto lengthX2 = length * 2;
auto lengthX3 = length * 3;
auto strideX2 = stride * 2;
auto strideX3 = stride * 3;
auto* twiddle1 = twiddleTable.getData();
auto* twiddle2 = twiddle1;
auto* twiddle3 = twiddle1;
for (int i = length; --i >= 0;)
{
auto s0 = data[length] * *twiddle1;
auto s1 = data[lengthX2] * *twiddle2;
auto s2 = data[lengthX3] * *twiddle3;
auto s3 = s0; s3 += s2;
auto s4 = s0; s4 -= s2;
auto s5 = *data; s5 -= s1;
*data += s1;
data[lengthX2] = *data;
data[lengthX2] -= s3;
twiddle1 += stride;
twiddle2 += strideX2;
twiddle3 += strideX3;
*data += s3;
if (inverse)
{
data[length] = { s5.real() - s4.imag(),
s5.imag() + s4.real() };
data[lengthX3] = { s5.real() + s4.imag(),
s5.imag() - s4.real() };
}
else
{
data[length] = { s5.real() + s4.imag(),
s5.imag() - s4.real() };
data[lengthX3] = { s5.real() - s4.imag(),
s5.imag() + s4.real() };
}
++data;
}
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FFTConfig)
};
//==============================================================================
SpinLock processLock;
std::unique_ptr<FFTConfig> configForward, configInverse;
int size;
};
FFT::EngineImpl<FFTFallback> fftFallback;
//==============================================================================
//==============================================================================
#if (JUCE_MAC || JUCE_IOS) && JUCE_USE_VDSP_FRAMEWORK
struct AppleFFT final : public FFT::Instance
{
static constexpr int priority = 5;
static AppleFFT* create (int order)
{
return new AppleFFT (order);
}
AppleFFT (int orderToUse)
: order (static_cast<vDSP_Length> (orderToUse)),
fftSetup (vDSP_create_fftsetup (order, 2)),
forwardNormalisation (0.5f),
inverseNormalisation (1.0f / static_cast<float> (1 << order))
{}
~AppleFFT() override
{
if (fftSetup != nullptr)
{
vDSP_destroy_fftsetup (fftSetup);
fftSetup = nullptr;
}
}
void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept override
{
auto size = (1 << order);
DSPSplitComplex splitInput (toSplitComplex (const_cast<Complex<float>*> (input)));
DSPSplitComplex splitOutput (toSplitComplex (output));
vDSP_fft_zop (fftSetup, &splitInput, 2, &splitOutput, 2,
order, inverse ? kFFTDirection_Inverse : kFFTDirection_Forward);
float factor = (inverse ? inverseNormalisation : forwardNormalisation * 2.0f);
vDSP_vsmul ((float*) output, 1, &factor, (float*) output, 1, static_cast<size_t> (size << 1));
}
void performRealOnlyForwardTransform (float* inoutData, bool ignoreNegativeFreqs) const noexcept override
{
auto size = (1 << order);
auto* inout = reinterpret_cast<Complex<float>*> (inoutData);
auto splitInOut (toSplitComplex (inout));
inoutData[size] = 0.0f;
vDSP_fft_zrip (fftSetup, &splitInOut, 2, order, kFFTDirection_Forward);
vDSP_vsmul (inoutData, 1, &forwardNormalisation, inoutData, 1, static_cast<size_t> (size << 1));
mirrorResult (inout, ignoreNegativeFreqs);
}
void performRealOnlyInverseTransform (float* inoutData) const noexcept override
{
auto* inout = reinterpret_cast<Complex<float>*> (inoutData);
auto size = (1 << order);
auto splitInOut (toSplitComplex (inout));
// Imaginary part of nyquist and DC frequencies are always zero
// so Apple uses the imaginary part of the DC frequency to store
// the real part of the nyquist frequency
if (size != 1)
inout[0] = Complex<float> (inout[0].real(), inout[size >> 1].real());
vDSP_fft_zrip (fftSetup, &splitInOut, 2, order, kFFTDirection_Inverse);
vDSP_vsmul (inoutData, 1, &inverseNormalisation, inoutData, 1, static_cast<size_t> (size << 1));
vDSP_vclr (inoutData + size, 1, static_cast<size_t> (size));
}
private:
//==============================================================================
void mirrorResult (Complex<float>* out, bool ignoreNegativeFreqs) const noexcept
{
auto size = (1 << order);
auto i = size >> 1;
// Imaginary part of nyquist and DC frequencies are always zero
// so Apple uses the imaginary part of the DC frequency to store
// the real part of the nyquist frequency
out[i++] = { out[0].imag(), 0.0 };
out[0] = { out[0].real(), 0.0 };
if (! ignoreNegativeFreqs)
for (; i < size; ++i)
out[i] = std::conj (out[size - i]);
}
static DSPSplitComplex toSplitComplex (Complex<float>* data) noexcept
{
// this assumes that Complex interleaves real and imaginary parts
// and is tightly packed.
return { reinterpret_cast<float*> (data),
reinterpret_cast<float*> (data) + 1};
}
//==============================================================================
vDSP_Length order;
FFTSetup fftSetup;
float forwardNormalisation, inverseNormalisation;
};
FFT::EngineImpl<AppleFFT> appleFFT;
#endif
//==============================================================================
//==============================================================================
#if JUCE_DSP_USE_SHARED_FFTW || JUCE_DSP_USE_STATIC_FFTW
#if JUCE_DSP_USE_STATIC_FFTW
extern "C"
{
void* fftwf_plan_dft_1d (int, void*, void*, int, int);
void* fftwf_plan_dft_r2c_1d (int, void*, void*, int);
void* fftwf_plan_dft_c2r_1d (int, void*, void*, int);
void fftwf_destroy_plan (void*);
void fftwf_execute_dft (void*, void*, void*);
void fftwf_execute_dft_r2c (void*, void*, void*);
void fftwf_execute_dft_c2r (void*, void*, void*);
}
#endif
struct FFTWImpl : public FFT::Instance
{
#if JUCE_DSP_USE_STATIC_FFTW
// if the JUCE developer has gone through the hassle of statically
// linking in fftw, they probably want to use it
static constexpr int priority = 10;
#else
static constexpr int priority = 3;
#endif
struct FFTWPlan;
using FFTWPlanRef = FFTWPlan*;
enum
{
measure = 0,
unaligned = (1 << 1),
estimate = (1 << 6)
};
struct Symbols
{
FFTWPlanRef (*plan_dft_fftw) (unsigned, Complex<float>*, Complex<float>*, int, unsigned);
FFTWPlanRef (*plan_r2c_fftw) (unsigned, float*, Complex<float>*, unsigned);
FFTWPlanRef (*plan_c2r_fftw) (unsigned, Complex<float>*, float*, unsigned);
void (*destroy_fftw) (FFTWPlanRef);
void (*execute_dft_fftw) (FFTWPlanRef, const Complex<float>*, Complex<float>*);
void (*execute_r2c_fftw) (FFTWPlanRef, float*, Complex<float>*);
void (*execute_c2r_fftw) (FFTWPlanRef, Complex<float>*, float*);
#if JUCE_DSP_USE_STATIC_FFTW
template <typename FuncPtr, typename ActualSymbolType>
static bool symbol (FuncPtr& dst, ActualSymbolType sym)
{
dst = reinterpret_cast<FuncPtr> (sym);
return true;
}
#else
template <typename FuncPtr>
static bool symbol (DynamicLibrary& lib, FuncPtr& dst, const char* name)
{
dst = reinterpret_cast<FuncPtr> (lib.getFunction (name));
return (dst != nullptr);
}
#endif
};
static FFTWImpl* create (int order)
{
DynamicLibrary lib;
#if ! JUCE_DSP_USE_STATIC_FFTW
#if JUCE_MAC
auto libName = "libfftw3f.dylib";
#elif JUCE_WINDOWS
auto libName = "libfftw3f.dll";
#else
auto libName = "libfftw3f.so";
#endif
if (lib.open (libName))
#endif
{
Symbols symbols;
#if JUCE_DSP_USE_STATIC_FFTW
if (! Symbols::symbol (symbols.plan_dft_fftw, fftwf_plan_dft_1d)) return nullptr;
if (! Symbols::symbol (symbols.plan_r2c_fftw, fftwf_plan_dft_r2c_1d)) return nullptr;
if (! Symbols::symbol (symbols.plan_c2r_fftw, fftwf_plan_dft_c2r_1d)) return nullptr;
if (! Symbols::symbol (symbols.destroy_fftw, fftwf_destroy_plan)) return nullptr;
if (! Symbols::symbol (symbols.execute_dft_fftw, fftwf_execute_dft)) return nullptr;
if (! Symbols::symbol (symbols.execute_r2c_fftw, fftwf_execute_dft_r2c)) return nullptr;
if (! Symbols::symbol (symbols.execute_c2r_fftw, fftwf_execute_dft_c2r)) return nullptr;
#else
if (! Symbols::symbol (lib, symbols.plan_dft_fftw, "fftwf_plan_dft_1d")) return nullptr;
if (! Symbols::symbol (lib, symbols.plan_r2c_fftw, "fftwf_plan_dft_r2c_1d")) return nullptr;
if (! Symbols::symbol (lib, symbols.plan_c2r_fftw, "fftwf_plan_dft_c2r_1d")) return nullptr;
if (! Symbols::symbol (lib, symbols.destroy_fftw, "fftwf_destroy_plan")) return nullptr;
if (! Symbols::symbol (lib, symbols.execute_dft_fftw, "fftwf_execute_dft")) return nullptr;
if (! Symbols::symbol (lib, symbols.execute_r2c_fftw, "fftwf_execute_dft_r2c")) return nullptr;
if (! Symbols::symbol (lib, symbols.execute_c2r_fftw, "fftwf_execute_dft_c2r")) return nullptr;
#endif
return new FFTWImpl (static_cast<size_t> (order), std::move (lib), symbols);
}
return nullptr;
}
FFTWImpl (size_t orderToUse, DynamicLibrary&& libraryToUse, const Symbols& symbols)
: fftwLibrary (std::move (libraryToUse)), fftw (symbols), order (static_cast<size_t> (orderToUse))
{
ScopedLock lock (getFFTWPlanLock());
auto n = (1u << order);
HeapBlock<Complex<float>> in (n), out (n);
c2cForward = fftw.plan_dft_fftw (n, in.getData(), out.getData(), -1, unaligned | estimate);
c2cInverse = fftw.plan_dft_fftw (n, in.getData(), out.getData(), +1, unaligned | estimate);
r2c = fftw.plan_r2c_fftw (n, (float*) in.getData(), in.getData(), unaligned | estimate);
c2r = fftw.plan_c2r_fftw (n, in.getData(), (float*) in.getData(), unaligned | estimate);
}
~FFTWImpl() override
{
ScopedLock lock (getFFTWPlanLock());
fftw.destroy_fftw (c2cForward);
fftw.destroy_fftw (c2cInverse);
fftw.destroy_fftw (r2c);
fftw.destroy_fftw (c2r);
}
void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept override
{
if (inverse)
{
auto n = (1u << order);
fftw.execute_dft_fftw (c2cInverse, input, output);
FloatVectorOperations::multiply ((float*) output, 1.0f / static_cast<float> (n), (int) n << 1);
}
else
{
fftw.execute_dft_fftw (c2cForward, input, output);
}
}
void performRealOnlyForwardTransform (float* inputOutputData, bool ignoreNegativeFreqs) const noexcept override
{
if (order == 0)
return;
auto* out = reinterpret_cast<Complex<float>*> (inputOutputData);
fftw.execute_r2c_fftw (r2c, inputOutputData, out);
auto size = (1 << order);
if (! ignoreNegativeFreqs)
for (int i = size >> 1; i < size; ++i)
out[i] = std::conj (out[size - i]);
}
void performRealOnlyInverseTransform (float* inputOutputData) const noexcept override
{
auto n = (1u << order);
fftw.execute_c2r_fftw (c2r, (Complex<float>*) inputOutputData, inputOutputData);
FloatVectorOperations::multiply ((float*) inputOutputData, 1.0f / static_cast<float> (n), (int) n);
}
//==============================================================================
// fftw's plan_* and destroy_* methods are NOT thread safe. So we need to share
// a lock between all instances of FFTWImpl
static CriticalSection& getFFTWPlanLock() noexcept
{
static CriticalSection cs;
return cs;
}
//==============================================================================
DynamicLibrary fftwLibrary;
Symbols fftw;
size_t order;
FFTWPlanRef c2cForward, c2cInverse, r2c, c2r;
};
FFT::EngineImpl<FFTWImpl> fftwEngine;
#endif
//==============================================================================
//==============================================================================
#if JUCE_DSP_USE_INTEL_MKL
struct IntelFFT final : public FFT::Instance
{
static constexpr int priority = 8;
static bool succeeded (MKL_LONG status) noexcept { return status == 0; }
static IntelFFT* create (int orderToUse)
{
DFTI_DESCRIPTOR_HANDLE mklc2c, mklc2r;
if (DftiCreateDescriptor (&mklc2c, DFTI_SINGLE, DFTI_COMPLEX, 1, 1 << orderToUse) == 0)
{
if (succeeded (DftiSetValue (mklc2c, DFTI_PLACEMENT, DFTI_NOT_INPLACE))
&& succeeded (DftiSetValue (mklc2c, DFTI_BACKWARD_SCALE, 1.0f / static_cast<float> (1 << orderToUse)))
&& succeeded (DftiCommitDescriptor (mklc2c)))
{
if (succeeded (DftiCreateDescriptor (&mklc2r, DFTI_SINGLE, DFTI_REAL, 1, 1 << orderToUse)))
{
if (succeeded (DftiSetValue (mklc2r, DFTI_PLACEMENT, DFTI_INPLACE))
&& succeeded (DftiSetValue (mklc2r, DFTI_BACKWARD_SCALE, 1.0f / static_cast<float> (1 << orderToUse)))
&& succeeded (DftiCommitDescriptor (mklc2r)))
{
return new IntelFFT (static_cast<size_t> (orderToUse), mklc2c, mklc2r);
}
DftiFreeDescriptor (&mklc2r);
}
}
DftiFreeDescriptor (&mklc2c);
}
return {};
}
IntelFFT (size_t orderToUse, DFTI_DESCRIPTOR_HANDLE c2cToUse, DFTI_DESCRIPTOR_HANDLE cr2ToUse)
: order (orderToUse), c2c (c2cToUse), c2r (cr2ToUse)
{}
~IntelFFT() override
{
DftiFreeDescriptor (&c2c);
DftiFreeDescriptor (&c2r);
}
void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept override
{
if (inverse)
DftiComputeBackward (c2c, (void*) input, output);
else
DftiComputeForward (c2c, (void*) input, output);
}
void performRealOnlyForwardTransform (float* inputOutputData, bool ignoreNegativeFreqs) const noexcept override
{
if (order == 0)
return;
DftiComputeForward (c2r, inputOutputData);
auto* out = reinterpret_cast<Complex<float>*> (inputOutputData);
auto size = (1 << order);
if (! ignoreNegativeFreqs)
for (int i = size >> 1; i < size; ++i)
out[i] = std::conj (out[size - i]);
}
void performRealOnlyInverseTransform (float* inputOutputData) const noexcept override
{
DftiComputeBackward (c2r, inputOutputData);
}
size_t order;
DFTI_DESCRIPTOR_HANDLE c2c, c2r;
};
FFT::EngineImpl<IntelFFT> fftwEngine;
#endif
//==============================================================================
//==============================================================================
// Visual Studio should define no more than one of these, depending on the
// setting at 'Project' > 'Properties' > 'Configuration Properties' > 'Intel
// Performance Libraries' > 'Use Intel(R) IPP'
#if _IPP_SEQUENTIAL_STATIC || _IPP_SEQUENTIAL_DYNAMIC || _IPP_PARALLEL_STATIC || _IPP_PARALLEL_DYNAMIC
class IntelPerformancePrimitivesFFT final : public FFT::Instance
{
public:
static constexpr auto priority = 9;
static IntelPerformancePrimitivesFFT* create (const int order)
{
auto complexContext = Context<ComplexTraits>::create (order);
auto realContext = Context<RealTraits> ::create (order);
if (complexContext.isValid() && realContext.isValid())
return new IntelPerformancePrimitivesFFT (std::move (complexContext), std::move (realContext), order);
return {};
}
void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept override
{
if (inverse)
{
ippsFFTInv_CToC_32fc (reinterpret_cast<const Ipp32fc*> (input),
reinterpret_cast<Ipp32fc*> (output),
cplx.specPtr,
cplx.workBuf.get());
}
else
{
ippsFFTFwd_CToC_32fc (reinterpret_cast<const Ipp32fc*> (input),
reinterpret_cast<Ipp32fc*> (output),
cplx.specPtr,
cplx.workBuf.get());
}
}
void performRealOnlyForwardTransform (float* inoutData, bool ignoreNegativeFreqs) const noexcept override
{
ippsFFTFwd_RToCCS_32f_I (inoutData, real.specPtr, real.workBuf.get());
if (order == 0)
return;
auto* out = reinterpret_cast<Complex<float>*> (inoutData);
const auto size = (1 << order);
if (! ignoreNegativeFreqs)
for (auto i = size >> 1; i < size; ++i)
out[i] = std::conj (out[size - i]);
}
void performRealOnlyInverseTransform (float* inoutData) const noexcept override
{
ippsFFTInv_CCSToR_32f_I (inoutData, real.specPtr, real.workBuf.get());
}
private:
static constexpr auto flag = IPP_FFT_DIV_INV_BY_N;
static constexpr auto hint = ippAlgHintFast;
struct IppFree
{
template <typename Ptr>
void operator() (Ptr* ptr) const noexcept { ippsFree (ptr); }
};
using IppPtr = std::unique_ptr<Ipp8u[], IppFree>;
template <typename Traits>
struct Context
{
using SpecPtr = typename Traits::Spec*;
static Context create (const int order)
{
int specSize = 0, initSize = 0, workSize = 0;
if (Traits::getSize (order, flag, hint, &specSize, &initSize, &workSize) != ippStsNoErr)
return {};
const auto initBuf = IppPtr (ippsMalloc_8u (initSize));
auto specBuf = IppPtr (ippsMalloc_8u (specSize));
SpecPtr specPtr = nullptr;
if (Traits::init (&specPtr, order, flag, hint, specBuf.get(), initBuf.get()) != ippStsNoErr)
return {};
return { std::move (specBuf), IppPtr (ippsMalloc_8u (workSize)), specPtr };
}
Context() noexcept = default;
Context (IppPtr&& spec, IppPtr&& work, typename Traits::Spec* ptr) noexcept
: specBuf (std::move (spec)), workBuf (std::move (work)), specPtr (ptr)
{}
bool isValid() const noexcept { return specPtr != nullptr; }
IppPtr specBuf, workBuf;
SpecPtr specPtr = nullptr;
};
struct ComplexTraits
{
static constexpr auto getSize = ippsFFTGetSize_C_32fc;
static constexpr auto init = ippsFFTInit_C_32fc;
using Spec = IppsFFTSpec_C_32fc;
};
struct RealTraits
{
static constexpr auto getSize = ippsFFTGetSize_R_32f;
static constexpr auto init = ippsFFTInit_R_32f;
using Spec = IppsFFTSpec_R_32f;
};
IntelPerformancePrimitivesFFT (Context<ComplexTraits>&& complexToUse,
Context<RealTraits>&& realToUse,
const int orderToUse)
: cplx (std::move (complexToUse)),
real (std::move (realToUse)),
order (orderToUse)
{}
Context<ComplexTraits> cplx;
Context<RealTraits> real;
int order = 0;
};
FFT::EngineImpl<IntelPerformancePrimitivesFFT> intelPerformancePrimitivesFFT;
#endif
//==============================================================================
//==============================================================================
FFT::FFT (int order)
: engine (FFT::Engine::createBestEngineForPlatform (order)),
size (1 << order)
{
}
FFT::FFT (FFT&&) noexcept = default;
FFT& FFT::operator= (FFT&&) noexcept = default;
FFT::~FFT() = default;
void FFT::perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept
{
if (engine != nullptr)
engine->perform (input, output, inverse);
}
void FFT::performRealOnlyForwardTransform (float* inputOutputData, bool ignoreNegativeFreqs) const noexcept
{
if (engine != nullptr)
engine->performRealOnlyForwardTransform (inputOutputData, ignoreNegativeFreqs);
}
void FFT::performRealOnlyInverseTransform (float* inputOutputData) const noexcept
{
if (engine != nullptr)
engine->performRealOnlyInverseTransform (inputOutputData);
}
void FFT::performFrequencyOnlyForwardTransform (float* inputOutputData, bool ignoreNegativeFreqs) const noexcept
{
if (size == 1)
return;
performRealOnlyForwardTransform (inputOutputData, ignoreNegativeFreqs);
auto* out = reinterpret_cast<Complex<float>*> (inputOutputData);
const auto limit = ignoreNegativeFreqs ? (size / 2) + 1 : size;
for (int i = 0; i < limit; ++i)
inputOutputData[i] = std::abs (out[i]);
zeromem (inputOutputData + limit, static_cast<size_t> (size * 2 - limit) * sizeof (float));
}
} // namespace juce::dsp
+129
View File
@@ -0,0 +1,129 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce::dsp
{
/**
Performs a fast fourier transform.
This is only a simple low-footprint implementation and isn't tuned for speed - it may
be useful for simple applications where one of the more complex FFT libraries would be
overkill. (But in the future it may end up becoming optimised of course...)
The FFT class itself contains lookup tables, so there's some overhead in creating
one, you should create and cache an FFT object for each size/direction of transform
that you need, and re-use them to perform the actual operation.
@tags{DSP}
*/
class JUCE_API FFT
{
public:
//==============================================================================
/** Initialises an object for performing forward and inverse FFT with the given size.
The number of points the FFT will operate on will be 2 ^ order.
*/
FFT (int order);
/** Move constructor. */
FFT (FFT&&) noexcept;
/** Move assignment operator. */
FFT& operator= (FFT&&) noexcept;
/** Destructor. */
~FFT();
//==============================================================================
/** Performs an out-of-place FFT, either forward or inverse.
The arrays must contain at least getSize() elements.
*/
void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept;
/** Performs an in-place forward transform on a block of real data.
As the coefficients of the negative frequencies (frequencies higher than
N/2 or pi) are the complex conjugate of their positive counterparts,
it may not be necessary to calculate them for your particular application.
You can use onlyCalculateNonNegativeFrequencies to let the FFT
engine know that you do not plan on using them. Note that this is only a
hint: some FFT engines (currently only the Fallback engine), will still
calculate the negative frequencies even if onlyCalculateNonNegativeFrequencies
is true.
The size of the array passed in must be 2 * getSize(), and the first half
should contain your raw input sample data. On return, if
onlyCalculateNonNegativeFrequencies is false, the array will contain size
complex real + imaginary parts data interleaved. If
onlyCalculateNonNegativeFrequencies is true, the array will contain at least
(size / 2) + 1 complex numbers. Both outputs can be passed to
performRealOnlyInverseTransform() in order to convert it back to reals.
*/
void performRealOnlyForwardTransform (float* inputOutputData,
bool onlyCalculateNonNegativeFrequencies = false) const noexcept;
/** Performs a reverse operation to data created in performRealOnlyForwardTransform().
Although performRealOnlyInverseTransform will only use the first ((size / 2) + 1)
complex numbers, the size of the array passed in must still be 2 * getSize(), as some
FFT engines require the extra space for the calculation. On return, the first half of the
array will contain the reconstituted samples.
*/
void performRealOnlyInverseTransform (float* inputOutputData) const noexcept;
/** Takes an array and simply transforms it to the magnitude frequency response
spectrum. This may be handy for things like frequency displays or analysis.
The size of the array passed in must be 2 * getSize().
On return, if onlyCalculateNonNegativeFrequencies is false, the array will contain size
magnitude values. If onlyCalculateNonNegativeFrequencies is true, the array will contain
at least size / 2 + 1 magnitude values.
*/
void performFrequencyOnlyForwardTransform (float* inputOutputData,
bool onlyCalculateNonNegativeFrequencies = false) const noexcept;
/** Returns the number of data points that this FFT was created to work with. */
int getSize() const noexcept { return size; }
//==============================================================================
#ifndef DOXYGEN
/* internal */
struct Instance;
template <typename> struct EngineImpl;
#endif
private:
//==============================================================================
struct Engine;
std::unique_ptr<Instance> engine;
int size;
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FFT)
};
} // namespace juce::dsp
@@ -0,0 +1,215 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce::dsp
{
struct FFTUnitTest final : public UnitTest
{
FFTUnitTest()
: UnitTest ("FFT", UnitTestCategories::dsp)
{}
static void fillRandom (Random& random, Complex<float>* buffer, size_t n)
{
for (size_t i = 0; i < n; ++i)
buffer[i] = Complex<float> ((2.0f * random.nextFloat()) - 1.0f,
(2.0f * random.nextFloat()) - 1.0f);
}
static void fillRandom (Random& random, float* buffer, size_t n)
{
for (size_t i = 0; i < n; ++i)
buffer[i] = (2.0f * random.nextFloat()) - 1.0f;
}
static Complex<float> freqConvolution (const Complex<float>* in, float freq, size_t n)
{
Complex<float> sum (0.0, 0.0);
for (size_t i = 0; i < n; ++i)
sum += in[i] * exp (Complex<float> (0, static_cast<float> (i) * freq));
return sum;
}
static void performReferenceFourier (const Complex<float>* in, Complex<float>* out,
size_t n, bool reverse)
{
auto base_freq = static_cast<float> (((reverse ? 1.0 : -1.0) * MathConstants<double>::twoPi)
/ static_cast<float> (n));
for (size_t i = 0; i < n; ++i)
out[i] = freqConvolution (in, static_cast<float> (i) * base_freq, n);
}
static void performReferenceFourier (const float* in, Complex<float>* out,
size_t n, bool reverse)
{
HeapBlock<Complex<float>> buffer (n);
for (size_t i = 0; i < n; ++i)
buffer.getData()[i] = Complex<float> (in[i], 0.0f);
float base_freq = static_cast<float> (((reverse ? 1.0 : -1.0) * MathConstants<double>::twoPi)
/ static_cast<float> (n));
for (size_t i = 0; i < n; ++i)
out[i] = freqConvolution (buffer.getData(), static_cast<float> (i) * base_freq, n);
}
//==============================================================================
template <typename Type>
static bool checkArrayIsSimilar (Type* a, Type* b, size_t n) noexcept
{
for (size_t i = 0; i < n; ++i)
if (std::abs (a[i] - b[i]) > 1e-3f)
return false;
return true;
}
struct RealTest
{
static void run (FFTUnitTest& u)
{
Random random (378272);
for (size_t order = 0; order <= 8; ++order)
{
auto n = (1u << order);
FFT fft ((int) order);
HeapBlock<float> input (n);
HeapBlock<Complex<float>> reference (n), output (n);
fillRandom (random, input.getData(), n);
performReferenceFourier (input.getData(), reference.getData(), n, false);
// fill only first half with real numbers
zeromem (output.getData(), n * sizeof (Complex<float>));
memcpy (reinterpret_cast<float*> (output.getData()), input.getData(), n * sizeof (float));
fft.performRealOnlyForwardTransform ((float*) output.getData());
u.expect (checkArrayIsSimilar (reference.getData(), output.getData(), n));
// fill only first half with real numbers
zeromem (output.getData(), n * sizeof (Complex<float>));
memcpy (reinterpret_cast<float*> (output.getData()), input.getData(), n * sizeof (float));
fft.performRealOnlyForwardTransform ((float*) output.getData(), true);
std::fill (reference.getData() + ((n >> 1) + 1), reference.getData() + n, std::complex<float> (0.0f));
u.expect (checkArrayIsSimilar (reference.getData(), output.getData(), (n >> 1) + 1));
memcpy (output.getData(), reference.getData(), n * sizeof (Complex<float>));
fft.performRealOnlyInverseTransform ((float*) output.getData());
u.expect (checkArrayIsSimilar ((float*) output.getData(), input.getData(), n));
}
}
};
struct FrequencyOnlyTest
{
static void run (FFTUnitTest& u)
{
Random random (378272);
for (size_t order = 0; order <= 8; ++order)
{
auto n = (1u << order);
FFT fft ((int) order);
std::vector<float> inout ((size_t) n << 1), reference ((size_t) n << 1);
std::vector<Complex<float>> frequency (n);
fillRandom (random, inout.data(), n);
zeromem (reference.data(), sizeof (float) * ((size_t) n << 1));
performReferenceFourier (inout.data(), frequency.data(), n, false);
for (size_t i = 0; i < n; ++i)
reference[i] = std::abs (frequency[i]);
for (auto ignoreNegative : { false, true })
{
auto inoutCopy = inout;
fft.performFrequencyOnlyForwardTransform (inoutCopy.data(), ignoreNegative);
auto numMatching = ignoreNegative ? (n / 2) + 1 : n;
u.expect (checkArrayIsSimilar (inoutCopy.data(), reference.data(), numMatching));
}
}
}
};
struct ComplexTest
{
static void run (FFTUnitTest& u)
{
Random random (378272);
for (size_t order = 0; order <= 7; ++order)
{
auto n = (1u << order);
FFT fft ((int) order);
HeapBlock<Complex<float>> input (n), buffer (n), output (n), reference (n);
fillRandom (random, input.getData(), n);
performReferenceFourier (input.getData(), reference.getData(), n, false);
memcpy (buffer.getData(), input.getData(), sizeof (Complex<float>) * n);
fft.perform (buffer.getData(), output.getData(), false);
u.expect (checkArrayIsSimilar (output.getData(), reference.getData(), n));
memcpy (buffer.getData(), reference.getData(), sizeof (Complex<float>) * n);
fft.perform (buffer.getData(), output.getData(), true);
u.expect (checkArrayIsSimilar (output.getData(), input.getData(), n));
}
}
};
template <class TheTest>
void runTestForAllTypes (const char* unitTestName)
{
beginTest (unitTestName);
TheTest::run (*this);
}
void runTest() override
{
runTestForAllTypes<RealTest> ("Real input numbers Test");
runTestForAllTypes<FrequencyOnlyTest> ("Frequency only Test");
runTestForAllTypes<ComplexTest> ("Complex input numbers Test");
}
};
static FFTUnitTest fftUnitTest;
} // namespace juce::dsp
@@ -0,0 +1,193 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce::dsp
{
template <typename FloatType>
static FloatType ncos (size_t order, size_t i, size_t size) noexcept
{
return std::cos (static_cast<FloatType> (order * i)
* MathConstants<FloatType>::pi / static_cast<FloatType> (size - 1));
}
template <typename FloatType>
WindowingFunction<FloatType>::WindowingFunction (size_t size, WindowingMethod type, bool normalise, FloatType beta)
{
fillWindowingTables (size, type, normalise, beta);
}
template <typename FloatType>
void WindowingFunction<FloatType>::fillWindowingTables (size_t size, WindowingMethod type,
bool normalise, FloatType beta) noexcept
{
windowTable.resize (static_cast<int> (size));
fillWindowingTables (windowTable.getRawDataPointer(), size, type, normalise, beta);
}
template <typename FloatType>
void WindowingFunction<FloatType>::fillWindowingTables (FloatType* samples, size_t size,
WindowingMethod type, bool normalise,
FloatType beta) noexcept
{
switch (type)
{
case rectangular:
{
for (size_t i = 0; i < size; ++i)
samples[i] = static_cast<FloatType> (1);
}
break;
case triangular:
{
auto halfSlots = static_cast<FloatType> (0.5) * static_cast<FloatType> (size - 1);
for (size_t i = 0; i < size; ++i)
samples[i] = static_cast<FloatType> (1.0) - std::abs ((static_cast<FloatType> (i) - halfSlots) / halfSlots);
}
break;
case hann:
{
for (size_t i = 0; i < size; ++i)
{
auto cos2 = ncos<FloatType> (2, i, size);
samples[i] = static_cast<FloatType> (0.5 - 0.5 * cos2);
}
}
break;
case hamming:
{
for (size_t i = 0; i < size; ++i)
{
auto cos2 = ncos<FloatType> (2, i, size);
samples[i] = static_cast<FloatType> (0.54 - 0.46 * cos2);
}
}
break;
case blackman:
{
constexpr FloatType alpha = 0.16f;
for (size_t i = 0; i < size; ++i)
{
auto cos2 = ncos<FloatType> (2, i, size);
auto cos4 = ncos<FloatType> (4, i, size);
samples[i] = static_cast<FloatType> (0.5 * (1 - alpha) - 0.5 * cos2 + 0.5 * alpha * cos4);
}
}
break;
case blackmanHarris:
{
for (size_t i = 0; i < size; ++i)
{
auto cos2 = ncos<FloatType> (2, i, size);
auto cos4 = ncos<FloatType> (4, i, size);
auto cos6 = ncos<FloatType> (6, i, size);
samples[i] = static_cast<FloatType> (0.35875 - 0.48829 * cos2 + 0.14128 * cos4 - 0.01168 * cos6);
}
}
break;
case flatTop:
{
for (size_t i = 0; i < size; ++i)
{
auto cos2 = ncos<FloatType> (2, i, size);
auto cos4 = ncos<FloatType> (4, i, size);
auto cos6 = ncos<FloatType> (6, i, size);
auto cos8 = ncos<FloatType> (8, i, size);
samples[i] = static_cast<FloatType> (1.0 - 1.93 * cos2 + 1.29 * cos4 - 0.388 * cos6 + 0.028 * cos8);
}
}
break;
case kaiser:
{
const double factor = 1.0 / SpecialFunctions::besselI0 (beta);
const auto doubleSize = (double) size;
for (size_t i = 0; i < size; ++i)
samples[i] = static_cast<FloatType> (SpecialFunctions::besselI0 (beta * std::sqrt (1.0 - std::pow (((double) i - 0.5 * (doubleSize - 1.0))
/ ( 0.5 * (doubleSize - 1.0)), 2.0)))
* factor);
}
break;
case numWindowingMethods:
default:
jassertfalse;
break;
}
// DC frequency amplitude must be one
if (normalise)
{
FloatType sum (0);
for (size_t i = 0; i < size; ++i)
sum += samples[i];
auto factor = static_cast<FloatType> (size) / sum;
FloatVectorOperations::multiply (samples, factor, static_cast<int> (size));
}
}
template <typename FloatType>
void WindowingFunction<FloatType>::multiplyWithWindowingTable (FloatType* samples, size_t size) const noexcept
{
FloatVectorOperations::multiply (samples, windowTable.getRawDataPointer(), jmin (static_cast<int> (size), windowTable.size()));
}
template <typename FloatType>
const char* WindowingFunction<FloatType>::getWindowingMethodName (WindowingMethod type) noexcept
{
switch (type)
{
case rectangular: return "Rectangular";
case triangular: return "Triangular";
case hann: return "Hann";
case hamming: return "Hamming";
case blackman: return "Blackman";
case blackmanHarris: return "Blackman-Harris";
case flatTop: return "Flat Top";
case kaiser: return "Kaiser";
case numWindowingMethods:
default: jassertfalse; return "";
}
}
template class WindowingFunction<float>;
template class WindowingFunction<double>;
} // namespace juce::dsp
@@ -0,0 +1,108 @@
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 7 End-User License
Agreement and JUCE Privacy Policy.
End User License Agreement: www.juce.com/juce-7-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce::dsp
{
/**
A class which provides multiple windowing functions useful for filter design
and spectrum analyzers.
The different functions provided here can be used by creating either a
WindowingFunction object, or a static function to fill an array with the
windowing method samples.
@tags{DSP}
*/
template <typename FloatType>
class JUCE_API WindowingFunction
{
public:
//==============================================================================
/** The windowing methods available. */
enum WindowingMethod
{
rectangular = 0,
triangular,
hann,
hamming,
blackman,
blackmanHarris,
flatTop,
kaiser,
numWindowingMethods
};
//==============================================================================
/** This constructor automatically fills a buffer of the specified size using
the fillWindowingTables function and the specified arguments.
@see fillWindowingTables
*/
WindowingFunction (size_t size, WindowingMethod,
bool normalise = true, FloatType beta = 0);
//==============================================================================
/** Fills the content of the object array with a given windowing method table.
@param size the size of the destination buffer allocated in the object
@param type the type of windowing method being used
@param normalise if the result must be normalised, creating a DC amplitude
response of one
@param beta an optional argument useful only for Kaiser's method
which must be positive and sets the properties of the
method (bandwidth and attenuation increases with beta)
*/
void fillWindowingTables (size_t size, WindowingMethod type,
bool normalise = true, FloatType beta = 0) noexcept;
/** Fills the content of an array with a given windowing method table.
@param samples the destination buffer pointer
@param size the size of the destination buffer allocated in the object
@param normalise if the result must be normalised, creating a DC amplitude
response of one
@param beta an optional argument useful only for Kaiser's method,
which must be positive and sets the properties of the
method (bandwidth and attenuation increases with beta)
*/
static void fillWindowingTables (FloatType* samples, size_t size, WindowingMethod,
bool normalise = true, FloatType beta = 0) noexcept;
/** Multiplies the content of a buffer with the given window. */
void multiplyWithWindowingTable (FloatType* samples, size_t size) const noexcept;
/** Returns the name of a given windowing method. */
static const char* getWindowingMethodName (WindowingMethod) noexcept;
private:
//==============================================================================
Array<FloatType> windowTable;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowingFunction)
};
} // namespace juce::dsp