Mercurial > hg > apm2s
diff AccessiblePeakMeter.cpp @ 0:4606bd505630 tip
first import
author | Fiore Martin <f.martin@qmul.ac.uk> |
---|---|
date | Sat, 13 Jun 2015 15:08:10 +0100 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/AccessiblePeakMeter.cpp Sat Jun 13 15:08:10 2015 +0100 @@ -0,0 +1,494 @@ +// +// AccessiblePeakMeter.cpp +// +// Author: Fiore Martin +// Started from IPlugMultiTargets example in WDL-OL, by Oli Larkin - https://github.com/olilarkin/wdl-ol +// +// Licensed under the Cockos WDL License, see README.txt +// + +#include "AccessiblePeakMeter.h" +#include "IPlug_include_in_plug_src.h" +#include "resource.h" + + +#include "IControl.h" +#include "IBitmapMonoText.h" +#include "AccessiblePeakMeter_controls.h" + +#include <memory> + +inline double midi2Freq(int note) { + return 440. * pow(2., (note - 69.) / 12.); +} + +double toDBMeter(double val, double range) +{ + double db; + if (val > 0) + db = ::AmpToDB(val); + else + db = -999; + return BOUNDED((db + 60) / range,0,1); +} + +/* reference points for controls layout, by changing these numbers only +the widgets can be moved around and all the other bits (top/left/right +borders, labels etc.) will follow. X and Y refer to the top-left coord */ +enum ELayout { + lDryX = 20, + lDryY = 10, + lWetX = 85, + lWetY = 10, + + lFaderLen = 190, + lPeakMeterX = 180, + lPeaklMeterY = 30, + + lSonifTypeX = 20, + lSonifTypeY = 200, + + lDecayRateX = 20, + lDecayRateY = 90 +}; + +enum EParams +{ + kDry = 0, + kWet, + kThreshold, + kSonificationType, + kMeterDecayRate, + kNumParams +}; + +AccessiblePeakMeter::AccessiblePeakMeter(IPlugInstanceInfo instanceInfo) + : IPLUG_CTOR(kNumParams, NUM_PRESETS, instanceInfo), + mDry(DRY_DEFAULT), + mWet(WET_DEFAULT), + mMeterDecayRate(1.0), + mThreshold(1.0), + mSampleRate(44100.), + mSonificationType(SONIFICATION_TYPE_CLIPPING) + +{ + TRACE; + + //arguments are: name, defaultVal, minVal, maxVal, step, label + GetParam(kDry)->InitDouble("Dry", DRY_DEFAULT, -61.0, 0., 0.2, "dB"); + GetParam(kDry)->SetDisplayText(-61.0, " -inf"); + GetParam(kWet)->InitDouble("Wet", WET_DEFAULT, -61.0, 0., 0.2, "dB"); + GetParam(kWet)->SetDisplayText(-61.0, " -inf"); + GetParam(kThreshold)->InitDouble("Threshold", 0.0, -60.0, 6.2, 0.2, "dB"); + GetParam(kSonificationType)->InitEnum("Sonification Type", SONIFICATION_TYPE_DEFAULT, 2); + GetParam(kSonificationType)->SetDisplayText(SONIFICATION_TYPE_CLIPPING, "Clipping"); + GetParam(kSonificationType)->SetDisplayText(SONIFICATION_TYPE_CONTINUOUS, "Continuous"); + + GetParam(kMeterDecayRate)->InitDouble("Decay", 1.0, 0.05, 1.0, 0.05, "sec."); + + IGraphics* pGraphics = MakeGraphics(this, GUI_WIDTH, GUI_HEIGHT); + pGraphics->AttachBackground(BG_ID, BG_FN); + + /* load bitmaps for fader, knob and switch button */ + IBitmap knob = pGraphics->LoadIBitmap(KNOB_ID, KNOB_FN, NUM_KNOB_FRAMES); + IBitmap faderBmap = pGraphics->LoadIBitmap(FADER_ID, FADER_FN); + IBitmap aSwitch = pGraphics->LoadIBitmap(SWITCH_ID, SWITCH_FN,2); + + //pGraphics->AttachKeyCatcher(new IKeyCatcher(this, IRECT(0, 0, GUI_WIDTH, GUI_HEIGHT))); + + /* text has info about the font-size, font-type etc. */ + IText text = IText(14); + /* attach sonification type switch to the GUI */ + pGraphics->AttachControl(new ISwitchPopUpControl(this, lSonifTypeX ,lSonifTypeY, kSonificationType, &aSwitch)); + pGraphics->AttachControl(new ITextControl(this, IRECT(lSonifTypeX+10, lSonifTypeY - 20, lSonifTypeX + 110, lSonifTypeY ), &text, "Sonification Type")); + + /* attach dry and wet knobs to GUI */ + pGraphics->AttachControl(new IKnobMultiControlText(this, IRECT(lDryX, lDryY, lDryX + 52, lDryY + 48 + 20 + 20), kDry, &knob, &text, 27)); + pGraphics->AttachControl(new IKnobMultiControlText(this, IRECT(lWetX, lWetY, lWetX + 52, lWetY + 48 + 20 + 20), kWet, &knob, &text, 27)); + + /* attach decay rate knob to the GUI */ + pGraphics->AttachControl(new IKnobMultiControlText(this, IRECT(lDecayRateX, lDecayRateY, lDecayRateX + 48, lDecayRateY + 48 + 20 + 20), kMeterDecayRate, &knob, &text, 33)); + + /* attach fader display, which shows the fader value, to GUI */ + ITextControl *faderText = new ITextControl(this, IRECT(lPeakMeterX+60, lPeaklMeterY + lFaderLen, lPeakMeterX + faderBmap.W + 95, lPeaklMeterY + lFaderLen + 20), &text); + pGraphics->AttachControl(faderText); + + /* attach the fader to GUI */ + pGraphics->AttachControl(new IFaderVertText(this, lPeakMeterX, lPeaklMeterY, lFaderLen, kThreshold, &faderBmap, faderText)); + + pGraphics->AttachControl(new ITextControl(this, IRECT(lPeakMeterX, lPeaklMeterY - 20, lPeakMeterX + 100, lPeaklMeterY), &text, "Peak Level Meter")); + pGraphics->AttachControl(new ITextControl(this, IRECT(lPeakMeterX-20, lPeaklMeterY + lFaderLen, lPeakMeterX + 75, lPeaklMeterY + lFaderLen + 20), &text, "Threshold: ")); + + /* attach peak meters to GUI */ + /* half the bitmap height is added to the peak meters on both top and bottom to prevent the fader + - a triangle pointing at half the height of the bitmap - from overflowing the peak meters */ + int halfFaderBmapLen = faderBmap.W / 2; + mMeterIdx[0] = pGraphics->AttachControl(new IPeakMeterVert(this, IRECT(lPeakMeterX + 25, lPeaklMeterY + halfFaderBmapLen, lPeakMeterX + 45, lPeaklMeterY + 170 + halfFaderBmapLen), + GetParam(kThreshold)->GetDefaultNormalized())); + mMeterIdx[1] = pGraphics->AttachControl(new IPeakMeterVert(this, + IRECT(lPeakMeterX + 50, lPeaklMeterY + halfFaderBmapLen, lPeakMeterX + 70, lPeaklMeterY + lFaderLen - halfFaderBmapLen), GetParam(kThreshold)->GetDefaultNormalized())); + + AttachGraphics(pGraphics); + + //kDry, kWet, kThreshold, kSonificationType, kMeterDecayRate, + MakePreset("Detect Clipping", DRY_DEFAULT, WET_DEFAULT, THRESHOLD_DEFAULT, SONIFICATION_TYPE_CLIPPING, METERDECAY_DEFAULT); + MakePreset("Sonify Audio", DRY_DEFAULT, WET_DEFAULT, THRESHOLD_DEFAULT, SONIFICATION_TYPE_CONTINUOUS, METERDECAY_DEFAULT); + +} + +AccessiblePeakMeter::~AccessiblePeakMeter() { } + + +void AccessiblePeakMeter::ProcessDoubleReplacing(double** inputs, double** outputs, int nFrames) +{ + if(mSonificationType == SONIFICATION_TYPE_CONTINUOUS) { + addContinuousSonification(inputs, outputs, nFrames); + } else { + addClippingSonification(inputs, outputs, nFrames); + } +} + + +void AccessiblePeakMeter::Reset() +{ + TRACE; + IMutexLock lock(this); + + mSampleRate = GetSampleRate(); + + for (int i = 0; i < MAX_CHANNELS; i++) { + mPrevPeak[i] = 0.0; + } + + if (!sDacThread.started){ + sDacThread.started = true; + sDacThread.t = std::move(std::thread(DacRoutine)); + } +} + +void AccessiblePeakMeter::OnParamChange(int paramIdx) +{ + IMutexLock lock(this); + + switch (paramIdx) + { + case kDry : + if (GetParam(kDry)->Value() < -60.5){ + mDry = 0.0; + } + else { + mDry = ::DBToAmp(GetParam(kDry)->Value()); + } + break; + + case kWet: + if (GetParam(kWet)->Value() < -60.5){ + mWet = 0.0; + } + else{ + mWet = ::DBToAmp(GetParam(kWet)->Value()); + } + break; + + case kThreshold: + mThreshold = GetParam(kThreshold)->DBToAmp(); + break; + + case kMeterDecayRate : + mMeterDecayRate = 1.0 / GetParam(kMeterDecayRate)->Value(); + break; + + case kSonificationType: + mSonificationType = GetParam(kSonificationType)->Int(); + + for (int i = 0; i < MAX_CHANNELS; i++) { + mPrevPeak[i] = 0.0; + } + + sDacMutex.lock(); + sDacSynced.sonificationType = mSonificationType; + sDacMutex.unlock(); + + break; + + default: + break; + } +} + +void AccessiblePeakMeter::addClippingSonification(double** inputs, double** outputs, int nFrames) { + // Mutex is already locked for us. + + double clippingDiff[MAX_CHANNELS] = { 0.0, 0.0 }; + + for (unsigned int channel = 0; channel < NInChannels(); channel++) { + double* in = inputs[channel]; + double* out = outputs[channel]; + double peak = 0.0; + + /* find the max absolute value in the block of samples */ + for (int offset = 0; offset < nFrames; ++offset, ++in, ++out) { + /* find the peak of this block */ + peak = IPMAX(peak, fabs(*in)); + /* write the input buffer to the output */ + *out = mDry * (*in); + } + + if (peak > mThreshold) { + double difftoThrs = fabs(::AmpToDB(peak) - ::AmpToDB(mThreshold)); + /* clipDiff will be rounded downward later, but if it's very very + close to the ceil, then let it be the ceil. + */ + const double ceilClippingDiff = ceil(difftoThrs); + if (ceilClippingDiff - difftoThrs < CLIPPING_CEILING_SNAP){ + difftoThrs = ceilClippingDiff; + } + + clippingDiff[channel] = BOUNDED(difftoThrs, 0.0, 12.0); + } + + /* now draw the peak meter with the maximum of this block of samples */ + const double deltaT = nFrames / mSampleRate; + const double decayAmount = deltaT * mMeterDecayRate; + + peak = ::toDBMeter(peak, DB_RANGE); + + /* max between new peak and old peak decay wins */ + peak = IPMAX(peak, mPrevPeak[channel] - decayAmount); + + /* save the peaks for next block of samples */ + mPrevPeak[channel] = peak; + + + /* update the GUI */ + if (GetGUI()){ + GetGUI()->SetControlFromPlug(mMeterIdx[channel], peak); + } + } + + /* pass the data related to this block over to the sonification thread */ + sDacMutex.lock(); + sDacSynced.wet = mWet; + sDacSynced.maxClippingDiff[0] = clippingDiff[0]; + sDacSynced.maxClippingDiff[1] = clippingDiff[1]; + sDacMutex.unlock(); + +} + +void AccessiblePeakMeter::addContinuousSonification(double** inputs, double** outputs, int nFrames) { + // Mutex is already locked for us. + + const int nChannels = NInChannels(); + + const double deltaT = nFrames / mSampleRate; + const double decayAmount = deltaT * mMeterDecayRate; + double sonifyFreq[MAX_CHANNELS] = {0.0, 0.0}; + + for (int channel = 0; channel < nChannels; channel++){ + + double peak = 0.0; + double *in = inputs[channel]; + double *out = outputs[channel]; + + /* find the max absolute value in the block of samples and write output */ + for (int offset = 0; offset < nFrames; ++offset, ++in, ++out) { + /* find the peak of this block */ + peak = IPMAX(peak, fabs(*in)); + /* write the input buffer to the output */ + *out = mDry * (*in); + } + + /* pick the max between new audio and peak meter decaying */ + peak = ::toDBMeter(peak, DB_RANGE); + peak = IPMAX(peak, mPrevPeak[channel] - decayAmount); + + /* set the sonification frequency according to the last peak value */ + sonifyFreq[channel] = SONIFICATION_RANGE * peak; + + /* save the peaks for next block of samples */ + mPrevPeak[channel] = peak; + + /* update the GUI */ + if (GetGUI()){ + GetGUI()->SetControlFromPlug(mMeterIdx[channel], peak); + } + + } + + /* pass the data related to this block over to the sonification thread */ + sDacMutex.lock(); + sDacSynced.sonifFreq[0] = sonifyFreq[0]; + sDacSynced.sonifFreq[1] = sonifyFreq[1]; + sDacSynced.wet = mWet; + sDacMutex.unlock(); +} + +/* Global scope function executed by the thread that plays the sonification to the dac */ +void DacRoutine(){ + + /* the sound card handle */ + std::unique_ptr<stk::RtWvOut> sDac; + + try { + // Define and open the default realtime output device for two-channels playback + sDac.reset(new stk::RtWvOut(MAX_CHANNELS, stk::Stk::sampleRate(), 0, DAC_BUFFER_SIZE)); + } + catch (stk::StkError &) { + exit(1); + } + + /* buffer to calculate the blocks of DAC_BUFFER_SIZE samples. + The content of the buffer is then fed to the sound card + */ + stk::StkFrames frames(DAC_BUFFER_SIZE, MAX_CHANNELS); + + while (true){ + + /* init local variables to be filled with shared variables' content */ + double freqs[MAX_CHANNELS] = { 0.0, 0.0 }; + double clippingDiffs[MAX_CHANNELS] = { 0.0, 0.0 }; + double wet = 0.0; + bool die = false; + int sonificationType; + + /* read the shared variables all together into local variables */ + sDacMutex.lock(); + + sonificationType = sDacSynced.sonificationType; + + for (int i = 0; i < MAX_CHANNELS; i++){ + freqs[i] = sDacSynced.sonifFreq[i]; + clippingDiffs[i] = sDacSynced.maxClippingDiff[i]; + } + + wet = sDacSynced.wet; + + die = sDacSynced.die; + + sDacMutex.unlock(); + + /* check if the thread has to stop. Called when the user exits the Daw */ + if (die){ + return; + } + + /* reset the ugen if sonification type has changed */ + if (sonificationType != sPrevSonificationType) { + + for (int i = 0; i < MAX_CHANNELS; i++){ + sSonification.ugen[i].reset(); + sSonification.ugen[i].setFrequency(sonificationType == SONIFICATION_TYPE_CLIPPING ? 440 : 0); + } + + sPrevSonificationType = sonificationType; + } + + if (sonificationType == SONIFICATION_TYPE_CONTINUOUS) { + /* write the next block of samples to send to the soundcard */ + for (int nFrame = 0; nFrame < DAC_BUFFER_SIZE; nFrame++){ + for (int channel = 0; channel < MAX_CHANNELS; channel++){ + + sSonification.ugen[channel].setFrequency(freqs[channel]); + /* If level goes below audible level just hush the sonification. * + * this avoids DC offset when sonification frequency gets too low. * + * Use an envelope to bring the sonification volume down gently */ + if (freqs[channel] < AccessiblePeakMeter::MIN_SONIFICATION_FREQ){ + + if (sSonification.continous.isOn[channel]){ // if it's on and level's low, turn it off + sSonification.continous.isOn[channel] = false; + sSonification.continous.envelope[channel].setTarget(0.0); + } + + } + else if (!sSonification.continous.isOn[channel]){ // if it's off and level's high, turn it on + + sSonification.continous.envelope[channel].setValue(1.0); + sSonification.continous.isOn[channel] = true; + + } + + double tick = sSonification.ugen[channel].tick(); + tick *= sSonification.continous.envelope[channel].tick(); // apply envelope + tick *= wet; // apply wet parameter, controlled by the user + frames(nFrame, channel) = tick; + } + } + } + else { // sonificationType = AccessiblePeakMeter::SONIFICATION_TYPE_CLIPPING + + for (int channel = 0; channel < MAX_CHANNELS; channel++){ + + if (clippingDiffs[channel] > 0.0){ + if (clippingDiffs[channel] > sSonification.clipping.maxDiff[channel]){ + sSonification.clipping.maxDiff[channel] = clippingDiffs[channel]; + } + + /* sonify the difference between the amplitude and threshold * + * one db (rounded downward) is one tone, up to one octave */ + sSonification.ugen[channel].setFrequency(midi2Freq(69 + (int)(sSonification.clipping.maxDiff[channel]))); + sSonification.clipping.envelope[channel].keyOn(); + } + + } + + for (int nFrame = 0; nFrame < DAC_BUFFER_SIZE; nFrame++){ + for (int channel = 0; channel < MAX_CHANNELS; channel++){ + + /* when attack is done switch immediately to RELEASE (keyOff) * + * this way the evelope goes like attack->release->silence */ + if (sSonification.clipping.envelope[channel].getState() == stk::ADSR::DECAY) { + sSonification.clipping.envelope[channel].keyOff(); + } + + /* write the sonification in the frames object */ + if (sSonification.clipping.envelope[channel].getState() == stk::ADSR::ATTACK || + sSonification.clipping.envelope[channel].getState() == stk::ADSR::RELEASE) { + + const double env = sSonification.clipping.envelope[channel].tick(); + double tick = sSonification.ugen[channel].tick() * env; + tick *= wet; + frames(nFrame, channel) = tick; + + } + else { // no sonification + + sSonification.clipping.maxDiff[channel] = 0.0; // reset max clipping diff + frames(nFrame, channel) = 0.0; + + } + } + } + + } + + /* play this block to the default soundcard */ + sDac->tick(frames); + } + +} + +//Called by the standalone wrapper if someone clicks about +bool AccessiblePeakMeter::HostRequestingAboutBox() +{ + IMutexLock lock(this); + if(GetGUI()) + { + // do nothing + } + return true; +} + + + +const double AccessiblePeakMeter::DRY_DEFAULT = 0.0; +const double AccessiblePeakMeter::WET_DEFAULT = -6.0; +const int AccessiblePeakMeter::SONIFICATION_TYPE_DEFAULT = 1; +const double AccessiblePeakMeter::METERDECAY_DEFAULT = 60.0; +const double AccessiblePeakMeter::THRESHOLD_DEFAULT = 0.0; + +const double AccessiblePeakMeter::DB_RANGE = 66.0; +const double AccessiblePeakMeter::SONIFICATION_RANGE = 2000; +const double AccessiblePeakMeter::MIN_SONIFICATION_FREQ = 20.0; +const double AccessiblePeakMeter::CLIPPING_CEILING_SNAP = 0.05; +const int AccessiblePeakMeter::NUM_KNOB_FRAMES = 60; +