| name | juce-best-practices |
| description | Professional JUCE development guide covering realtime safety, threading, memory management, modern C++, and audio plugin best practices. Use when writing JUCE code, reviewing for realtime safety, implementing audio threads, managing parameters, or learning JUCE patterns and idioms. |
| allowed-tools | Read, Grep, Glob |
JUCE Best Practices
Comprehensive guide to professional JUCE framework development with modern C++ patterns, realtime safety, thread management, and audio plugin best practices.
Table of Contents
- Realtime Safety
- Thread Management
- Memory Management
- Modern C++ in JUCE
- JUCE Idioms and Conventions
- Parameter Management
- State Management
- Performance Optimization
- Common Pitfalls
Realtime Safety
The Golden Rule
NEVER allocate, deallocate, lock, or block in the audio thread (processBlock).
What to Avoid in processBlock()
โ Memory Allocation
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
std::vector<float> temp(buffer.getNumSamples());
auto dynamicArray = new float[buffer.getNumSamples()];
}
โ
Pre-allocate in prepare()
void prepareToPlay(double sampleRate, int maxBlockSize) {
tempBuffer.setSize(2, maxBlockSize);
workingMemory.resize(maxBlockSize);
}
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
tempBuffer.makeCopyOf(buffer);
}
โ Mutex Locks
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
const ScopedLock lock(parameterLock);
auto value = sharedParameter;
}
โ
Use Atomics or Lock-Free Structures
std::atomic<float> cutoffFrequency{1000.0f};
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
auto freq = cutoffFrequency.load();
filter.setCutoff(freq);
}
โ System Calls and I/O
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
DBG("Processing " << buffer.getNumSamples());
saveAudioToFile(buffer);
}
Realtime Safety Checklist
Thread Management
The Two Worlds
JUCE audio plugins operate in two separate thread contexts:
- Message Thread - UI, user interactions, file I/O, networking
- Audio Thread - processBlock(), realtime audio processing
Thread Communication
โ
Message Thread โ Audio Thread
std::atomic<float> gain{1.0f};
void sliderValueChanged(Slider* slider) {
gain.store(slider->getValue());
}
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
auto currentGain = gain.load();
buffer.applyGain(currentGain);
}
โ
Audio Thread โ Message Thread
class MyProcessor : public AudioProcessor,
private AsyncUpdater {
private:
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) override {
if (needsUIUpdate) {
triggerAsyncUpdate();
}
}
void handleAsyncUpdate() override {
editor->updateDisplay();
}
};
โ
Complex Data with Lock-Free Queue
juce::AbstractFifo fifo;
std::vector<float> ringBuffer;
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
int start1, size1, start2, size2;
fifo.prepareToWrite(buffer.getNumSamples(), start1, size1, start2, size2);
fifo.finishedWrite(size1 + size2);
}
void timerCallback() {
int start1, size1, start2, size2;
fifo.prepareToRead(fifo.getNumReady(), start1, size1, start2, size2);
fifo.finishedRead(size1 + size2);
}
Thread Safety Rules
| Action | Message Thread | Audio Thread |
|---|
| Allocate memory | โ
OK | โ Never |
| File I/O | โ
OK | โ Never |
| Lock mutex | โ
OK | โ Never |
| Update UI | โ
OK | โ Never |
| Process audio | โ Never | โ
OK |
| Use atomics | โ
OK | โ
OK |
Memory Management
RAII and Smart Pointers
โ
Use RAII for Resource Management
class MyProcessor : public AudioProcessor {
private:
std::unique_ptr<Reverb> reverb;
std::vector<float> delayBuffer;
void prepareToPlay(double sr, int maxBlockSize) override {
reverb = std::make_unique<Reverb>();
delayBuffer.resize(sr * 2.0);
}
};
Prefer Stack Allocation in processBlock()
โ
Stack Allocation is Realtime-Safe
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
float tempGain = 0.5f;
int sampleCount = buffer.getNumSamples();
}
Pre-allocate Buffers
โ
Allocate Once, Reuse Many Times
class MyProcessor : public AudioProcessor {
private:
AudioBuffer<float> tempBuffer;
std::vector<float> fftData;
void prepareToPlay(double sr, int maxBlockSize) override {
tempBuffer.setSize(2, maxBlockSize);
fftData.resize(2048);
}
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) override {
tempBuffer.makeCopyOf(buffer);
}
};
Modern C++ in JUCE
Use C++17/20 Features Appropriately
โ
Structured Bindings (C++17)
auto [min, max] = buffer.findMinMax(0, buffer.getNumSamples());
โ
if constexpr (C++17)
template<typename SampleType>
void process(AudioBuffer<SampleType>& buffer) {
if constexpr (std::is_same_v<SampleType, float>) {
} else {
}
}
โ
std::optional (C++17)
std::optional<float> tryGetParameter(const String& id) {
if (auto* param = parameters.getParameter(id))
return param->getValue();
return std::nullopt;
}
Const Correctness
โ
Mark Non-Mutating Methods const
class Filter {
public:
float getCutoff() const { return cutoff; }
float getResonance() const { return resonance; }
void setCutoff(float f) { cutoff = f; }
private:
float cutoff = 1000.0f;
float resonance = 0.707f;
};
Range-Based For Loops
โ
Cleaner Iteration
for (int ch = 0; ch < buffer.getNumChannels(); ++ch) {
auto* channelData = buffer.getWritePointer(ch);
for (int i = 0; i < buffer.getNumSamples(); ++i) {
channelData[i] *= gain;
}
}
for (int ch = 0; ch < buffer.getNumChannels(); ++ch) {
auto* data = buffer.getWritePointer(ch);
for (int i = 0; i < buffer.getNumSamples(); ++i) {
data[i] *= gain;
}
}
buffer.applyGain(gain);
JUCE Idioms and Conventions
Audio Buffer Operations
โ
Use JUCE's Buffer Methods
buffer.applyGain(0.5f);
buffer.clear();
AudioBuffer<float> copy;
copy.makeCopyOf(buffer);
outputBuffer.addFrom(0, 0, inputBuffer, 0, 0, numSamples);
Value Tree for State
โ
Use ValueTree for Hierarchical State
ValueTree state("PluginState");
state.setProperty("version", "1.0.0", nullptr);
ValueTree parameters("Parameters");
parameters.setProperty("gain", 0.5f, nullptr);
parameters.setProperty("frequency", 1000.0f, nullptr);
state.appendChild(parameters, nullptr);
auto xml = state.toXmlString();
auto loadedState = ValueTree::fromXml(xml);
AudioProcessorValueTreeState for Parameters
โ
Standard Parameter Management
class MyProcessor : public AudioProcessor {
public:
MyProcessor()
: parameters(*this, nullptr, "Parameters", createParameterLayout())
{
}
private:
AudioProcessorValueTreeState parameters;
static AudioProcessorValueTreeState::ParameterLayout createParameterLayout() {
std::vector<std::unique_ptr<RangedAudioParameter>> params;
params.push_back(std::make_unique<AudioParameterFloat>(
"gain",
"Gain",
NormalisableRange<float>(0.0f, 1.0f),
0.5f
));
return { params.begin(), params.end() };
}
};
Parameter Management
Parameter Smoothing
โ
Smooth Parameter Changes to Avoid Zipper Noise
class MyProcessor : public AudioProcessor {
private:
SmoothedValue<float> gainSmooth;
void prepareToPlay(double sr, int maxBlockSize) override {
gainSmooth.reset(sr, 0.05);
}
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) override {
auto* gainParam = parameters.getRawParameterValue("gain");
gainSmooth.setTargetValue(*gainParam);
for (int i = 0; i < buffer.getNumSamples(); ++i) {
auto gain = gainSmooth.getNextValue();
for (int ch = 0; ch < buffer.getNumChannels(); ++ch) {
buffer.setSample(ch, i, buffer.getSample(ch, i) * gain);
}
}
}
};
Parameter Change Notifications
โ
Efficient Parameter Updates
void parameterChanged(const String& parameterID, float newValue) override {
if (parameterID == "cutoff") {
cutoffFrequency.store(newValue);
}
}
State Management
Save and Restore State
โ
Implement getStateInformation/setStateInformation
void getStateInformation(MemoryBlock& destData) override {
auto state = parameters.copyState();
std::unique_ptr<XmlElement> xml(state.createXml());
copyXmlToBinary(*xml, destData);
}
void setStateInformation(const void* data, int sizeInBytes) override {
std::unique_ptr<XmlElement> xml(getXmlFromBinary(data, sizeInBytes));
if (xml && xml->hasTagName(parameters.state.getType())) {
parameters.replaceState(ValueTree::fromXml(*xml));
}
}
Version Your State
โ
Handle Backward Compatibility
void setStateInformation(const void* data, int sizeInBytes) override {
auto xml = getXmlFromBinary(data, sizeInBytes);
int version = xml->getIntAttribute("version", 1);
if (version == 1) {
migrateFromV1(xml);
} else if (version == 2) {
parameters.replaceState(ValueTree::fromXml(*xml));
}
}
Performance Optimization
Avoid Unnecessary Calculations
โ
Calculate Once, Use Many Times
for (int i = 0; i < buffer.getNumSamples(); ++i) {
auto coeff = std::exp(-1.0f / (sampleRate * timeConstant));
}
auto coeff = std::exp(-1.0f / (sampleRate * timeConstant));
for (int i = 0; i < buffer.getNumSamples(); ++i) {
}
Use SIMD When Appropriate
โ
JUCE's dsp::SIMDRegister
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
auto* data = buffer.getWritePointer(0);
auto gain = dsp::SIMDRegister<float>(0.5f);
for (int i = 0; i < buffer.getNumSamples(); i += gain.size()) {
auto samples = dsp::SIMDRegister<float>::fromRawArray(data + i);
samples *= gain;
samples.copyToRawArray(data + i);
}
}
Denormal Prevention
โ
Prevent Denormals for CPU Performance
void prepareToPlay(double sr, int maxBlockSize) override {
juce::FloatVectorOperations::disableDenormalisedNumberSupport();
}
float processSample(float input) {
static constexpr float denormalPrevention = 1.0e-20f;
feedbackState = input + feedbackState * 0.99f + denormalPrevention;
return feedbackState;
}
Common Pitfalls
โ Pitfall 1: Calling repaint() from Audio Thread
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
if (editor)
editor->repaint();
}
โ
Solution: Use AsyncUpdater
void processBlock(AudioBuffer<float>& buffer, MidiBuffer&) {
triggerAsyncUpdate();
}
void handleAsyncUpdate() override {
if (editor)
editor->repaint();
}
โ Pitfall 2: Not Handling Sample Rate Changes
float delayTimeInSamples = 0.5f * 44100.0f;
โ
Solution: Update in prepareToPlay
void prepareToPlay(double sampleRate, int maxBlockSize) override {
delayTimeInSamples = 0.5f * sampleRate;
}
โ Pitfall 3: Forgetting to Call Base Class Methods
void prepareToPlay(double sr, int maxBlockSize) override {
mySetup(sr, maxBlockSize);
}
โ
Solution: Always Call Base
void prepareToPlay(double sr, int maxBlockSize) override {
AudioProcessor::prepareToPlay(sr, maxBlockSize);
mySetup(sr, maxBlockSize);
}
Quick Reference
Do's โ
- Use
AudioProcessorValueTreeState for parameters
- Pre-allocate buffers in
prepareToPlay()
- Use atomics for simple thread communication
- Smooth parameter changes to avoid zipper noise
- Version your plugin state
- Handle all sample rates correctly
- Use RAII and smart pointers
- Mark const methods const
- Use JUCE's helper functions
Don'ts โ
- Allocate/deallocate in
processBlock()
- Lock mutexes in audio thread
- Call UI methods from audio thread
- Use
DBG() or logging in processBlock()
- Assume fixed sample rate or buffer size
- Forget to handle state save/load
- Use raw pointers for ownership
- Ignore const correctness
- Reinvent JUCE functionality
Further Reading
Remember: Audio plugins must be realtime-safe, thread-aware, and robust. Follow these best practices to create professional, stable plugins that work reliably across all DAWs and platforms.