-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathNeuralAmpModeler.cpp
821 lines (734 loc) · 30.6 KB
/
NeuralAmpModeler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
#include <algorithm> // std::clamp
#include <cmath> // pow
#include <filesystem>
#include <iostream>
#include <utility>
#include "Colors.h"
#include "NeuralAmpModelerCore/NAM/activations.h"
// clang-format off
// These includes need to happen in this order or else the latter won't know
// a bunch of stuff.
#include "NeuralAmpModeler.h"
#include "IPlug_include_in_plug_src.h"
// clang-format on
#include "architecture.hpp"
#include "NeuralAmpModelerControls.h"
using namespace iplug;
using namespace igraphics;
const double kDCBlockerFrequency = 5.0;
// Styles
const IVColorSpec colorSpec{
DEFAULT_BGCOLOR, // Background
PluginColors::NAM_THEMECOLOR, // Foreground
PluginColors::NAM_THEMECOLOR.WithOpacity(0.3f), // Pressed
PluginColors::NAM_THEMECOLOR.WithOpacity(0.4f), // Frame
PluginColors::MOUSEOVER, // Highlight
DEFAULT_SHCOLOR, // Shadow
PluginColors::NAM_THEMECOLOR, // Extra 1
COLOR_RED, // Extra 2 --> color for clipping in meters
PluginColors::NAM_THEMECOLOR.WithContrast(0.1f), // Extra 3
};
const IVStyle style =
IVStyle{true, // Show label
true, // Show value
colorSpec,
{DEFAULT_TEXT_SIZE + 3.f, EVAlign::Middle, PluginColors::NAM_THEMEFONTCOLOR}, // Knob label text5
{DEFAULT_TEXT_SIZE + 3.f, EVAlign::Bottom, PluginColors::NAM_THEMEFONTCOLOR}, // Knob value text
DEFAULT_HIDE_CURSOR,
DEFAULT_DRAW_FRAME,
false,
DEFAULT_EMBOSS,
0.2f,
2.f,
DEFAULT_SHADOW_OFFSET,
DEFAULT_WIDGET_FRAC,
DEFAULT_WIDGET_ANGLE};
const IVStyle titleStyle =
DEFAULT_STYLE.WithValueText(IText(30, COLOR_WHITE, "Michroma-Regular")).WithDrawFrame(false).WithShadowOffset(2.f);
NeuralAmpModeler::NeuralAmpModeler(const InstanceInfo& info)
: Plugin(info, MakeConfig(kNumParams, kNumPresets))
{
nam::activations::Activation::enable_fast_tanh();
GetParam(kInputLevel)->InitGain("Input", 0.0, -20.0, 20.0, 0.1);
GetParam(kToneBass)->InitDouble("Bass", 5.0, 0.0, 10.0, 0.1);
GetParam(kToneMid)->InitDouble("Middle", 5.0, 0.0, 10.0, 0.1);
GetParam(kToneTreble)->InitDouble("Treble", 5.0, 0.0, 10.0, 0.1);
GetParam(kOutputLevel)->InitGain("Output", 0.0, -40.0, 40.0, 0.1);
GetParam(kNoiseGateThreshold)->InitGain("Gate", -80.0, -100.0, 0.0, 0.1);
GetParam(kNoiseGateActive)->InitBool("NoiseGateActive", true);
GetParam(kEQActive)->InitBool("ToneStack", true);
GetParam(kOutNorm)->InitBool("OutNorm", true);
GetParam(kIRToggle)->InitBool("IRToggle", true);
mNoiseGateTrigger.AddListener(&mNoiseGateGain);
mMakeGraphicsFunc = [&]() {
#ifdef OS_IOS
auto scaleFactor = GetScaleForScreen(PLUG_WIDTH, PLUG_HEIGHT) * 0.85f;
#else
auto scaleFactor = 1.0f;
#endif
return MakeGraphics(*this, PLUG_WIDTH, PLUG_HEIGHT, PLUG_FPS, scaleFactor);
};
mLayoutFunc = [&](IGraphics* pGraphics) {
pGraphics->AttachCornerResizer(EUIResizerMode::Scale, false);
pGraphics->AttachTextEntryControl();
pGraphics->EnableMouseOver(true);
pGraphics->EnableTooltips(true);
pGraphics->EnableMultiTouch(true);
pGraphics->LoadFont("Roboto-Regular", ROBOTO_FN);
pGraphics->LoadFont("Michroma-Regular", MICHROMA_FN);
const auto helpSVG = pGraphics->LoadSVG(HELP_FN);
const auto fileSVG = pGraphics->LoadSVG(FILE_FN);
const auto crossSVG = pGraphics->LoadSVG(CLOSE_BUTTON_FN);
const auto rightArrowSVG = pGraphics->LoadSVG(RIGHT_ARROW_FN);
const auto leftArrowSVG = pGraphics->LoadSVG(LEFT_ARROW_FN);
const auto modelIconSVG = pGraphics->LoadSVG(MODEL_ICON_FN);
const auto irIconOnSVG = pGraphics->LoadSVG(IR_ICON_ON_FN);
const auto irIconOffSVG = pGraphics->LoadSVG(IR_ICON_OFF_FN);
const auto backgroundBitmap = pGraphics->LoadBitmap(BACKGROUND_FN);
const auto fileBackgroundBitmap = pGraphics->LoadBitmap(FILEBACKGROUND_FN);
const auto linesBitmap = pGraphics->LoadBitmap(LINES_FN);
const auto knobBackgroundBitmap = pGraphics->LoadBitmap(KNOBBACKGROUND_FN);
const auto switchHandleBitmap = pGraphics->LoadBitmap(SLIDESWITCHHANDLE_FN);
const auto meterBackgroundBitmap = pGraphics->LoadBitmap(METERBACKGROUND_FN);
const auto b = pGraphics->GetBounds();
const auto mainArea = b.GetPadded(-20);
const auto contentArea = mainArea.GetPadded(-10);
const auto titleHeight = 50.0f;
const auto titleArea = contentArea.GetFromTop(titleHeight);
// Areas for knobs
const auto knobsPad = 20.0f;
const auto knobsExtraSpaceBelowTitle = 25.0f;
const auto knobHeight = 120.f;
const auto singleKnobPad = -2.0f;
const auto knobsArea = contentArea.GetFromTop(knobHeight)
.GetReducedFromLeft(knobsPad)
.GetReducedFromRight(knobsPad)
.GetVShifted(titleHeight + knobsExtraSpaceBelowTitle);
const auto inputKnobArea = knobsArea.GetGridCell(0, kInputLevel, 1, numKnobs).GetPadded(-singleKnobPad);
const auto noiseGateArea = knobsArea.GetGridCell(0, kNoiseGateThreshold, 1, numKnobs).GetPadded(-singleKnobPad);
const auto bassKnobArea = knobsArea.GetGridCell(0, kToneBass, 1, numKnobs).GetPadded(-singleKnobPad);
const auto midKnobArea = knobsArea.GetGridCell(0, kToneMid, 1, numKnobs).GetPadded(-singleKnobPad);
const auto trebleKnobArea = knobsArea.GetGridCell(0, kToneTreble, 1, numKnobs).GetPadded(-singleKnobPad);
const auto outputKnobArea = knobsArea.GetGridCell(0, kOutputLevel, 1, numKnobs).GetPadded(-singleKnobPad);
const auto ngToggleArea =
noiseGateArea.GetVShifted(noiseGateArea.H()).SubRectVertical(2, 0).GetReducedFromTop(10.0f);
const auto eqToggleArea = midKnobArea.GetVShifted(midKnobArea.H()).SubRectVertical(2, 0).GetReducedFromTop(10.0f);
const auto outNormToggleArea =
outputKnobArea.GetVShifted(midKnobArea.H()).SubRectVertical(2, 0).GetReducedFromTop(10.0f);
// Areas for model and IR
const auto fileWidth = 200.0f;
const auto fileHeight = 30.0f;
const auto irYOffset = 38.0f;
const auto modelArea =
contentArea.GetFromBottom((2.0f * fileHeight)).GetFromTop(fileHeight).GetMidHPadded(fileWidth).GetVShifted(-1);
const auto modelIconArea = modelArea.GetFromLeft(30).GetTranslated(-40, 10);
const auto irArea = modelArea.GetVShifted(irYOffset);
const auto irSwitchArea = irArea.GetFromLeft(30.0f).GetHShifted(-40.0f).GetScaledAboutCentre(0.6f);
// Areas for meters
const auto inputMeterArea = contentArea.GetFromLeft(30).GetHShifted(-20).GetMidVPadded(100).GetVShifted(-25);
const auto outputMeterArea = contentArea.GetFromRight(30).GetHShifted(20).GetMidVPadded(100).GetVShifted(-25);
// Misc Areas
const auto helpButtonArea = mainArea.GetFromTRHC(50, 50).GetCentredInside(20, 20);
const auto sampleRateWarningArea = inputMeterArea.GetFromBottom(16.f).GetTranslated(12.f, 16.f).GetFromLeft(300.f);
// Model loader button
auto loadModelCompletionHandler = [&](const WDL_String& fileName, const WDL_String& path) {
if (fileName.GetLength())
{
// Sets mNAMPath and mStagedNAM
const std::string msg = _StageModel(fileName);
// TODO error messages like the IR loader.
if (msg.size())
{
std::stringstream ss;
ss << "Failed to load NAM model. Message:\n\n" << msg;
GetUI()->ShowMessageBox(ss.str().c_str(), "Failed to load model!", kMB_OK);
}
std::cout << "Loaded: " << fileName.Get() << std::endl;
}
};
// IR loader button
auto loadIRCompletionHandler = [&](const WDL_String& fileName, const WDL_String& path) {
if (fileName.GetLength())
{
mIRPath = fileName;
const dsp::wav::LoadReturnCode retCode = _StageIR(fileName);
if (retCode != dsp::wav::LoadReturnCode::SUCCESS)
{
std::stringstream message;
message << "Failed to load IR file " << fileName.Get() << ":\n";
message << dsp::wav::GetMsgForLoadReturnCode(retCode);
GetUI()->ShowMessageBox(message.str().c_str(), "Failed to load IR!", kMB_OK);
}
}
};
pGraphics->AttachBackground(BACKGROUND_FN);
pGraphics->AttachControl(new IBitmapControl(b, linesBitmap));
pGraphics->AttachControl(new IVLabelControl(titleArea, "NEURAL AMP MODELER", titleStyle));
pGraphics->AttachControl(new ISVGControl(modelIconArea, modelIconSVG));
#ifdef NAM_PICK_DIRECTORY
const std::string defaultNamFileString = "Select model directory...";
const std::string defaultIRString = "Select IR directory...";
#else
const std::string defaultNamFileString = "Select model...";
const std::string defaultIRString = "Select IR...";
#endif
pGraphics->AttachControl(new NAMFileBrowserControl(modelArea, kMsgTagClearModel, defaultNamFileString.c_str(),
"nam", loadModelCompletionHandler, style, fileSVG, crossSVG,
leftArrowSVG, rightArrowSVG, fileBackgroundBitmap),
kCtrlTagModelFileBrowser);
pGraphics->AttachControl(new ISVGSwitchControl(irSwitchArea, {irIconOffSVG, irIconOnSVG}, kIRToggle));
pGraphics->AttachControl(
new NAMFileBrowserControl(irArea, kMsgTagClearIR, defaultIRString.c_str(), "wav", loadIRCompletionHandler, style,
fileSVG, crossSVG, leftArrowSVG, rightArrowSVG, fileBackgroundBitmap),
kCtrlTagIRFileBrowser);
pGraphics->AttachControl(new NAMSwitchControl(ngToggleArea, kNoiseGateActive, " ", style, switchHandleBitmap));
pGraphics->AttachControl(new NAMSwitchControl(eqToggleArea, kEQActive, "EQ", style, switchHandleBitmap));
pGraphics->AttachControl(
new NAMSwitchControl(outNormToggleArea, kOutNorm, "Normalize", style, switchHandleBitmap), kCtrlTagOutNorm);
// The knobs
pGraphics->AttachControl(new NAMKnobControl(inputKnobArea, kInputLevel, "", style, knobBackgroundBitmap));
pGraphics->AttachControl(new NAMKnobControl(noiseGateArea, kNoiseGateThreshold, "", style, knobBackgroundBitmap));
pGraphics->AttachControl(
new NAMKnobControl(bassKnobArea, kToneBass, "", style, knobBackgroundBitmap), -1, "EQ_KNOBS");
pGraphics->AttachControl(
new NAMKnobControl(midKnobArea, kToneMid, "", style, knobBackgroundBitmap), -1, "EQ_KNOBS");
pGraphics->AttachControl(
new NAMKnobControl(trebleKnobArea, kToneTreble, "", style, knobBackgroundBitmap), -1, "EQ_KNOBS");
pGraphics->AttachControl(new NAMKnobControl(outputKnobArea, kOutputLevel, "", style, knobBackgroundBitmap));
// The meters
pGraphics->AttachControl(new NAMMeterControl(inputMeterArea, meterBackgroundBitmap, style), kCtrlTagInputMeter);
pGraphics->AttachControl(new NAMMeterControl(outputMeterArea, meterBackgroundBitmap, style), kCtrlTagOutputMeter);
// A warning when NAM isn't being run in the right sample rate:
pGraphics->AttachControl(new NAMSampleRateWarningControl(sampleRateWarningArea), kCtrlTagSampleRateWarning);
// Help/about box
pGraphics->AttachControl(new NAMCircleButtonControl(
helpButtonArea,
[pGraphics](IControl* pCaller) {
pGraphics->GetControlWithTag(kCtrlTagAboutBox)->As<NAMAboutBoxControl>()->HideAnimated(false);
},
helpSVG));
pGraphics->AttachControl(new NAMAboutBoxControl(b, backgroundBitmap, style), kCtrlTagAboutBox)->Hide(true);
pGraphics->ForAllControlsFunc([](IControl* pControl) {
pControl->SetMouseEventsWhenDisabled(true);
pControl->SetMouseOverWhenDisabled(true);
});
pGraphics->GetControlWithTag(kCtrlTagOutNorm)->SetMouseEventsWhenDisabled(false);
};
}
NeuralAmpModeler::~NeuralAmpModeler()
{
_DeallocateIOPointers();
}
void NeuralAmpModeler::ProcessBlock(iplug::sample** inputs, iplug::sample** outputs, int nFrames)
{
const size_t numChannelsExternalIn = (size_t)NInChansConnected();
const size_t numChannelsExternalOut = (size_t)NOutChansConnected();
const size_t numChannelsInternal = kNumChannelsInternal;
const size_t numFrames = (size_t)nFrames;
const double sampleRate = GetSampleRate();
// Disable floating point denormals
std::fenv_t fe_state;
std::feholdexcept(&fe_state);
disable_denormals();
_PrepareBuffers(numChannelsInternal, numFrames);
// Input is collapsed to mono in preparation for the NAM.
_ProcessInput(inputs, numFrames, numChannelsExternalIn, numChannelsInternal);
_ApplyDSPStaging();
const bool noiseGateActive = GetParam(kNoiseGateActive)->Value();
const bool toneStackActive = GetParam(kEQActive)->Value();
// Noise gate trigger
sample** triggerOutput = mInputPointers;
if (noiseGateActive)
{
const double time = 0.01;
const double threshold = GetParam(kNoiseGateThreshold)->Value(); // GetParam...
const double ratio = 0.1; // Quadratic...
const double openTime = 0.005;
const double holdTime = 0.01;
const double closeTime = 0.05;
const dsp::noise_gate::TriggerParams triggerParams(time, threshold, ratio, openTime, holdTime, closeTime);
mNoiseGateTrigger.SetParams(triggerParams);
mNoiseGateTrigger.SetSampleRate(sampleRate);
triggerOutput = mNoiseGateTrigger.Process(mInputPointers, numChannelsInternal, numFrames);
}
if (mModel != nullptr)
{
// TODO multi-channel processing; Issue
// Make sure it's multi-threaded or else this won't perform well!
mModel->process(triggerOutput[0], mOutputPointers[0], nFrames);
mModel->finalize_(nFrames);
// Normalize loudness
if (GetParam(kOutNorm)->Value())
{
_NormalizeModelOutput(mOutputPointers, numChannelsInternal, numFrames);
}
}
else
{
_FallbackDSP(triggerOutput, mOutputPointers, numChannelsInternal, numFrames);
}
// Apply the noise gate
sample** gateGainOutput =
noiseGateActive ? mNoiseGateGain.Process(mOutputPointers, numChannelsInternal, numFrames) : mOutputPointers;
sample** toneStackOutPointers = gateGainOutput;
if (toneStackActive)
{
// Translate params from knob 0-10 to dB.
// Tuned ranges based on my ear. E.g. seems treble doesn't need nearly as
// much swing as bass can use.
const double bassGainDB = 4.0 * (GetParam(kToneBass)->Value() - 5.0); // +/- 20
const double midGainDB = 3.0 * (GetParam(kToneMid)->Value() - 5.0); // +/- 15
const double trebleGainDB = 2.0 * (GetParam(kToneTreble)->Value() - 5.0); // +/- 10
const double bassFrequency = 150.0;
const double midFrequency = 425.0;
const double trebleFrequency = 1800.0;
const double bassQuality = 0.707;
// Wider EQ on mid bump up to sound less honky.
const double midQuality = midGainDB < 0.0 ? 1.5 : 0.7;
const double trebleQuality = 0.707;
// Define filter parameters
recursive_linear_filter::BiquadParams bassParams(sampleRate, bassFrequency, bassQuality, bassGainDB);
recursive_linear_filter::BiquadParams midParams(sampleRate, midFrequency, midQuality, midGainDB);
recursive_linear_filter::BiquadParams trebleParams(sampleRate, trebleFrequency, trebleQuality, trebleGainDB);
// Apply tone stack
// Set parameters
mToneBass.SetParams(bassParams);
mToneMid.SetParams(midParams);
mToneTreble.SetParams(trebleParams);
sample** bassPointers = mToneBass.Process(gateGainOutput, numChannelsInternal, numFrames);
sample** midPointers = mToneMid.Process(bassPointers, numChannelsInternal, numFrames);
sample** treblePointers = mToneTreble.Process(midPointers, numChannelsInternal, numFrames);
toneStackOutPointers = treblePointers;
}
sample** irPointers = toneStackOutPointers;
if (mIR != nullptr && GetParam(kIRToggle)->Value())
irPointers = mIR->Process(toneStackOutPointers, numChannelsInternal, numFrames);
// And the HPF for DC offset (Issue 271)
const double highPassCutoffFreq = kDCBlockerFrequency;
// const double lowPassCutoffFreq = 20000.0;
const recursive_linear_filter::HighPassParams highPassParams(sampleRate, highPassCutoffFreq);
// const recursive_linear_filter::LowPassParams lowPassParams(sampleRate, lowPassCutoffFreq);
mHighPass.SetParams(highPassParams);
// mLowPass.SetParams(lowPassParams);
sample** hpfPointers = mHighPass.Process(irPointers, numChannelsInternal, numFrames);
// sample** lpfPointers = mLowPass.Process(hpfPointers, numChannelsInternal, numFrames);
// restore previous floating point state
std::feupdateenv(&fe_state);
// Let's get outta here
// This is where we exit mono for whatever the output requires.
_ProcessOutput(hpfPointers, outputs, numFrames, numChannelsInternal, numChannelsExternalOut);
// _ProcessOutput(lpfPointers, outputs, numFrames, numChannelsInternal, numChannelsExternalOut);
// * Output of input leveling (inputs -> mInputPointers),
// * Output of output leveling (mOutputPointers -> outputs)
_UpdateMeters(mInputPointers, outputs, numFrames, numChannelsInternal, numChannelsExternalOut);
}
void NeuralAmpModeler::OnReset()
{
const auto sampleRate = GetSampleRate();
// Tail is because the HPF DC blocker has a decay.
// 10 cycles should be enough to pass the VST3 tests checking tail behavior.
// I'm ignoring the model & IR, but it's not the end of the world.
const int tailCycles = 10;
SetTailSize(tailCycles * (int)(sampleRate / kDCBlockerFrequency));
mInputSender.Reset(sampleRate);
mOutputSender.Reset(sampleRate);
mCheckSampleRateWarning = true;
// If there is a model or IR loaded, they need to be checked for resampling.
_ResetModelAndIR(sampleRate, GetBlockSize());
}
void NeuralAmpModeler::OnIdle()
{
mInputSender.TransmitData(*this);
mOutputSender.TransmitData(*this);
if (mNewModelLoadedInDSP)
{
if (auto* pGraphics = GetUI())
pGraphics->GetControlWithTag(kCtrlTagOutNorm)->SetDisabled(!mModel->HasLoudness());
mNewModelLoadedInDSP = false;
}
if (mCheckSampleRateWarning)
{
_CheckSampleRateWarning();
}
}
bool NeuralAmpModeler::SerializeState(IByteChunk& chunk) const
{
// Model directory (don't serialize the model itself; we'll just load it again
// when we unserialize)
chunk.PutStr(mNAMPath.Get());
chunk.PutStr(mIRPath.Get());
return SerializeParams(chunk);
}
int NeuralAmpModeler::UnserializeState(const IByteChunk& chunk, int startPos)
{
WDL_String dir;
startPos = chunk.GetStr(mNAMPath, startPos);
startPos = chunk.GetStr(mIRPath, startPos);
int retcode = UnserializeParams(chunk, startPos);
if (mNAMPath.GetLength())
_StageModel(mNAMPath);
if (mIRPath.GetLength())
_StageIR(mIRPath);
return retcode;
}
void NeuralAmpModeler::OnUIOpen()
{
Plugin::OnUIOpen();
if (mNAMPath.GetLength())
{
SendControlMsgFromDelegate(kCtrlTagModelFileBrowser, kMsgTagLoadedModel, mNAMPath.GetLength(), mNAMPath.Get());
// If it's not loaded yet, then mark as failed.
// If it's yet to be loaded, then the completion handler will set us straight once it runs.
if (mModel == nullptr && mStagedModel == nullptr)
SendControlMsgFromDelegate(kCtrlTagModelFileBrowser, kMsgTagLoadFailed);
}
if (mIRPath.GetLength())
{
SendControlMsgFromDelegate(kCtrlTagIRFileBrowser, kMsgTagLoadedIR, mIRPath.GetLength(), mIRPath.Get());
if (mIR == nullptr && mStagedIR == nullptr)
SendControlMsgFromDelegate(kCtrlTagIRFileBrowser, kMsgTagLoadFailed);
}
if (mModel != nullptr)
GetUI()->GetControlWithTag(kCtrlTagOutNorm)->SetDisabled(!mModel->HasLoudness());
mCheckSampleRateWarning = true;
}
void NeuralAmpModeler::OnParamChangeUI(int paramIdx, EParamSource source)
{
if (auto pGraphics = GetUI())
{
bool active = GetParam(paramIdx)->Bool();
switch (paramIdx)
{
case kNoiseGateActive: pGraphics->GetControlWithParamIdx(kNoiseGateThreshold)->SetDisabled(!active); break;
case kEQActive:
pGraphics->ForControlInGroup("EQ_KNOBS", [active](IControl* pControl) { pControl->SetDisabled(!active); });
break;
case kIRToggle: pGraphics->GetControlWithTag(kCtrlTagIRFileBrowser)->SetDisabled(!active);
default: break;
}
}
}
bool NeuralAmpModeler::OnMessage(int msgTag, int ctrlTag, int dataSize, const void* pData)
{
switch (msgTag)
{
case kMsgTagClearModel: mShouldRemoveModel = true; return true;
case kMsgTagClearIR: mShouldRemoveIR = true; return true;
case kMsgTagHighlightColor:
{
mHighLightColor.Set((const char*)pData);
if (GetUI())
{
GetUI()->ForStandardControlsFunc([&](IControl* pControl) {
if (auto* pVectorBase = pControl->As<IVectorBase>())
{
IColor color = IColor::FromColorCodeStr(mHighLightColor.Get());
pVectorBase->SetColor(kX1, color);
pVectorBase->SetColor(kPR, color.WithOpacity(0.3f));
pVectorBase->SetColor(kFR, color.WithOpacity(0.4f));
pVectorBase->SetColor(kX3, color.WithContrast(0.1f));
}
pControl->GetUI()->SetAllControlsDirty();
});
}
return true;
}
default: return false;
}
}
// Private methods ============================================================
void NeuralAmpModeler::_AllocateIOPointers(const size_t nChans)
{
if (mInputPointers != nullptr)
throw std::runtime_error("Tried to re-allocate mInputPointers without freeing");
mInputPointers = new sample*[nChans];
if (mInputPointers == nullptr)
throw std::runtime_error("Failed to allocate pointer to input buffer!\n");
if (mOutputPointers != nullptr)
throw std::runtime_error("Tried to re-allocate mOutputPointers without freeing");
mOutputPointers = new sample*[nChans];
if (mOutputPointers == nullptr)
throw std::runtime_error("Failed to allocate pointer to output buffer!\n");
}
void NeuralAmpModeler::_ApplyDSPStaging()
{
// Remove marked modules
if (mShouldRemoveModel)
{
mModel = nullptr;
mNAMPath.Set("");
mShouldRemoveModel = false;
mCheckSampleRateWarning = true;
}
if (mShouldRemoveIR)
{
mIR = nullptr;
mIRPath.Set("");
mShouldRemoveIR = false;
}
// Move things from staged to live
if (mStagedModel != nullptr)
{
// Move from staged to active DSP
mModel = std::move(mStagedModel);
mStagedModel = nullptr;
mNewModelLoadedInDSP = true;
mCheckSampleRateWarning = true;
}
if (mStagedIR != nullptr)
{
mIR = std::move(mStagedIR);
mStagedIR = nullptr;
}
}
void NeuralAmpModeler::_CheckSampleRateWarning()
{
if (auto* pGraphics = GetUI())
{
auto* control = pGraphics->GetControlWithTag(kCtrlTagSampleRateWarning)->As<NAMSampleRateWarningControl>();
bool showWarning = false;
if (_HaveModel())
{
const auto pluginSampleRate = GetSampleRate();
const auto namSampleRate = mModel->GetEncapsulatedSampleRate();
control->SetSampleRate(namSampleRate);
showWarning = pluginSampleRate != namSampleRate;
}
control->SetDisabled(!showWarning);
mCheckSampleRateWarning = false;
}
}
void NeuralAmpModeler::_DeallocateIOPointers()
{
if (mInputPointers != nullptr)
{
delete[] mInputPointers;
mInputPointers = nullptr;
}
if (mInputPointers != nullptr)
throw std::runtime_error("Failed to deallocate pointer to input buffer!\n");
if (mOutputPointers != nullptr)
{
delete[] mOutputPointers;
mOutputPointers = nullptr;
}
if (mOutputPointers != nullptr)
throw std::runtime_error("Failed to deallocate pointer to output buffer!\n");
}
void NeuralAmpModeler::_FallbackDSP(iplug::sample** inputs, iplug::sample** outputs, const size_t numChannels,
const size_t numFrames)
{
for (auto c = 0; c < numChannels; c++)
for (auto s = 0; s < numFrames; s++)
mOutputArray[c][s] = mInputArray[c][s];
}
void NeuralAmpModeler::_NormalizeModelOutput(iplug::sample** buffer, const size_t numChannels, const size_t numFrames)
{
if (!mModel)
return;
if (!mModel->HasLoudness())
return;
const double loudness = mModel->GetLoudness();
const double targetLoudness = -18.0;
const double gain = pow(10.0, (targetLoudness - loudness) / 20.0);
for (size_t c = 0; c < numChannels; c++)
{
for (size_t f = 0; f < numFrames; f++)
{
buffer[c][f] *= gain;
}
}
}
void NeuralAmpModeler::_ResetModelAndIR(const double sampleRate, const int maxBlockSize)
{
// Model
if (mStagedModel != nullptr)
{
mStagedModel->Reset(sampleRate, maxBlockSize);
}
else if (mModel != nullptr)
{
mModel->Reset(sampleRate, maxBlockSize);
}
// IR
if (mStagedIR != nullptr)
{
const double irSampleRate = mStagedIR->GetSampleRate();
if (irSampleRate != sampleRate)
{
const auto irData = mStagedIR->GetData();
mStagedIR = std::make_unique<dsp::ImpulseResponse>(irData, sampleRate);
}
}
else if (mIR != nullptr)
{
const double irSampleRate = mIR->GetSampleRate();
if (irSampleRate != sampleRate)
{
const auto irData = mIR->GetData();
mStagedIR = std::make_unique<dsp::ImpulseResponse>(irData, sampleRate);
}
}
}
std::string NeuralAmpModeler::_StageModel(const WDL_String& modelPath)
{
WDL_String previousNAMPath = mNAMPath;
try
{
auto dspPath = std::filesystem::u8path(modelPath.Get());
std::unique_ptr<nam::DSP> model = nam::get_dsp(dspPath);
std::unique_ptr<ResamplingNAM> temp = std::make_unique<ResamplingNAM>(std::move(model), GetSampleRate());
temp->Reset(GetSampleRate(), GetBlockSize());
mStagedModel = std::move(temp);
mNAMPath = modelPath;
SendControlMsgFromDelegate(kCtrlTagModelFileBrowser, kMsgTagLoadedModel, mNAMPath.GetLength(), mNAMPath.Get());
}
catch (std::runtime_error& e)
{
SendControlMsgFromDelegate(kCtrlTagModelFileBrowser, kMsgTagLoadFailed);
if (mStagedModel != nullptr)
{
mStagedModel = nullptr;
}
mNAMPath = previousNAMPath;
std::cerr << "Failed to read DSP module" << std::endl;
std::cerr << e.what() << std::endl;
return e.what();
}
return "";
}
dsp::wav::LoadReturnCode NeuralAmpModeler::_StageIR(const WDL_String& irPath)
{
// FIXME it'd be better for the path to be "staged" as well. Just in case the
// path and the model got caught on opposite sides of the fence...
WDL_String previousIRPath = mIRPath;
const double sampleRate = GetSampleRate();
dsp::wav::LoadReturnCode wavState = dsp::wav::LoadReturnCode::ERROR_OTHER;
try
{
auto irPathU8 = std::filesystem::u8path(irPath.Get());
mStagedIR = std::make_unique<dsp::ImpulseResponse>(irPathU8.string().c_str(), sampleRate);
wavState = mStagedIR->GetWavState();
}
catch (std::runtime_error& e)
{
wavState = dsp::wav::LoadReturnCode::ERROR_OTHER;
std::cerr << "Caught unhandled exception while attempting to load IR:" << std::endl;
std::cerr << e.what() << std::endl;
}
if (wavState == dsp::wav::LoadReturnCode::SUCCESS)
{
mIRPath = irPath;
SendControlMsgFromDelegate(kCtrlTagIRFileBrowser, kMsgTagLoadedIR, mIRPath.GetLength(), mIRPath.Get());
}
else
{
if (mStagedIR != nullptr)
{
mStagedIR = nullptr;
}
mIRPath = previousIRPath;
SendControlMsgFromDelegate(kCtrlTagIRFileBrowser, kMsgTagLoadFailed);
}
return wavState;
}
size_t NeuralAmpModeler::_GetBufferNumChannels() const
{
// Assumes input=output (no mono->stereo effects)
return mInputArray.size();
}
size_t NeuralAmpModeler::_GetBufferNumFrames() const
{
if (_GetBufferNumChannels() == 0)
return 0;
return mInputArray[0].size();
}
void NeuralAmpModeler::_PrepareBuffers(const size_t numChannels, const size_t numFrames)
{
const bool updateChannels = numChannels != _GetBufferNumChannels();
const bool updateFrames = updateChannels || (_GetBufferNumFrames() != numFrames);
// if (!updateChannels && !updateFrames) // Could we do this?
// return;
if (updateChannels)
{
_PrepareIOPointers(numChannels);
mInputArray.resize(numChannels);
mOutputArray.resize(numChannels);
}
if (updateFrames)
{
for (auto c = 0; c < mInputArray.size(); c++)
{
mInputArray[c].resize(numFrames);
std::fill(mInputArray[c].begin(), mInputArray[c].end(), 0.0);
}
for (auto c = 0; c < mOutputArray.size(); c++)
{
mOutputArray[c].resize(numFrames);
std::fill(mOutputArray[c].begin(), mOutputArray[c].end(), 0.0);
}
}
// Would these ever get changed by something?
for (auto c = 0; c < mInputArray.size(); c++)
mInputPointers[c] = mInputArray[c].data();
for (auto c = 0; c < mOutputArray.size(); c++)
mOutputPointers[c] = mOutputArray[c].data();
}
void NeuralAmpModeler::_PrepareIOPointers(const size_t numChannels)
{
_DeallocateIOPointers();
_AllocateIOPointers(numChannels);
}
void NeuralAmpModeler::_ProcessInput(iplug::sample** inputs, const size_t nFrames, const size_t nChansIn,
const size_t nChansOut)
{
// We'll assume that the main processing is mono for now. We'll handle dual amps later.
if (nChansOut != 1)
{
std::stringstream ss;
ss << "Expected mono output, but " << nChansOut << " output channels are requested!";
throw std::runtime_error(ss.str());
}
// On the standalone, we can probably assume that the user has plugged into only one input and they expect it to be
// carried straight through. Don't apply any division over nCahnsIn because we're just "catching anything out there."
// However, in a DAW, it's probably something providing stereo, and we want to take the average in order to avoid
// doubling the loudness.
#ifdef APP_API
const double gain = pow(10.0, GetParam(kInputLevel)->Value() / 20.0);
#else
const double gain = pow(10.0, GetParam(kInputLevel)->Value() / 20.0) / (float)nChansIn;
#endif
// Assume _PrepareBuffers() was already called
for (size_t c = 0; c < nChansIn; c++)
for (size_t s = 0; s < nFrames; s++)
if (c == 0)
mInputArray[0][s] = gain * inputs[c][s];
else
mInputArray[0][s] += gain * inputs[c][s];
}
void NeuralAmpModeler::_ProcessOutput(iplug::sample** inputs, iplug::sample** outputs, const size_t nFrames,
const size_t nChansIn, const size_t nChansOut)
{
const double gain = pow(10.0, GetParam(kOutputLevel)->Value() / 20.0);
// Assume _PrepareBuffers() was already called
if (nChansIn != 1)
throw std::runtime_error("Plugin is supposed to process in mono.");
// Broadcast the internal mono stream to all output channels.
const size_t cin = 0;
for (auto cout = 0; cout < nChansOut; cout++)
for (auto s = 0; s < nFrames; s++)
#ifdef APP_API // Ensure valid output to interface
outputs[cout][s] = std::clamp(gain * inputs[cin][s], -1.0, 1.0);
#else // In a DAW, other things may come next and should be able to handle large
// values.
outputs[cout][s] = gain * inputs[cin][s];
#endif
}
void NeuralAmpModeler::_UpdateMeters(sample** inputPointer, sample** outputPointer, const size_t nFrames,
const size_t nChansIn, const size_t nChansOut)
{
// Right now, we didn't specify MAXNC when we initialized these, so it's 1.
const int nChansHack = 1;
mInputSender.ProcessBlock(inputPointer, (int)nFrames, kCtrlTagInputMeter, nChansHack);
mOutputSender.ProcessBlock(outputPointer, (int)nFrames, kCtrlTagOutputMeter, nChansHack);
}