diff --git a/NeuralAmpModeler/NeuralAmpModeler.cpp b/NeuralAmpModeler/NeuralAmpModeler.cpp index 77a69a200..de941ae9a 100644 --- a/NeuralAmpModeler/NeuralAmpModeler.cpp +++ b/NeuralAmpModeler/NeuralAmpModeler.cpp @@ -188,7 +188,6 @@ NeuralAmpModeler::NeuralAmpModeler(const InstanceInfo& info) 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 cab loader. if (msg.size()) @@ -281,7 +280,8 @@ NeuralAmpModeler::NeuralAmpModeler(const InstanceInfo& info) // The meters pGraphics->AttachControl(new NAMMeterControl<1>(inputMeterArea, meterBackgroundBitmap, style), kCtrlTagInputMeter); - pGraphics->AttachControl(new NAMMeterControl<2>(outputMeterArea, meterBackgroundBitmap, style), kCtrlTagOutputMeter); + pGraphics->AttachControl( + new NAMMeterControl<2>(outputMeterArea, meterBackgroundBitmap, style), kCtrlTagOutputMeter); // Settings/help/about box pGraphics->AttachControl(new NAMCircleButtonControl( @@ -336,7 +336,7 @@ void NeuralAmpModeler::ProcessBlock(iplug::sample** inputs, iplug::sample** outp } void NeuralAmpModeler::_ProcessBlock(iplug::sample** inputs, iplug::sample** outputs, int nFrames, - size_t numChannelsExternalIn, size_t numChannelsExternalOut) + size_t numChannelsExternalIn, size_t numChannelsExternalOut) { const size_t numModelOutputs = mModel != nullptr ? mModel->NumOutputChannels() : 1; const size_t numFrames = (size_t)nFrames; @@ -393,9 +393,9 @@ void NeuralAmpModeler::_ProcessBlock(iplug::sample** inputs, iplug::sample** out size_t numOutputChannels = numModelOutputs; sample** cabPointers = toneStackOutPointers; sample* cabinetOutputPointers[]{mCabinetOutput[0].data(), mCabinetOutput[1].data()}; - if (mCab != nullptr && GetParam(kCabToggle)->Bool()) + if (mCab.model != nullptr && mCabEnabled) { - if (mCab->NumOutputChannels() == 2) + if (mCab.model->NumOutputChannels() == 2) { sample* cabInputPointers[]{toneStackOutPointers[0]}; if (numModelOutputs == 2) @@ -404,15 +404,15 @@ void NeuralAmpModeler::_ProcessBlock(iplug::sample** inputs, iplug::sample** out mCabinetInput[i] = 0.5 * (toneStackOutPointers[0][i] + toneStackOutPointers[1][i]); cabInputPointers[0] = mCabinetInput.data(); } - mCab->process(cabInputPointers, cabinetOutputPointers, nFrames); + mCab.model->process(cabInputPointers, cabinetOutputPointers, nFrames); numOutputChannels = 2; } else { // Mono cabs process stereo amp outputs independently, preserving L/R. - mCab->process(toneStackOutPointers, cabinetOutputPointers, nFrames); + mCab.model->process(toneStackOutPointers, cabinetOutputPointers, nFrames); if (numModelOutputs == 2) - mCabRight->process(toneStackOutPointers + 1, cabinetOutputPointers + 1, nFrames); + mCab.right->process(toneStackOutPointers + 1, cabinetOutputPointers + 1, nFrames); } cabPointers = cabinetOutputPointers; } @@ -441,6 +441,7 @@ void NeuralAmpModeler::OnReset() // If there is a model or cab loaded, they need to be checked for resampling. _ResetModelAndCab(sampleRate); mToneStack->Reset(sampleRate, kMaxInternalBlockSize); + mCabEnabled = GetParam(kCabToggle)->Bool(); _UpdateLatencyAndTail(); } @@ -448,6 +449,7 @@ void NeuralAmpModeler::OnIdle() { mInputSender.TransmitData(*this); mOutputSender.TransmitData(*this); + _ApplySlimParamToLoadedNAMs(); if (mNewModelLoadedInDSP) { @@ -486,8 +488,11 @@ bool NeuralAmpModeler::SerializeState(IByteChunk& chunk) const chunk.PutStr(version.Get()); // Model directory (don't serialize the model itself; we'll just load it again // when we unserialize) - chunk.PutStr(mNAMPath.Get()); - chunk.PutStr(mCabPath.Get()); + { + const std::lock_guard lock(mDSPStagingMutex); + chunk.PutStr(mNAMPath.Get()); + chunk.PutStr(mCabPath.Get()); + } return SerializeParams(chunk); } @@ -513,47 +518,50 @@ void NeuralAmpModeler::OnUIOpen() { Plugin::OnUIOpen(); - if (mNAMPath.GetLength()) + WDL_String modelPath, cabPath; + bool modelLoaded, cabLoaded; + { + const std::lock_guard lock(mDSPStagingMutex); + modelPath = mNAMPath; + cabPath = mCabPath; + modelLoaded = mModel != nullptr || mStagedModel != nullptr; + cabLoaded = mCab.model != nullptr || mStagedCab.model != nullptr; + } + if (modelPath.GetLength()) { - SendControlMsgFromDelegate(kCtrlTagModelFileBrowser, kMsgTagLoadedModel, mNAMPath.GetLength(), mNAMPath.Get()); + SendControlMsgFromDelegate(kCtrlTagModelFileBrowser, kMsgTagLoadedModel, modelPath.GetLength(), modelPath.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) + if (!modelLoaded) SendControlMsgFromDelegate(kCtrlTagModelFileBrowser, kMsgTagLoadFailed); } - if (mCabPath.GetLength()) + if (cabPath.GetLength()) { - SendControlMsgFromDelegate(kCtrlTagCabFileBrowser, kMsgTagLoadedCab, mCabPath.GetLength(), mCabPath.Get()); - if (mCab == nullptr && mStagedCab == nullptr) + SendControlMsgFromDelegate(kCtrlTagCabFileBrowser, kMsgTagLoadedCab, cabPath.GetLength(), cabPath.Get()); + if (!cabLoaded) SendControlMsgFromDelegate(kCtrlTagCabFileBrowser, kMsgTagLoadFailed); } - if (mModel != nullptr) - { - _UpdateControlsFromModel(); - } + _UpdateControlsFromModel(); } void NeuralAmpModeler::OnParamChange(int paramIdx) { switch (paramIdx) { - // Changes to the input gain case kCalibrateInput: case kInputCalibrationLevel: - case kInputLevel: _SetInputGain(); break; - // Changes to the output gain + case kInputLevel: case kOutputLevel: - case kOutputMode: _SetOutputGain(); break; - // Tone stack: - case kToneBass: mToneStack->SetParam("bass", GetParam(paramIdx)->Value()); break; - case kToneMid: mToneStack->SetParam("middle", GetParam(paramIdx)->Value()); break; - case kToneTreble: mToneStack->SetParam("treble", GetParam(paramIdx)->Value()); break; - case kSlim: _ApplySlimParamToLoadedNAMs(); break; - case kCabToggle: - _SetOutputGain(); - _UpdateLatencyAndTail(); + case kOutputMode: + case kCabToggle: mDSPGainsAndTimingDirty = true; break; + case kToneBass: + case kToneMid: + case kToneTreble: mToneStackDirty = true; break; + case kSlim: + mSlimDirty = true; + _ApplySlimParamToLoadedNAMs(); break; default: break; } @@ -581,8 +589,24 @@ bool NeuralAmpModeler::OnMessage(int msgTag, int ctrlTag, int dataSize, const vo { switch (msgTag) { - case kMsgTagClearModel: mShouldRemoveModel = true; return true; - case kMsgTagClearCab: mShouldRemoveCab = true; return true; + case kMsgTagClearModel: + { + std::unique_ptr superseded; + const std::lock_guard lock(mDSPStagingMutex); + superseded = std::move(mStagedModel); + mNAMPath.Set(""); + mShouldRemoveModel = true; + return true; + } + case kMsgTagClearCab: + { + Cabinet superseded; + const std::lock_guard lock(mDSPStagingMutex); + superseded = std::exchange(mStagedCab, {}); + mCabPath.Set(""); + mShouldRemoveCab = true; + return true; + } case kMsgTagHighlightColor: { mHighLightColor.Set((const char*)pData); @@ -613,45 +637,46 @@ bool NeuralAmpModeler::OnMessage(int msgTag, int ctrlTag, int dataSize, const vo void NeuralAmpModeler::_ApplyDSPStaging() { - // Remove marked modules - if (mShouldRemoveModel) + std::unique_ptr retiredModel; + Cabinet retiredCab; + bool modelChanged = false, cabChanged = false; { - mModel = nullptr; - mNAMPath.Set(""); - mShouldRemoveModel = false; - mModelCleared = true; - _UpdateLatencyAndTail(); - _SetInputGain(); - _SetOutputGain(); + // The audio thread keeps using the current modules if a publisher holds the lock. + const std::unique_lock lock(mDSPStagingMutex, std::try_to_lock); + if (lock.owns_lock()) + { + // A staged replacement takes precedence over an earlier clear request. + if (mStagedModel != nullptr || mShouldRemoveModel) + { + retiredModel = std::exchange(mModel, std::move(mStagedModel)); + mShouldRemoveModel = false; + mNewModelLoadedInDSP = mModel != nullptr; + mModelCleared = mModel == nullptr; + modelChanged = true; + } + if (mStagedCab.model != nullptr || mShouldRemoveCab) + { + std::swap(retiredCab, mCab); + mCab = std::exchange(mStagedCab, {}); + mShouldRemoveCab = false; + cabChanged = true; + } + } } - if (mShouldRemoveCab) + + // State recall and host automation can arrive off the audio thread. + if (mToneStackDirty.exchange(false)) { - mCab = nullptr; - mCabRight = nullptr; - mCabIsWav = false; - mCabPath.Set(""); - mShouldRemoveCab = false; - _UpdateLatencyAndTail(); - _SetOutputGain(); + mToneStack->SetParam("bass", GetParam(kToneBass)->Value()); + mToneStack->SetParam("middle", GetParam(kToneMid)->Value()); + mToneStack->SetParam("treble", GetParam(kToneTreble)->Value()); } - // Move things from staged to live - if (mStagedModel != nullptr) + if (mDSPGainsAndTimingDirty.exchange(false) || modelChanged || cabChanged) { - mModel = std::move(mStagedModel); - mStagedModel = nullptr; - mNewModelLoadedInDSP = true; - _UpdateLatencyAndTail(); + mCabEnabled = GetParam(kCabToggle)->Bool(); _SetInputGain(); _SetOutputGain(); - } - if (mStagedCab != nullptr) - { - mCab = std::move(mStagedCab); - mCabRight = std::move(mStagedCabRight); - mCabIsWav = mStagedCabIsWav; - mStagedCab = nullptr; _UpdateLatencyAndTail(); - _SetOutputGain(); } } @@ -663,31 +688,25 @@ void NeuralAmpModeler::_FallbackDSP(iplug::sample** inputs, iplug::sample** outp outputs[c][s] = inputs[c][s]; } +void NeuralAmpModeler::Cabinet::Reset(double sampleRate) +{ + if (model != nullptr) + model->Reset(sampleRate, kMaxInternalBlockSize); + if (right != nullptr) + right->Reset(sampleRate, kMaxInternalBlockSize); +} + void NeuralAmpModeler::_ResetModelAndCab(const double sampleRate) { - // Model + const std::lock_guard lock(mDSPStagingMutex); + mDSPStagingSampleRate = sampleRate; + // The active module may still render if the pending handoff is delayed. + if (mModel != nullptr) + mModel->Reset(sampleRate, kMaxInternalBlockSize); if (mStagedModel != nullptr) - { mStagedModel->Reset(sampleRate, kMaxInternalBlockSize); - } - else if (mModel != nullptr) - { - mModel->Reset(sampleRate, kMaxInternalBlockSize); - } - - // Core retains the original model data and handles coefficient resampling on Reset. - if (mStagedCab != nullptr) - { - mStagedCab->Reset(sampleRate, kMaxInternalBlockSize); - if (mStagedCabRight != nullptr) - mStagedCabRight->Reset(sampleRate, kMaxInternalBlockSize); - } - else if (mCab != nullptr) - { - mCab->Reset(sampleRate, kMaxInternalBlockSize); - if (mCabRight != nullptr) - mCabRight->Reset(sampleRate, kMaxInternalBlockSize); - } + mCab.Reset(sampleRate); + mStagedCab.Reset(sampleRate); } void NeuralAmpModeler::_SetInputGain() @@ -729,17 +748,23 @@ void NeuralAmpModeler::_SetOutputGain() default: break; } } - if (mCab != nullptr && mCabIsWav && GetParam(kCabToggle)->Bool()) + if (mCab.model != nullptr && mCab.isWav && mCabEnabled) { // Core compensates by sourceRate / hostRate when resampling IR coefficients. // This remaining factor preserves the legacy -18 dB * 48000 / hostRate level. - gainDB += -18.0 + 20.0 * std::log10(48000.0 / mCab->GetEncapsulatedSampleRate()); + gainDB += -18.0 + 20.0 * std::log10(48000.0 / mCab.model->GetEncapsulatedSampleRate()); } mOutputGain = DBToAmp(gainDB); } void NeuralAmpModeler::_ApplySlimParamToLoadedNAMs() { + if (!mSlimDirty) + return; + const std::unique_lock lock(mDSPStagingMutex, std::try_to_lock); + if (!lock.owns_lock() || !mSlimDirty.exchange(false)) + return; + const double v = GetParam(kSlim)->Value(); auto apply = [v](ResamplingNAM* p) { if (p == nullptr) @@ -749,12 +774,11 @@ void NeuralAmpModeler::_ApplySlimParamToLoadedNAMs() }; apply(mModel.get()); apply(mStagedModel.get()); - _UpdateLatencyAndTail(); + mDSPGainsAndTimingDirty = true; } std::string NeuralAmpModeler::_StageModel(const WDL_String& modelPath) { - WDL_String previousNAMPath = mNAMPath; try { auto dspPath = std::filesystem::u8path(modelPath.Get()); @@ -771,25 +795,29 @@ std::string NeuralAmpModeler::_StageModel(const WDL_String& modelPath) + std::to_string(model->NumOutputChannels())); } - std::unique_ptr temp = std::make_unique(std::move(model), GetSampleRate()); - temp->Reset(GetSampleRate(), kMaxInternalBlockSize); - if (nam::SlimmableModel* slimmable = temp->GetSlimmableModel()) + const double sampleRate = mDSPStagingSampleRate.load(); + auto staged = std::make_unique(std::move(model), sampleRate); + auto* slimmable = staged->GetSlimmableModel(); + const double slim = GetParam(kSlim)->Value(); + if (slimmable != nullptr) + slimmable->SetSlimmableSize(slim); + { - slimmable->SetSlimmableSize(GetParam(kSlim)->Value()); + const std::lock_guard lock(mDSPStagingMutex); + const double currentRate = mDSPStagingSampleRate.load(); + if (currentRate != sampleRate) + staged->Reset(currentRate, kMaxInternalBlockSize); + const double currentSlim = GetParam(kSlim)->Value(); + if (slimmable != nullptr && currentSlim != slim) + slimmable->SetSlimmableSize(currentSlim); + mNAMPath = modelPath; + std::swap(mStagedModel, staged); } - mStagedModel = std::move(temp); - mNAMPath = modelPath; - SendControlMsgFromDelegate(kCtrlTagModelFileBrowser, kMsgTagLoadedModel, mNAMPath.GetLength(), mNAMPath.Get()); + SendControlMsgFromDelegate(kCtrlTagModelFileBrowser, kMsgTagLoadedModel, modelPath.GetLength(), modelPath.Get()); } - catch (std::runtime_error& e) + catch (const 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(); @@ -807,24 +835,30 @@ std::string NeuralAmpModeler::_StageCab(const WDL_String& cabPath) auto model = nam::get_dsp(path, config); if (model->NumInputChannels() != 1 || model->NumOutputChannels() < 1 || model->NumOutputChannels() > 2) throw std::runtime_error("Cab model must have 1 input and 1 or 2 output channels."); - auto cab = std::make_unique(std::move(model), GetSampleRate()); - cab->Reset(GetSampleRate(), kMaxInternalBlockSize); - std::unique_ptr right; - if (cab->NumOutputChannels() == 1) + + const double sampleRate = mDSPStagingSampleRate.load(); + Cabinet staged; + staged.model = std::make_unique(std::move(model), sampleRate); + if (staged.model->NumOutputChannels() == 1) { // Use the same decoded data so both instances match even if the file changes. // Prepare the right instance here so changing amp width needs no model loading in ProcessBlock. - right = std::make_unique(nam::get_dsp(config), GetSampleRate()); - right->Reset(GetSampleRate(), kMaxInternalBlockSize); + staged.right = std::make_unique(nam::get_dsp(config), sampleRate); } auto extension = path.extension().string(); std::transform(extension.begin(), extension.end(), extension.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); - mStagedCabIsWav = extension == ".wav"; - mStagedCabRight = std::move(right); - mStagedCab = std::move(cab); - mCabPath = cabPath; - SendControlMsgFromDelegate(kCtrlTagCabFileBrowser, kMsgTagLoadedCab, mCabPath.GetLength(), mCabPath.Get()); + staged.isWav = extension == ".wav"; + + { + const std::lock_guard lock(mDSPStagingMutex); + const double currentRate = mDSPStagingSampleRate.load(); + if (currentRate != sampleRate) + staged.Reset(currentRate); + mCabPath = cabPath; + std::swap(mStagedCab, staged); + } + SendControlMsgFromDelegate(kCtrlTagCabFileBrowser, kMsgTagLoadedCab, cabPath.GetLength(), cabPath.Get()); } catch (const std::exception& error) { @@ -880,36 +914,37 @@ void NeuralAmpModeler::_ProcessOutput(iplug::sample** inputs, iplug::sample** ou void NeuralAmpModeler::_UpdateControlsFromModel() { - if (mModel == nullptr) - { - return; - } if (auto* pGraphics = GetUI()) { ModelInfo modelInfo; - modelInfo.sampleRate.known = true; - modelInfo.sampleRate.value = mModel->GetEncapsulatedSampleRate(); - modelInfo.inputCalibrationLevel.known = mModel->HasInputLevel(); - modelInfo.inputCalibrationLevel.value = mModel->HasInputLevel() ? mModel->GetInputLevel() : 0.0; - modelInfo.outputCalibrationLevel.known = mModel->HasOutputLevel(); - modelInfo.outputCalibrationLevel.value = mModel->HasOutputLevel() ? mModel->GetOutputLevel() : 0.0; + bool slimmable, hasLoudness; + { + const std::lock_guard lock(mDSPStagingMutex); + if (mModel == nullptr) + return; + modelInfo.sampleRate.known = true; + modelInfo.sampleRate.value = mModel->GetEncapsulatedSampleRate(); + modelInfo.inputCalibrationLevel.known = mModel->HasInputLevel(); + modelInfo.inputCalibrationLevel.value = mModel->HasInputLevel() ? mModel->GetInputLevel() : 0.0; + modelInfo.outputCalibrationLevel.known = mModel->HasOutputLevel(); + modelInfo.outputCalibrationLevel.value = mModel->HasOutputLevel() ? mModel->GetOutputLevel() : 0.0; + slimmable = mModel->GetSlimmableModel() != nullptr; + hasLoudness = mModel->HasLoudness(); + } static_cast(pGraphics->GetControlWithTag(kCtrlTagSettingsBox))->SetModelInfo(modelInfo); - const bool disableInputCalibrationControls = !mModel->HasInputLevel(); + const bool disableInputCalibrationControls = !modelInfo.inputCalibrationLevel.known; pGraphics->GetControlWithTag(kCtrlTagCalibrateInput)->SetDisabled(disableInputCalibrationControls); pGraphics->GetControlWithTag(kCtrlTagInputCalibrationLevel)->SetDisabled(disableInputCalibrationControls); { auto* c = static_cast(pGraphics->GetControlWithTag(kCtrlTagOutputMode)); - c->SetNormalizedDisable(!mModel->HasLoudness()); - c->SetCalibratedDisable(!mModel->HasOutputLevel()); + c->SetNormalizedDisable(!hasLoudness); + c->SetCalibratedDisable(!modelInfo.outputCalibrationLevel.known); } if (auto* pSlimIcon = pGraphics->GetControlWithTag(kCtrlTagSlimmableIcon)) - { - const bool show = mModel->GetSlimmableModel() != nullptr; - pSlimIcon->Hide(!show); - } + pSlimIcon->Hide(!slimmable); } } @@ -920,14 +955,14 @@ void NeuralAmpModeler::_UpdateLatencyAndTail() { latency += mModel->GetLatency(); } - const bool cabActive = mCab != nullptr && GetParam(kCabToggle)->Bool(); + const bool cabActive = mCab.model != nullptr && mCabEnabled; if (cabActive) - latency += mCab->GetLatency(); + latency += mCab.model->GetLatency(); // Both wrappers report their models' history lengths in host-rate samples. // Allow another two seconds (ten cycles at 5 Hz) for the DC blocker. const double tail = 2.0 * GetSampleRate() + (mModel ? mModel->GetPrewarmSamples() : 0) - + (cabActive ? mCab->GetPrewarmSamples() : 0); + + (cabActive ? mCab.model->GetPrewarmSamples() : 0); SetTailSize(static_cast(std::min(tail, static_cast(std::numeric_limits::max())))); // Feels weird to have to do this. diff --git a/NeuralAmpModeler/NeuralAmpModeler.h b/NeuralAmpModeler/NeuralAmpModeler.h index 8b5c71f04..ec464b0b7 100644 --- a/NeuralAmpModeler/NeuralAmpModeler.h +++ b/NeuralAmpModeler/NeuralAmpModeler.h @@ -1,6 +1,8 @@ #pragma once #include +#include +#include #include "../AudioDSPTools/dsp/NoiseGate.h" #include "../AudioDSPTools/dsp/dsp.h" @@ -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. @@ -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 mModel; - // The cabinet, loaded from a WAV impulse response or NAM model. - std::unique_ptr mCab; - // Independent state for a mono cab processing the right side of a stereo amp. - std::unique_ptr mCabRight; - bool mCabIsWav = false; - // Manages switching what DSP is being used. + struct Cabinet + { + std::unique_ptr model; + // Independent state for a mono cab processing the right side of a stereo amp. + std::unique_ptr 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 mDSPStagingSampleRate{iplug::DEFAULT_SAMPLE_RATE}; std::unique_ptr mStagedModel; - std::unique_ptr mStagedCab; - std::unique_ptr mStagedCabRight; - bool mStagedCabIsWav = false; - // Flags to take away the modules at a safe time. - std::atomic mShouldRemoveModel = false; - std::atomic mShouldRemoveCab = false; + Cabinet mStagedCab; + bool mShouldRemoveModel = false; + bool mShouldRemoveCab = false; + std::atomic mDSPGainsAndTimingDirty{true}; + std::atomic mToneStackDirty{true}; + std::atomic mSlimDirty{false}; std::atomic mNewModelLoadedInDSP = false; std::atomic mModelCleared = false; @@ -203,6 +211,6 @@ class NeuralAmpModeler final : public iplug::Plugin std::unordered_map mNAMParams = {{"Input", 0.0}, {"Output", 0.0}}; - NAMSender<1> mInputSender; - NAMSender<2> mOutputSender; + NAMSender<1> mInputSender; // Mono input + NAMSender<2> mOutputSender; // Stereo output }; diff --git a/NeuralAmpModeler/NeuralAmpModelerControls.h b/NeuralAmpModeler/NeuralAmpModelerControls.h index c7e8a5166..dcd1da104 100644 --- a/NeuralAmpModeler/NeuralAmpModelerControls.h +++ b/NeuralAmpModeler/NeuralAmpModelerControls.h @@ -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); } @@ -604,7 +604,7 @@ class NAMMeterControl : public IVPeakAvgMeterControl, public IBitmapBa public: NAMMeterControl(const IRECT& bounds, const IBitmap& bitmap, const IVStyle& style) : IVPeakAvgMeterControl(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); @@ -656,7 +656,7 @@ class IContainerBaseWithNamedChildren : public IContainerBase { public: IContainerBaseWithNamedChildren(const IRECT& bounds) - : IContainerBase(bounds) {}; + : IContainerBase(bounds){}; ~IContainerBaseWithNamedChildren() = default; protected: @@ -698,7 +698,7 @@ class ModelInfoControl : public IContainerBaseWithNamedChildren public: ModelInfoControl(const IRECT& bounds, const IVStyle& style) : IContainerBaseWithNamedChildren(bounds) - , mStyle(style) {}; + , mStyle(style){}; void ClearModelInfo() { @@ -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) { @@ -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 { diff --git a/NeuralAmpModeler/ResamplingNAM.h b/NeuralAmpModeler/ResamplingNAM.h index 242d2deaf..c5cfab04e 100644 --- a/NeuralAmpModeler/ResamplingNAM.h +++ b/NeuralAmpModeler/ResamplingNAM.h @@ -78,8 +78,7 @@ class ResamplingNAM : public nam::DSP double samples = mEncapsulated->GetPrewarmSamples(); if (NeedToResample()) samples *= GetExpectedSampleRate() / GetEncapsulatedSampleRate(); - return static_cast(std::clamp(std::ceil(samples), 0.0, - static_cast(std::numeric_limits::max()))); + return static_cast(std::clamp(std::ceil(samples), 0.0, static_cast(std::numeric_limits::max()))); } void process(NAM_SAMPLE** input, NAM_SAMPLE** output, const int num_frames) override @@ -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); } }; diff --git a/NeuralAmpModeler/Unserialization.cpp b/NeuralAmpModeler/Unserialization.cpp index cd106ca48..a85e25464 100644 --- a/NeuralAmpModeler/Unserialization.cpp +++ b/NeuralAmpModeler/Unserialization.cpp @@ -54,16 +54,21 @@ void NeuralAmpModeler::_UnserializeApplyConfig(nlohmann::json& config) OnParamReset(iplug::EParamSource::kPresetRecall); LEAVE_PARAMS_MUTEX - mNAMPath.Set(static_cast(config["NAMPath"]).c_str()); - mCabPath.Set(static_cast(config["IRPath"]).c_str()); + const WDL_String modelPath(static_cast(config["NAMPath"]).c_str()); + const WDL_String cabPath(static_cast(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); } } @@ -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); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8fdc18b51..4078817ee 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -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() @@ -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") diff --git a/tests/test_resampling_nam.cpp b/tests/test_resampling_nam.cpp index 4644c2105..afaa5cf7f 100644 --- a/tests/test_resampling_nam.cpp +++ b/tests/test_resampling_nam.cpp @@ -27,10 +27,7 @@ class RateTrackingDSP : public nam::DSP bool SupportsArbitrarySampleRate() override { return mAdaptive; } - int GetPrewarmSamples() override - { - return mAdaptive ? static_cast(std::ceil(0.1 * mProcessingRate)) : 4801; - } + int GetPrewarmSamples() override { return mAdaptive ? static_cast(std::ceil(0.1 * mProcessingRate)) : 4801; } void Reset(double sampleRate, int maxBlockSize) override { @@ -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(std::ceil(0.1 * hostRate)) - : static_cast(std::ceil(4801.0 * hostRate / 48000.0)); + : static_cast(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); }); } diff --git a/tests/test_stereo_plugin.cpp b/tests/test_stereo_plugin.cpp index b45775b00..3bebd1698 100644 --- a/tests/test_stereo_plugin.cpp +++ b/tests/test_stereo_plugin.cpp @@ -11,12 +11,14 @@ #include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -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 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"); @@ -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& state) + { MemoryStream stream(state.data(), state.size()); require(mComponent->setState(&stream) == kResultOk, "Could not restore plugin state"); } @@ -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, 2> states{plugin.makeState("", mono), plugin.makeState("", stereo)}; + const Audio input{{0.25, -0.25, 0.25, -0.25}}; + const std::array, 2> cabGains{{{0.375, -0.1875}, {0.0625, -0.0625}}}; + const std::array 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 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 finished{false}; + std::promise started; + auto playback = std::async(std::launch::async, [&]() { + started.set_value(); + std::array 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; @@ -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"); @@ -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; }