According to this ITU guide (page 16 onwards)
https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.1770-4-201510-I!!PDF-E.pdf
measuring true peak would need the following steps:
- attenuate the signal by 12.04dB if integer arithmetic is used (not needed with floats in JUCE)
- oversampling up to 4x to reach 192kHz (or 176.4kHz @ 44.1 sample rate)
- filtering the oversampled signal with a FIR (see coeffs in the guide)
- reading the absolute value of the result
- convert into dB
- raise the gain by 12.04dB (see above)
I’ve built a minimal example plug-in with juce::dsp::Oversampling and using the included stock FIR filtering.
The result seems to be correct comparing with other commercial plugins.
Is that really all I need to do? That would be too good to be true.
Off topic: in dsp::Oversampling class, you have to define the num of channels during construction, so I’m using a std::unique_ptr instead of a stack variable and instantiate it in prepareToPlay
. Is there any issues or performance penalty doing it that way?
Here is my code (any optimisation advice are welcome )
Thanks
Stefan
PluginEditor.h:
#pragma once
#include <JuceHeader.h>
#include "PluginProcessor.h"
//==============================================================================
/**
*/
class TruePeakMeteringAudioProcessorEditor : public juce::AudioProcessorEditor, public Timer
{
public :
TruePeakMeteringAudioProcessorEditor (TruePeakMeteringAudioProcessor&);
~TruePeakMeteringAudioProcessorEditor() override;
//==============================================================================
void paint (juce::Graphics&) override;
**void** resized() **override** ;
**void** timerCallback() **override**;
**private** :
// This reference is provided as a quick way for your editor to
// access the processor object that created it.
TruePeakMeteringAudioProcessor& audioProcessor;
Label headline;
Label truePeakLabel;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TruePeakMeteringAudioProcessorEditor)
};
PluginEditor.cpp:
/*
==============================================================================
This file contains the basic framework code for a JUCE plugin editor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
//==============================================================================
TruePeakMeteringAudioProcessorEditor::TruePeakMeteringAudioProcessorEditor (TruePeakMeteringAudioProcessor& p)
: AudioProcessorEditor (&p), audioProcessor (p)
{
addAndMakeVisible(headline);
headline.setText("Max True Peak", dontSendNotification);
headline.setFont(Font(30));
headline.setJustificationType(Justification::centred);
addAndMakeVisible(truePeakLabel);
truePeakLabel.setFont(Font(60));
truePeakLabel.setJustificationType(Justification::centred);
truePeakLabel.setText("---", dontSendNotification);
startTimerHz(30);
setSize (400, 300);
}
TruePeakMeteringAudioProcessorEditor::~TruePeakMeteringAudioProcessorEditor()
{
}
//==============================================================================
void TruePeakMeteringAudioProcessorEditor::paint (juce::Graphics& g)
{
// (Our component is opaque, so we must completely fill the background with a solid colour)
g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId));
}
void TruePeakMeteringAudioProcessorEditor::resized()
{
auto area = getLocalBounds().removeFromBottom(250);
auto headlineArea = area.removeFromTop(50);
headline.setBounds(headlineArea);
truePeakLabel.setBounds(area);
}
void TruePeakMeteringAudioProcessorEditor::timerCallback() {
float dbValue = Decibels::gainToDecibels(audioProcessor.getMaxTruePeak());
auto str = String(dbValue, 1) + "\n(" + String(dbValue) + ")";
truePeakLabel.setText(str, dontSendNotification);
}
PluginProcessor.h:
/*
==============================================================================
This file contains the basic framework code for a JUCE plugin processor.
==============================================================================
*/
#pragma once
#include <JuceHeader.h>
//==============================================================================
/**
*/
**class** TruePeakMeteringAudioProcessor : **public** juce::AudioProcessor
#if JucePlugin_Enable_ARA
, **public** juce::AudioProcessorARAExtension
#endif
{
**public** :
//==============================================================================
TruePeakMeteringAudioProcessor();
~TruePeakMeteringAudioProcessor() **override**;
//==============================================================================
**void** prepareToPlay (**double** sampleRate, **int** samplesPerBlock) **override**;
**void** releaseResources() **override**;
#ifndef JucePlugin_PreferredChannelConfigurations
**bool** isBusesLayoutSupported (**const** BusesLayout& layouts) **const** **override**;
#endif
**void** processBlock (juce::AudioBuffer<**float**>&, juce::MidiBuffer&) **override**;
//==============================================================================
juce::AudioProcessorEditor* createEditor() **override**;
**bool** hasEditor() **const** **override** ;
//==============================================================================
**const** juce::String getName() **const** **override** ;
**bool** acceptsMidi() **const** **override** ;
**bool** producesMidi() **const** **override** ;
**bool** isMidiEffect() **const** **override** ;
**double** getTailLengthSeconds() **const** **override**;
//==============================================================================
**int** getNumPrograms() **override**;
**int** getCurrentProgram() **override**;
**void** setCurrentProgram (**int** index) **override**;
**const** juce::String getProgramName (**int** index) **override**;
**void** changeProgramName (**int** index, **const** juce::String& newName) **override**;
//==============================================================================
**void** getStateInformation (juce::MemoryBlock& destData) **override**;
**void** setStateInformation (**const** **void*** data, **int** sizeInBytes) **override**;
**float** getMaxTruePeak();
**private** :
std::unique_ptr<dsp::Oversampling<float>> oversamplingProcessor;
Atomic<**float**> maxTruePeak;
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TruePeakMeteringAudioProcessor)
};
PluginProcessor.cpp:
#include "PluginProcessor.h"
#include "PluginEditor.h"
//==============================================================================
TruePeakMeteringAudioProcessor::TruePeakMeteringAudioProcessor()
#ifndef JucePlugin_PreferredChannelConfigurations
: AudioProcessor (BusesProperties()
#if ! JucePlugin_IsMidiEffect
#if ! JucePlugin_IsSynth
.withInput ("Input", juce::AudioChannelSet::stereo(), true)
#endif
.withOutput ("Output", juce::AudioChannelSet::stereo(), true)
#endif
)
#endif
{
}
TruePeakMeteringAudioProcessor::~TruePeakMeteringAudioProcessor()
{
}
// ...
//==============================================================================
void TruePeakMeteringAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock)
{
int numInputChannels = getTotalNumInputChannels();
/// TRUE PEAK (OVERSAMPLING)
//============================================================================================
/// see https://www.itu.int/dms_pubrec/itu-r/rec/bs/R-REC-BS.1770-4-201510-I!!PDF-E.pdf ; page 16
/// 192kHz -> no oversampling; 96/88.2kHz -> 2x oversampling; 48/44.1kHz -> 4x oversampling
int oversamplingFactor = 1 / (sampleRate / 192000);
if (oversamplingFactor > 1) {
int order = std::log2(oversamplingFactor);
oversamplingProcessor.reset(new dsp::Oversampling<float>(numInputChannels, order, dsp::Oversampling<float>::FilterType::filterHalfBandFIREquiripple));
oversamplingProcessor->initProcessing(samplesPerBlock);
oversamplingProcessor->reset();
}
else oversamplingProcessor.reset();
}
void TruePeakMeteringAudioProcessor::processBlock (juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midiMessages)
{
juce::ScopedNoDenormals noDenormals;
auto totalNumInputChannels = getTotalNumInputChannels();
auto totalNumOutputChannels = getTotalNumOutputChannels();
auto audioBlock = dsp::AudioBlock<float>(buffer);
// auto osBlock = dsp::AudioBlock<float>(buffer);
/// TRUE PEAK (OVERSAMPLING)
//============================================================================================
auto truePeak = 0.0f;
auto readTruePeak = [&truePeak] (dsp::AudioBlock<float>& block) {
for (int i = 0; i < block.getNumChannels(); i++)
for (int j = 0; j < block.getNumSamples(); j++)
truePeak = jmax(truePeak, std::abs(block.getSample(i, j)));
};
if (oversamplingProcessor != nullptr) {
auto osBlock = oversamplingProcessor->processSamplesUp(audioBlock);
readTruePeak(osBlock);
}
/// sampleRate already 192kHz
else readTruePeak(audioBlock);
maxTruePeak = jmax(truePeak, maxTruePeak.get());
// In case we have more outputs than inputs, this code clears any output
// channels that didn't contain input data, (because these aren't
// guaranteed to be empty - they may contain garbage).
// This is here to avoid people getting screaming feedback
// when they first compile a plugin, but obviously you don't need to keep
// this code if your algorithm always overwrites all the output channels.
for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
buffer.clear (i, 0, buffer.getNumSamples());
}
// ...
float TruePeakMeteringAudioProcessor::getMaxTruePeak() {
return maxTruePeak.get();
}