Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
305 changes: 170 additions & 135 deletions NeuralAmpModeler/NeuralAmpModeler.cpp

Large diffs are not rendered by default.

52 changes: 30 additions & 22 deletions NeuralAmpModeler/NeuralAmpModeler.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#pragma once

#include <array>
#include <atomic>
#include <mutex>

#include "../AudioDSPTools/dsp/NoiseGate.h"
#include "../AudioDSPTools/dsp/dsp.h"
Expand Down Expand Up @@ -101,22 +103,18 @@ class NeuralAmpModeler final : public iplug::Plugin
private:
static constexpr int kMaxInternalBlockSize = 2048;

// Moves DSP modules from staging area to the main area.
// Also deletes DSP modules that are flagged for removal.
// Exists so that we don't try to use a DSP module that's only
// partially-instantiated.
// Applies pending module and parameter changes at the start of a host block.
void _ApplyDSPStaging();
// Fallback that just copies inputs to outputs if mDSP doesn't hold a model.
void _FallbackDSP(iplug::sample** inputs, iplug::sample** outputs, const size_t numChannels, const size_t numFrames);
void _InitToneStack();
// Loads a NAM model and stores it to mStagedNAM
// Loads a NAM model and stores it to mStagedModel.
// Returns an empty string on success, or an error message on failure.
std::string _StageModel(const WDL_String& dspFile);
// Loads a WAV or NAM cab and stores it to mStagedCab.
// Returns an empty string on success, or an error message on failure.
std::string _StageCab(const WDL_String& cabPath);

bool _HaveModel() const { return this->mModel != nullptr; };
void _ProcessBlock(iplug::sample** inputs, iplug::sample** outputs, int nFrames, size_t numChannelsExternalIn,
size_t numChannelsExternalOut);
// Mix the host inputs to mono and apply input gain.
Expand Down Expand Up @@ -164,27 +162,37 @@ class NeuralAmpModeler final : public iplug::Plugin
// Input and output gain
double mInputGain = 1.0;
double mOutputGain = 1.0;
bool mCabEnabled = true;

// Noise gates
dsp::noise_gate::Trigger mNoiseGateTrigger; // Mono input to the trigger
dsp::noise_gate::Gain mNoiseGateGain; // Gain reduction applied to left/mono output of the amp...
dsp::noise_gate::Gain mNoiseGateGainRight; // ...and the right output, if applicable.
dsp::noise_gate::Gain mNoiseGateGain; // Gain reduction applied to left/mono output of the amp...
dsp::noise_gate::Gain mNoiseGateGainRight; // ...and the right output, if applicable.
// The model actually being used:
std::unique_ptr<ResamplingNAM> mModel;
// The cabinet, loaded from a WAV impulse response or NAM model.
std::unique_ptr<ResamplingNAM> mCab;
// Independent state for a mono cab processing the right side of a stereo amp.
std::unique_ptr<ResamplingNAM> mCabRight;
bool mCabIsWav = false;
// Manages switching what DSP is being used.
struct Cabinet
{
std::unique_ptr<ResamplingNAM> model;
// Independent state for a mono cab processing the right side of a stereo amp.
std::unique_ptr<ResamplingNAM> right;
bool isWav = false;

void Reset(double sampleRate);
};
Cabinet mCab;

// Mutex to prevent the staging routines (_StageModel(), _StageCab()) from changing what's in the "mStaged{Model,Cab}"
// members while _ApplyDSPStaging() is getting from them.
mutable std::mutex mDSPStagingMutex;
std::atomic<double> mDSPStagingSampleRate{iplug::DEFAULT_SAMPLE_RATE};
std::unique_ptr<ResamplingNAM> mStagedModel;
std::unique_ptr<ResamplingNAM> mStagedCab;
std::unique_ptr<ResamplingNAM> mStagedCabRight;
bool mStagedCabIsWav = false;
// Flags to take away the modules at a safe time.
std::atomic<bool> mShouldRemoveModel = false;
std::atomic<bool> mShouldRemoveCab = false;
Cabinet mStagedCab;
bool mShouldRemoveModel = false;
bool mShouldRemoveCab = false;

std::atomic<bool> mDSPGainsAndTimingDirty{true};
std::atomic<bool> mToneStackDirty{true};
std::atomic<bool> mSlimDirty{false};
std::atomic<bool> mNewModelLoadedInDSP = false;
std::atomic<bool> mModelCleared = false;

Expand All @@ -203,6 +211,6 @@ class NeuralAmpModeler final : public iplug::Plugin

std::unordered_map<std::string, double> mNAMParams = {{"Input", 0.0}, {"Output", 0.0}};

NAMSender<1> mInputSender;
NAMSender<2> mOutputSender;
NAMSender<1> mInputSender; // Mono input
NAMSender<2> mOutputSender; // Stereo output
};
26 changes: 13 additions & 13 deletions NeuralAmpModeler/NeuralAmpModelerControls.h
Original file line number Diff line number Diff line change
Expand Up @@ -258,14 +258,14 @@ class NAMGetButtonControl : public NAMSquareButtonControl
public:
NAMGetButtonControl(const IRECT& bounds, const char* label, const char* url, const ISVG& globeSVG)
: NAMSquareButtonControl(
bounds,
[url](IControl* pCaller) {
WDL_String fullURL(url);
auto* ui = pCaller->GetUI();
ui->ReleaseMouseCapture();
ui->OpenURL(fullURL.Get());
},
globeSVG)
bounds,
[url](IControl* pCaller) {
WDL_String fullURL(url);
auto* ui = pCaller->GetUI();
ui->ReleaseMouseCapture();
ui->OpenURL(fullURL.Get());
},
globeSVG)
{
SetTooltip(label);
}
Expand Down Expand Up @@ -604,7 +604,7 @@ class NAMMeterControl : public IVPeakAvgMeterControl<Channels>, public IBitmapBa
public:
NAMMeterControl(const IRECT& bounds, const IBitmap& bitmap, const IVStyle& style)
: IVPeakAvgMeterControl<Channels>(bounds, "", style.WithShowValue(false).WithDrawFrame(false).WithWidgetFrac(0.8),
EDirection::Vertical, {}, 0, KMeterMin, KMeterMax, {})
EDirection::Vertical, {}, 0, KMeterMin, KMeterMax, {})
, IBitmapBase(bitmap)
{
this->SetPeakSize(1.0f);
Expand Down Expand Up @@ -656,7 +656,7 @@ class IContainerBaseWithNamedChildren : public IContainerBase
{
public:
IContainerBaseWithNamedChildren(const IRECT& bounds)
: IContainerBase(bounds) {};
: IContainerBase(bounds){};
~IContainerBaseWithNamedChildren() = default;

protected:
Expand Down Expand Up @@ -698,7 +698,7 @@ class ModelInfoControl : public IContainerBaseWithNamedChildren
public:
ModelInfoControl(const IRECT& bounds, const IVStyle& style)
: IContainerBaseWithNamedChildren(bounds)
, mStyle(style) {};
, mStyle(style){};

void ClearModelInfo()
{
Expand Down Expand Up @@ -765,7 +765,7 @@ class OutputModeControl : public IVRadioButtonControl
public:
OutputModeControl(const IRECT& bounds, int paramIdx, const IVStyle& style, float buttonSize)
: IVRadioButtonControl(
bounds, paramIdx, {}, "Output Mode", style, EVShape::Ellipse, EDirection::Vertical, buttonSize) {};
bounds, paramIdx, {}, "Output Mode", style, EVShape::Ellipse, EDirection::Vertical, buttonSize){};

void SetNormalizedDisable(const bool disable)
{
Expand Down Expand Up @@ -1012,7 +1012,7 @@ class NAMSettingsPageControl : public IContainerBaseWithNamedChildren
AboutControl(const IRECT& bounds, const IVStyle& style, const IText& text)
: IContainerBase(bounds)
, mStyle(style)
, mText(text) {};
, mText(text){};

void OnAttached() override
{
Expand Down
7 changes: 3 additions & 4 deletions NeuralAmpModeler/ResamplingNAM.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ class ResamplingNAM : public nam::DSP
double samples = mEncapsulated->GetPrewarmSamples();
if (NeedToResample())
samples *= GetExpectedSampleRate() / GetEncapsulatedSampleRate();
return static_cast<int>(std::clamp(std::ceil(samples), 0.0,
static_cast<double>(std::numeric_limits<int>::max())));
return static_cast<int>(std::clamp(std::ceil(samples), 0.0, static_cast<double>(std::numeric_limits<int>::max())));
}

void process(NAM_SAMPLE** input, NAM_SAMPLE** output, const int num_frames) override
Expand All @@ -94,8 +93,8 @@ class ResamplingNAM : public nam::DSP
}
else
{
std::visit([&](auto& resampler) { resampler.ProcessBlock(input, output, num_frames, mBlockProcessFunc); },
mResampler);
std::visit(
[&](auto& resampler) { resampler.ProcessBlock(input, output, num_frames, mBlockProcessFunc); }, mResampler);
}
};

Expand Down
19 changes: 12 additions & 7 deletions NeuralAmpModeler/Unserialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,21 @@ void NeuralAmpModeler::_UnserializeApplyConfig(nlohmann::json& config)
OnParamReset(iplug::EParamSource::kPresetRecall);
LEAVE_PARAMS_MUTEX

mNAMPath.Set(static_cast<std::string>(config["NAMPath"]).c_str());
mCabPath.Set(static_cast<std::string>(config["IRPath"]).c_str());
const WDL_String modelPath(static_cast<std::string>(config["NAMPath"]).c_str());
const WDL_String cabPath(static_cast<std::string>(config["IRPath"]).c_str());
{
const std::lock_guard lock(mDSPStagingMutex);
mNAMPath = modelPath;
mCabPath = cabPath;
}

if (mNAMPath.GetLength())
if (modelPath.GetLength())
{
_StageModel(mNAMPath);
_StageModel(modelPath);
}
if (mCabPath.GetLength())
if (cabPath.GetLength())
{
_StageCab(mCabPath);
_StageCab(cabPath);
}
}

Expand Down Expand Up @@ -206,7 +211,7 @@ class _Version
_Version(const int major, const int minor, const int patch)
: mMajor(major)
, mMinor(minor)
, mPatch(patch) {};
, mPatch(patch){};
_Version(const std::string& versionStr)
{
std::istringstream stream(versionStr);
Expand Down
3 changes: 2 additions & 1 deletion tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ add_test(NAME cabinet_model COMMAND test_cabinet_model)
set(NAM_VST3_SDK_ROOT "" CACHE PATH "Steinberg VST3 SDK checkout for plugin integration tests")
set(NAM_VST3_TEST_PLUGIN "" CACHE PATH "Built NeuralAmpModeler.vst3 bundle to test")
if(NAM_VST3_SDK_ROOT AND NAM_VST3_TEST_PLUGIN)
find_package(Threads REQUIRED)
if(APPLE)
enable_language(OBJCXX)
endif()
Expand All @@ -53,7 +54,7 @@ if(NAM_VST3_SDK_ROOT AND NAM_VST3_TEST_PLUGIN)
# Match the SDK validator: its Windows loader expects u8string() to return std::string.
set_target_properties(test_stereo_plugin PROPERTIES CXX_STANDARD 17 CXX_STANDARD_REQUIRED YES)
target_include_directories(test_stereo_plugin PRIVATE "${CORE_ROOT}/Dependencies/nlohmann")
target_link_libraries(test_stereo_plugin PRIVATE sdk_hosting)
target_link_libraries(test_stereo_plugin PRIVATE sdk_hosting Threads::Threads)
if(APPLE)
set(MODULE_SOURCE "${NAM_VST3_SDK_ROOT}/public.sdk/source/vst/hosting/module_mac.mm")
set_source_files_properties("${MODULE_SOURCE}" PROPERTIES COMPILE_FLAGS "-fobjc-arc")
Expand Down
7 changes: 2 additions & 5 deletions tests/test_resampling_nam.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,7 @@ class RateTrackingDSP : public nam::DSP

bool SupportsArbitrarySampleRate() override { return mAdaptive; }

int GetPrewarmSamples() override
{
return mAdaptive ? static_cast<int>(std::ceil(0.1 * mProcessingRate)) : 4801;
}
int GetPrewarmSamples() override { return mAdaptive ? static_cast<int>(std::ceil(0.1 * mProcessingRate)) : 4801; }

void Reset(double sampleRate, int maxBlockSize) override
{
Expand Down Expand Up @@ -108,7 +105,7 @@ void test_reset_rates_and_metadata()
require(wrapped.GetEncapsulatedSampleRate() == 48000.0, "Wrapper lost the training sample rate");
require((wrapped.GetLatency() == 0) == (adaptive || hostRate == 48000.0), "Incorrect resampling latency");
const int expectedHistory = adaptive ? static_cast<int>(std::ceil(0.1 * hostRate))
: static_cast<int>(std::ceil(4801.0 * hostRate / 48000.0));
: static_cast<int>(std::ceil(4801.0 * hostRate / 48000.0));
require(wrapped.GetPrewarmSamples() == expectedHistory, "History length was not reported in host-rate samples");
render([&](auto** in, auto** out, int frames) { wrapped.process(in, out, frames); });
}
Expand Down
90 changes: 88 additions & 2 deletions tests/test_stereo_plugin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@

#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <future>
#include <initializer_list>
#include <iostream>
#include <stdexcept>
Expand Down Expand Up @@ -126,6 +128,13 @@ class HostedPlugin
}

void load(const std::string& model, const std::string& cab, bool cabEnabled = true, bool gateAndEQ = false)
{
auto state = makeState(model, cab, cabEnabled, gateAndEQ);
loadState(state);
}

std::vector<char> makeState(const std::string& model, const std::string& cab, bool cabEnabled = true,
bool gateAndEQ = false)
{
MemoryStream saved;
require(mComponent->getState(&saved) == kResultOk, "Could not read plugin state");
Expand Down Expand Up @@ -171,6 +180,11 @@ class HostedPlugin
param(3, 3);
param(4, 8);
state.insert(state.end(), params.begin(), params.end());
return state;
}

void loadState(std::vector<char>& state)
{
MemoryStream stream(state.data(), state.size());
require(mComponent->setState(&stream) == kResultOk, "Could not restore plugin state");
}
Expand Down Expand Up @@ -410,6 +424,77 @@ void test_routing(const VST3::Hosting::PluginFactory& factory, const VST3::Hosti
std::cout << cases << " routing cases plus gate/EQ, replacement, long IR, and resampling checks passed\n";
}

void test_cab_switching_during_playback(const VST3::Hosting::PluginFactory& factory,
const VST3::Hosting::ClassInfo& info)
{
constexpr double rate = 48000.0;
Fixtures files;
const auto amp = files.nam("switch-amp.nam", {{0.5}, {-0.25}}, rate);
const auto mono = files.nam("switch-mono.nam", {{0.75}}, rate);
const auto stereo = files.wav("switch-stereo.wav", {{0.5}, {-0.5}}, rate);
HostedPlugin plugin(factory, info, rate, 2);
plugin.load(amp, mono);
// Only replace the cabinet during playback. The stereo amp stays active.
std::array<std::vector<char>, 2> states{plugin.makeState("", mono), plugin.makeState("", stereo)};
const Audio input{{0.25, -0.25, 0.25, -0.25}};
const std::array<std::array<double, 2>, 2> cabGains{{{0.375, -0.1875}, {0.0625, -0.0625}}};
const std::array<double, 2> outputGains{1.0, std::pow(10.0, -18.0 / 20.0)};
const double highPassAlpha = 1.0 / (1.0 + 2.0 * std::acos(-1.0) * 5.0 / rate);
std::array<double, 2> previousInput{}, previousOutput{};
auto renderCab = [&]() {
const auto output = plugin.render(input, {4});
// Each block must match one whole cabinet, including the WAV output gain.
for (size_t cab = 0; cab < cabGains.size(); ++cab)
{
auto lastInput = previousInput, lastOutput = previousOutput;
bool matches = true;
for (size_t ch = 0; ch < output.size(); ++ch)
for (size_t i = 0; i < output[ch].size(); ++i)
{
const double sample = cabGains[cab][ch] * input[0][i];
lastOutput[ch] = highPassAlpha * (lastOutput[ch] + sample - lastInput[ch]);
lastInput[ch] = sample;
matches &= std::abs(output[ch][i] - outputGains[cab] * lastOutput[ch]) < 2.0e-6;
}
if (matches)
{
previousInput = lastInput;
previousOutput = lastOutput;
return cab;
}
}
throw std::runtime_error("Playback received a mismatched cabinet");
};
require(renderCab() == 0, "Playback did not start with the mono cabinet");

std::atomic<bool> finished{false};
std::promise<void> started;
auto playback = std::async(std::launch::async, [&]() {
started.set_value();
std::array<bool, 2> heard{};
while (!finished.load())
heard[renderCab()] = true;
require(heard[0] && heard[1], "Playback did not render both cabinet widths during switching");
});
started.get_future().wait();
try
{
// Keep the audio callback running while the host repeatedly loads new state.
for (int i = 0; i < 2000; ++i)
plugin.loadState(states[i % states.size()]);
}
catch (...)
{
finished = true;
playback.wait();
throw;
}
finished = true;
playback.get();
require(renderCab() == 1, "Playback did not adopt the final stereo cabinet");
std::cout << "Mono and stereo cabinet switches kept both channels coherent during playback\n";
}

void test_large_host_blocks(const VST3::Hosting::PluginFactory& factory, const VST3::Hosting::ClassInfo& info)
{
constexpr int largeBlockSize = 5000;
Expand All @@ -433,8 +518,8 @@ void test_large_host_blocks(const VST3::Hosting::PluginFactory& factory, const V
const auto expected = small.render(input);
const auto actual = large.render(input, {largeBlockSize});
for (const auto& channel : expected)
require(std::any_of(channel.end() - finalBlockSize, channel.end(),
[](double value) { return std::abs(value) > 1.0e-4; }),
require(std::any_of(
channel.end() - finalBlockSize, channel.end(), [](double value) { return std::abs(value) > 1.0e-4; }),
"Large-block fixture produced no signal in the final block");
compare(actual, expected);
require(large.latency() == small.latency(), "Large host blocks changed latency");
Expand All @@ -459,6 +544,7 @@ int main(int argc, char** argv)
if (info.category() == kVstAudioEffectClass)
{
test_routing(module->getFactory(), info);
test_cab_switching_during_playback(module->getFactory(), info);
test_large_host_blocks(module->getFactory(), info);
tested = true;
}
Expand Down
Loading