21#include "IPlugStructs.h"
24BEGIN_IGRAPHICS_NAMESPACE
30template <
int MAXNC = 2,
int MAX_FFT_SIZE = 4096>
37 kMsgTagSampleRate = 1,
44 static constexpr auto numExtraPoints = 2;
45 using TDataPacket = std::array<float, MAX_FFT_SIZE>;
46 enum class EChannelType { Left = 0, Right, LeftAndRight };
47 enum class EFrequencyScale { Linear, Log };
48 enum class EAmplitudeScale { Linear, Decibel };
63 std::initializer_list<IColor> colors = {COLOR_RED, COLOR_GREEN},
64 EFrequencyScale freqScale = EFrequencyScale::Log,
65 EAmplitudeScale ampScale = EAmplitudeScale::Decibel,
66 float curveThickness = 2.0,
67 float gridThickness = 1.0,
68 float fillOpacity = 0.25,
69 float attackTimeMs = 3.0,
70 float decayTimeMs = 50.0)
73 , mChannelColors(colors)
74 , mFreqScale(freqScale)
76 , mCurveThickness(curveThickness)
77 , mGridThickness(gridThickness)
78 , mFillOpacity(fillOpacity)
79 , mAttackTimeMs(attackTimeMs)
80 , mDecayTimeMs(decayTimeMs)
82 assert(colors.size() >= MAXNC);
85 SetFreqRange(FirstBinFreq(), NyquistFreq());
86 SetAmpRange(
DBToAmp(-90.0f), 1.0f);
92 auto* pFftSizeMenu = mMenu.AddItem(
"FFT Size",
new IPopupMenu(
"FFT Size", {
"64",
"128",
"256",
"512",
"1024",
"2048",
"4096"}))->GetSubmenu();
93 auto* pChansMenu = mMenu.AddItem(
"Channels",
new IPopupMenu(
"Channels", {
"L",
"R",
"L + R"}))->GetSubmenu();
94 auto* pFreqScaleMenu = mMenu.AddItem(
"Freq Scaling",
new IPopupMenu(
"Freq Scaling", {
"Linear",
"Log"}))->GetSubmenu();
96 pFftSizeMenu->CheckItem(0, mFFTSize == 64);
97 pFftSizeMenu->CheckItem(1, mFFTSize == 128);
98 pFftSizeMenu->CheckItem(2, mFFTSize == 256);
99 pFftSizeMenu->CheckItem(3, mFFTSize == 512);
100 pFftSizeMenu->CheckItem(4, mFFTSize == 1024);
101 pFftSizeMenu->CheckItem(5, mFFTSize == 2048);
102 pFftSizeMenu->CheckItem(6, mFFTSize == 4096);
104 pChansMenu->CheckItem(0, mChanType == EChannelType::Left);
105 pChansMenu->CheckItem(1, mChanType == EChannelType::Right);
106 pChansMenu->CheckItem(2, mChanType == EChannelType::LeftAndRight);
107 pFreqScaleMenu->CheckItem(0, mFreqScale == EFrequencyScale::Linear);
108 pFreqScaleMenu->CheckItem(1, mFreqScale == EFrequencyScale::Log);
116 mCursorAmp = CalcYNorm(1.0 - y/mWidgetBounds.
H(), mAmpScale,
true);
117 mCursorFreq = CalcXNorm(x/mWidgetBounds.
W(), mFreqScale,
true) * NyquistFreq();
124 const char* title = pSelectedMenu->GetRootTitle();
126 if (strcmp(title,
"FFT Size") == 0)
128 int fftSize = atoi(pSelectedMenu->GetChosenItem()->GetText());
132 else if (strcmp(title,
"Channels") == 0)
134 const char* chanStr = pSelectedMenu->GetChosenItem()->GetText();
135 if (strcmp(chanStr,
"L") == 0) mChanType = EChannelType::Left;
136 else if (strcmp(chanStr,
"R") == 0) mChanType = EChannelType::Right;
137 else if (strcmp(chanStr,
"L + R") == 0) mChanType = EChannelType::LeftAndRight;
139 else if (strcmp(title,
"Freq Scaling") == 0)
141 auto index = pSelectedMenu->GetChosenItemIdx();
142 SetFrequencyScale(index == 0 ? EFrequencyScale::Linear : EFrequencyScale::Log);
162 for (
auto c = d.chanOffset; c < (d.chanOffset + d.nChans); c++)
164 CalculateYPoints(c, d.vals[c]);
167 else if (msgTag == kMsgTagSampleRate)
173 else if (msgTag == kMsgTagFFTSize)
176 stream.
Get(&fftSize, 0);
179 else if (msgTag == kMsgTagOctaveGain)
182 stream.
Get(&octaveGain, 0);
183 SetOctaveGain(octaveGain);
194 if (mStyle.drawFrame)
204 while (freq <= mFreqHi)
206 auto t = CalcXNorm(freq, mFreqScale);
207 auto x0 = t * mWidgetBounds.
W();
208 auto y0 = mWidgetBounds.B;
210 auto y1 = mWidgetBounds.T;
216 else if (freq < 100.0)
218 else if (freq < 1000.0)
220 else if (freq < 10000.0)
227 if (mAmpScale == EAmplitudeScale::Decibel)
230 const auto dBYHi =
AmpToDB(mAmpHi);
232 while (ampDB <= dBYHi)
234 auto t =
Clip(CalcYNorm(ampDB, EAmplitudeScale::Decibel), 0.0f, 1.0f);
236 auto x0 = mWidgetBounds.L;
237 auto y0 = t * mWidgetBounds.
H();
238 auto x1 = mWidgetBounds.R;
252 for (
auto c = 0; c < MAXNC; c++)
254 if ((c == 0) && (mChanType == EChannelType::Right))
256 if ((c == 1) && (mChanType == EChannelType::Left))
259 int nPoints = NumPoints();
260 IColor fillColor = mChannelColors[c].WithOpacity(mFillOpacity);
261 g.
DrawData(mChannelColors[c], mWidgetBounds, mYPoints[c].data(), nPoints, mXPoints.data(), 0, mCurveThickness, &fillColor);
269 if (mCursorFreq >= 0.0)
271 label.SetFormatted(64,
"%.1fHz", mCursorFreq);
275 if (mAmpScale == EAmplitudeScale::Linear)
276 label.SetFormatted(64,
"%.3fs", mCursorAmp);
278 label.SetFormatted(64,
"%ddB", (
int) mCursorAmp);
285 void SetFFTSize(
int fftSize)
288 assert(fftSize <= MAX_FFT_SIZE);
293 SetFreqRange(FirstBinFreq(), NyquistFreq());
294 SetSmoothing(mAttackTimeMs, mDecayTimeMs);
298 void SetSampleRate(
double sampleRate)
300 mSampleRate = sampleRate;
301 SetFreqRange(FirstBinFreq(), NyquistFreq());
302 SetSmoothing(mAttackTimeMs, mDecayTimeMs);
306 void SetFreqRange(
float freqLo,
float freqHi)
313 void SetFrequencyScale(EFrequencyScale scale)
320 void SetAmpRange(
float ampLo,
float ampHi)
327 void SetOctaveGain(
float octaveGain)
329 mOctaveGain = octaveGain;
333 void SetSmoothing(
float attackTimeMs,
float releaseTimeMs)
335 auto attackTimeSec = attackTimeMs * 0.001f;
336 auto releaseTimeSec = releaseTimeMs * 0.001f;
337 auto updatePeriod = (float) mFFTSize / (
float) mSampleRate;
338 mAttackCoeff = exp(-updatePeriod / attackTimeSec);
339 mReleaseCoeff = exp(-updatePeriod / releaseTimeSec);
343 float ApplyOctaveGain(
float amp,
float freqNorm)
346 const float centerFreq = 500.0f;
347 float centerFreqNorm = (centerFreq - mFreqLo)/(mFreqHi - mFreqLo);
349 if (mOctaveGain > 0.0)
351 amp *= freqNorm/centerFreqNorm;
359 mXPoints.resize(NumPoints());
361 for (
auto c = 0; c < MAXNC; c++)
363 mYPoints[c].assign(NumPoints(), 0.0f);
364 mEnvelopeValues[c].assign(NumPoints(), 0.0f);
368 void CalculateXPoints()
370 const auto numBins = NumBins();
371 const auto xIncr = (1.0f /
static_cast<float>(numBins-1)) * NyquistFreq();
373 for (
auto i = 1; i < numBins; i++)
375 auto xVal = CalcXNorm(
float(i) * xIncr, mFreqScale);
378 mXPoints[numBins] = mXPoints[numBins-1];
379 mXPoints[numBins+1] = mXPoints[0];
382 void CalculateYPoints(
int ch,
const TDataPacket& powerSpectrum)
384 const auto numBins = NumBins();
386 for (
auto i = 0; i < numBins; i++)
388 const auto adjustedAmp = ApplyOctaveGain(powerSpectrum[i],
static_cast<float>(numBins-1));
389 float rawVal = (mAmpScale == EAmplitudeScale::Decibel)
390 ?
AmpToDB(adjustedAmp + 1e-30f)
392 rawVal =
Clip(CalcYNorm(rawVal, mAmpScale), 0.0f, 1.0f);
394 float prevVal = mEnvelopeValues[ch][i];
396 if (rawVal > prevVal)
397 newVal = mAttackCoeff * prevVal + (1.0f - mAttackCoeff) * rawVal;
399 newVal = mReleaseCoeff * prevVal + (1.0f - mReleaseCoeff) * rawVal;
401 mEnvelopeValues[ch][i] = newVal;
402 mYPoints[ch][i] = newVal;
408 auto offset = mCurveThickness/mWidgetBounds.
H();
410 mYPoints[ch][numBins] = -offset;
411 mYPoints[ch][numBins+1] = -offset;
417 float CalcXNorm(
float x, EFrequencyScale scale,
bool inverted =
false)
419 const auto nyquist = NyquistFreq();
423 case EFrequencyScale::Linear:
426 return (x - mFreqLo) / (mFreqHi - mFreqLo);
428 return (mFreqLo + x * (mFreqHi - mFreqLo)) / nyquist;
430 case EFrequencyScale::Log:
432 const auto logXLo = std::log(mFreqLo / nyquist);
433 const auto logXHi = std::log(mFreqHi / nyquist);
436 return (std::log(x / nyquist) - logXLo) / (logXHi - logXLo);
438 return std::exp(logXLo + x * (logXHi - logXLo));
444 float CalcYNorm(
float y, EAmplitudeScale scale,
bool inverted =
false)
const
448 case EAmplitudeScale::Linear:
451 return (y - mAmpLo) / (mAmpHi - mAmpLo);
453 return mAmpLo + y * (mAmpHi - mAmpLo);
455 case EAmplitudeScale::Decibel:
457 const auto dBYLo =
AmpToDB(mAmpLo);
458 const auto dBYHi =
AmpToDB(mAmpHi);
461 return (y - dBYLo) / (dBYHi - dBYLo);
463 return dBYLo + y * (dBYHi - dBYLo);
468 int NumPoints()
const {
return FillCurves() ? NumBins() + numExtraPoints : NumBins(); }
469 int NumBins()
const {
return mFFTSize / 2; }
470 double FirstBinFreq()
const {
return NyquistFreq()/mFFTSize; }
471 double NyquistFreq()
const {
return mSampleRate * 0.5; }
472 bool FillCurves()
const {
return mFillOpacity > 0.0f; }
475 std::vector<IColor> mChannelColors;
476 EFrequencyScale mFreqScale;
477 EAmplitudeScale mAmpScale;
479 double mSampleRate = 44100.0;
481 float mOctaveGain = 0.0;
482 float mFreqLo = 20.0;
483 float mFreqHi = 22050.0;
486 float mAttackTimeMs = 3.0;
487 float mDecayTimeMs = 50.0;
488 EChannelType mChanType = EChannelType::LeftAndRight;
490 float mCurveThickness = 1.0f;
491 float mGridThickness = 1.0f;
492 float mFillOpacity = 0.5f;
493 float mCursorAmp = 0.0;
494 float mCursorFreq = -1.0;
497 std::vector<float> mXPoints;
498 std::array<std::vector<float>, MAXNC> mYPoints;
499 std::array<std::vector<float>, MAXNC> mEnvelopeValues;
500 float mAttackCoeff = 0.2f;
501 float mReleaseCoeff = 0.99f;
504END_IGRAPHICS_NAMESPACE
This file contains the base IControl implementation, along with some base classes for specific types ...
Manages a non-owned block of memory, for receiving arbitrary message byte streams.
int Get(T *pDst, int startPos) const
Get arbitary typed data from the stream.
The lowest level base class of an IGraphics control.
void SetTargetRECT(const IRECT &bounds)
Set the rectangular mouse tracking target area, within the graphics context for this control.
IGEditorDelegate * GetDelegate()
Gets a pointer to the class implementing the IEditorDelegate interface that handles parameter changes...
virtual void SetDirty(bool triggerAction=true, int valIdx=kNoValIdx)
Mark the control as dirty, i.e.
virtual void SendArbitraryMsgFromUI(int msgTag, int ctrlTag=kNoTag, int dataSize=0, const void *pData=nullptr)
SendArbitraryMsgFromUI (Abbreviation: SAMFUI)
The lowest level base class of an IGraphics context.
virtual void DrawRect(const IColor &color, const IRECT &bounds, const IBlend *pBlend=0, float thickness=1.f)
Draw a rectangle to the graphics context.
void DrawText(const IText &text, const char *str, const IRECT &bounds, const IBlend *pBlend=0)
Draw some text to the graphics context in a specific rectangle.
void CreatePopupMenu(IControl &control, IPopupMenu &menu, const IRECT &bounds, int valIdx=0)
Shows a pop up/contextual menu in relation to a rectangular region of the graphics context.
virtual void DrawLine(const IColor &color, float x1, float y1, float x2, float y2, const IBlend *pBlend=0, float thickness=1.f)
Draw a line to the graphics context.
virtual void DrawData(const IColor &color, const IRECT &bounds, float *normYPoints, int nPoints, float *normXPoints=nullptr, const IBlend *pBlend=0, float thickness=1.f, const IColor *pFillColor=nullptr)
Draw a line between a collection of normalized points.
ISender is a utility class which can be used to defer data from the realtime audio processing and sen...
Vectorial multi-channel capable spectrum analyzer controlDerived from work by Alex Harker and Matthew...
void OnMsgFromDelegate(int msgTag, int dataSize, const void *pData) override
Implement to receive messages sent to the control, see IEditorDelegate:SendControlMsgFromDelegate()
IVSpectrumAnalyzerControl(const IRECT &bounds, const char *label="", const IVStyle &style=DEFAULT_STYLE, std::initializer_list< IColor > colors={COLOR_RED, COLOR_GREEN}, EFrequencyScale freqScale=EFrequencyScale::Log, EAmplitudeScale ampScale=EAmplitudeScale::Decibel, float curveThickness=2.0, float gridThickness=1.0, float fillOpacity=0.25, float attackTimeMs=3.0, float decayTimeMs=50.0)
Create a IVSpectrumAnalyzerControl.
void OnPopupMenuSelection(IPopupMenu *pSelectedMenu, int valIdx) override
Implement this method to handle popup menu selection after IGraphics::CreatePopupMenu/IControlPromptU...
void OnResize() override
Called when IControl is constructed or resized using SetRect().
void Draw(IGraphics &g) override
Draw the control to the graphics context.
void OnMouseOver(float x, float y, const IMouseMod &mod) override
Implement this method to respond to a mouseover event on this control.
void OnMouseDown(float x, float y, const IMouseMod &mod) override
Implement this method to respond to a mouse down event on this control.
A base interface to be combined with IControl for vectorial controls "IVControls",...
IRECT MakeRects(const IRECT &parent, bool hasHandle=false)
Calculate the rectangles for the various areas, depending on the style.
virtual void DrawBackground(IGraphics &g, const IRECT &rect)
Draw the IVControl background (usually transparent)
void AttachIControl(IControl *pControl, const char *label)
Call in the constructor of your IVControl to link the IVectorBase and IControl.
virtual void DrawLabel(IGraphics &g)
Draw the IVControl label text.
const IColor & GetColor(EVColor color) const
Get value of a specific EVColor in the IVControl.
BEGIN_IPLUG_NAMESPACE T Clip(T x, T lo, T hi)
Clips the value x between lo and hi.
static double AmpToDB(double amp)
static double DBToAmp(double dB)
Calculates gain from a given dB value.
Used to manage color data, independent of draw class/platform.
Used to manage mouse modifiers i.e.
Used to manage a rectangular area, independent of draw class/platform.
IRECT GetFromTRHC(float w, float h) const
Get a subrect of this IRECT expanding from the top-right corner.
IRECT FracRectVertical(float frac, bool fromTop=false) const
Returns a new IRECT with a height that is multiplied by frac.
void Constrain(float &x, float &y) const
Ensure the point (x,y) is inside this IRECT.
ISenderData is used to represent a typed data packet, that may contain values for multiple channels.
A struct encapsulating a set of properties used to configure IVControls.