diff --git a/.github/workflows/build-native.yml b/.github/workflows/build-native.yml index d2c3d6ce5..e2c5cb729 100644 --- a/.github/workflows/build-native.yml +++ b/.github/workflows/build-native.yml @@ -17,6 +17,7 @@ jobs: name: Build-native-plugins runs-on: ${{matrix.os}} strategy: + fail-fast: false matrix: os: [macos-latest, windows-latest] include: @@ -103,6 +104,21 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } shell: pwsh + - name: Run CTest suite + run: | + $sdk = Join-Path $env:RUNNER_TEMP "vst3sdk" + if ($env:RUNNER_OS -eq 'Windows') { + $bundle = Join-Path $env:GITHUB_WORKSPACE "NeuralAmpModeler/build-win/NeuralAmpModeler.vst3" + } else { + $bundle = Join-Path $HOME "Library/Audio/Plug-Ins/VST3/NeuralAmpModeler.vst3" + } + cmake -S tests -B build-tests -DCMAKE_BUILD_TYPE=Release "-DNAM_VST3_SDK_ROOT=$sdk" "-DNAM_VST3_TEST_PLUGIN=$bundle" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + cmake --build build-tests --config Release --parallel 2 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + ctest --test-dir build-tests -C Release --output-on-failure --no-tests=error + shell: pwsh + - name: Upload artifact uses: actions/upload-artifact@v4 with: diff --git a/AudioDSPTools b/AudioDSPTools index e19ef4b5b..95cd88d5f 160000 --- a/AudioDSPTools +++ b/AudioDSPTools @@ -1 +1 @@ -Subproject commit e19ef4b5b3bf2171c431847563acde29eedf85c0 +Subproject commit 95cd88d5fbb31e5470298659b10e6948c46ff001 diff --git a/NeuralAmpModeler/NeuralAmpModeler.cpp b/NeuralAmpModeler/NeuralAmpModeler.cpp index 5c1436fd6..77a69a200 100644 --- a/NeuralAmpModeler/NeuralAmpModeler.cpp +++ b/NeuralAmpModeler/NeuralAmpModeler.cpp @@ -98,6 +98,7 @@ NeuralAmpModeler::NeuralAmpModeler(const InstanceInfo& info) GetParam(kSlim)->InitDouble("Slim", 0.0, 0.0, 1.0, 0.01); mNoiseGateTrigger.AddListener(&mNoiseGateGain); + mNoiseGateTrigger.AddListener(&mNoiseGateGainRight); mMakeGraphicsFunc = [&]() { @@ -279,8 +280,8 @@ NeuralAmpModeler::NeuralAmpModeler(const InstanceInfo& info) 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); + pGraphics->AttachControl(new NAMMeterControl<1>(inputMeterArea, meterBackgroundBitmap, style), kCtrlTagInputMeter); + pGraphics->AttachControl(new NAMMeterControl<2>(outputMeterArea, meterBackgroundBitmap, style), kCtrlTagOutputMeter); // Settings/help/about box pGraphics->AttachControl(new NAMCircleButtonControl( @@ -313,16 +314,31 @@ NeuralAmpModeler::NeuralAmpModeler(const InstanceInfo& info) }; } -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; + _ApplyDSPStaging(); + + // The host buses have at most two channels. Offset each channel within the host block. + std::array chunkInputs{}, chunkOutputs{}; + for (int offset = 0; offset < nFrames;) + { + const int chunkFrames = std::min(nFrames - offset, kMaxInternalBlockSize); + for (size_t ch = 0; ch < numChannelsExternalIn; ++ch) + chunkInputs[ch] = inputs[ch] + offset; + for (size_t ch = 0; ch < numChannelsExternalOut; ++ch) + chunkOutputs[ch] = outputs[ch] + offset; + + _ProcessBlock(chunkInputs.data(), chunkOutputs.data(), chunkFrames, numChannelsExternalIn, numChannelsExternalOut); + offset += chunkFrames; + } +} + +void NeuralAmpModeler::_ProcessBlock(iplug::sample** inputs, iplug::sample** outputs, int nFrames, + size_t numChannelsExternalIn, size_t numChannelsExternalOut) +{ + const size_t numModelOutputs = mModel != nullptr ? mModel->NumOutputChannels() : 1; const size_t numFrames = (size_t)nFrames; const double sampleRate = GetSampleRate(); @@ -331,15 +347,14 @@ void NeuralAmpModeler::ProcessBlock(iplug::sample** inputs, iplug::sample** outp 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(); + _ProcessInput(inputs, numFrames, numChannelsExternalIn); + sample* modelInput[]{mInputBuffer.data()}; + sample* modelOutput[]{mModelOutput[0].data(), mModelOutput[1].data()}; const bool noiseGateActive = GetParam(kNoiseGateActive)->Value(); const bool toneStackActive = GetParam(kEQActive)->Value(); // Noise gate trigger - sample** triggerOutput = mInputPointers; + sample** triggerOutput = modelInput; if (noiseGateActive) { const double time = 0.01; @@ -351,65 +366,81 @@ void NeuralAmpModeler::ProcessBlock(iplug::sample** inputs, iplug::sample** outp const dsp::noise_gate::TriggerParams triggerParams(time, threshold, ratio, openTime, holdTime, closeTime); mNoiseGateTrigger.SetParams(triggerParams); mNoiseGateTrigger.SetSampleRate(sampleRate); - triggerOutput = mNoiseGateTrigger.Process(mInputPointers, numChannelsInternal, numFrames); + triggerOutput = mNoiseGateTrigger.Process(modelInput, 1, numFrames); } if (mModel != nullptr) { - mModel->process(triggerOutput, mOutputPointers, nFrames); + mModel->process(triggerOutput, modelOutput, nFrames); } else { - _FallbackDSP(triggerOutput, mOutputPointers, numChannelsInternal, numFrames); + _FallbackDSP(triggerOutput, modelOutput, 1, numFrames); // Fallback is mono-mono + } + // Apply the same input-triggered gate envelope to both amp output channels. + sample* gateGainPointers[]{modelOutput[0], modelOutput[1]}; + if (noiseGateActive) + { + gateGainPointers[0] = mNoiseGateGain.Process(modelOutput, 1, numFrames)[0]; + if (numModelOutputs == 2) + gateGainPointers[1] = mNoiseGateGainRight.Process(modelOutput + 1, 1, numFrames)[0]; } - // Apply the noise gate after the NAM - sample** gateGainOutput = - noiseGateActive ? mNoiseGateGain.Process(mOutputPointers, numChannelsInternal, numFrames) : mOutputPointers; sample** toneStackOutPointers = (toneStackActive && mToneStack != nullptr) - ? mToneStack->Process(gateGainOutput, numChannelsInternal, nFrames) - : gateGainOutput; + ? mToneStack->Process(gateGainPointers, numModelOutputs, nFrames) + : gateGainPointers; + size_t numOutputChannels = numModelOutputs; sample** cabPointers = toneStackOutPointers; - sample* cabinetOutputPointers[]{mCabinetOutput.data()}; + sample* cabinetOutputPointers[]{mCabinetOutput[0].data(), mCabinetOutput[1].data()}; if (mCab != nullptr && GetParam(kCabToggle)->Bool()) { - mCab->process(toneStackOutPointers, cabinetOutputPointers, nFrames); + if (mCab->NumOutputChannels() == 2) + { + sample* cabInputPointers[]{toneStackOutPointers[0]}; + if (numModelOutputs == 2) + { + for (size_t i = 0; i < numFrames; ++i) + mCabinetInput[i] = 0.5 * (toneStackOutPointers[0][i] + toneStackOutPointers[1][i]); + cabInputPointers[0] = mCabinetInput.data(); + } + mCab->process(cabInputPointers, cabinetOutputPointers, nFrames); + numOutputChannels = 2; + } + else + { + // Mono cabs process stereo amp outputs independently, preserving L/R. + mCab->process(toneStackOutPointers, cabinetOutputPointers, nFrames); + if (numModelOutputs == 2) + mCabRight->process(toneStackOutPointers + 1, cabinetOutputPointers + 1, nFrames); + } cabPointers = cabinetOutputPointers; } // 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(cabPointers, numChannelsInternal, numFrames); - // sample** lpfPointers = mLowPass.Process(hpfPointers, numChannelsInternal, numFrames); + sample** hpfPointers = mHighPass.Process(cabPointers, numOutputChannels, 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); + // Adapt the internal mono/stereo result to the host output bus. + _ProcessOutput(hpfPointers, outputs, numFrames, numOutputChannels, numChannelsExternalOut); + _UpdateMeters(modelInput, outputs, numFrames, numChannelsExternalOut); } void NeuralAmpModeler::OnReset() { const auto sampleRate = GetSampleRate(); - const int maxBlockSize = GetBlockSize(); mInputSender.Reset(sampleRate); mOutputSender.Reset(sampleRate); // If there is a model or cab loaded, they need to be checked for resampling. - _ResetModelAndCab(sampleRate, GetBlockSize()); - mToneStack->Reset(sampleRate, maxBlockSize); + _ResetModelAndCab(sampleRate); + mToneStack->Reset(sampleRate, kMaxInternalBlockSize); _UpdateLatencyAndTail(); } @@ -580,20 +611,6 @@ bool NeuralAmpModeler::OnMessage(int msgTag, int ctrlTag, int dataSize, const vo // 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 @@ -610,6 +627,7 @@ void NeuralAmpModeler::_ApplyDSPStaging() if (mShouldRemoveCab) { mCab = nullptr; + mCabRight = nullptr; mCabIsWav = false; mCabPath.Set(""); mShouldRemoveCab = false; @@ -629,6 +647,7 @@ void NeuralAmpModeler::_ApplyDSPStaging() if (mStagedCab != nullptr) { mCab = std::move(mStagedCab); + mCabRight = std::move(mStagedCabRight); mCabIsWav = mStagedCabIsWav; mStagedCab = nullptr; _UpdateLatencyAndTail(); @@ -636,49 +655,39 @@ void NeuralAmpModeler::_ApplyDSPStaging() } } -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]; + outputs[c][s] = inputs[c][s]; } -void NeuralAmpModeler::_ResetModelAndCab(const double sampleRate, const int maxBlockSize) +void NeuralAmpModeler::_ResetModelAndCab(const double sampleRate) { // Model if (mStagedModel != nullptr) { - mStagedModel->Reset(sampleRate, maxBlockSize); + mStagedModel->Reset(sampleRate, kMaxInternalBlockSize); } else if (mModel != nullptr) { - mModel->Reset(sampleRate, maxBlockSize); + mModel->Reset(sampleRate, kMaxInternalBlockSize); } // Core retains the original model data and handles coefficient resampling on Reset. if (mStagedCab != nullptr) - mStagedCab->Reset(sampleRate, maxBlockSize); + { + mStagedCab->Reset(sampleRate, kMaxInternalBlockSize); + if (mStagedCabRight != nullptr) + mStagedCabRight->Reset(sampleRate, kMaxInternalBlockSize); + } else if (mCab != nullptr) - mCab->Reset(sampleRate, maxBlockSize); + { + mCab->Reset(sampleRate, kMaxInternalBlockSize); + if (mCabRight != nullptr) + mCabRight->Reset(sampleRate, kMaxInternalBlockSize); + } } void NeuralAmpModeler::_SetInputGain() @@ -751,19 +760,19 @@ std::string NeuralAmpModeler::_StageModel(const WDL_String& modelPath) auto dspPath = std::filesystem::u8path(modelPath.Get()); std::unique_ptr model = nam::get_dsp(dspPath); - // Check that the model has 1 input and 1 output channel + // Support mono-input models with mono or stereo output. if (model->NumInputChannels() != 1) { throw std::runtime_error("Model must have 1 input channel, but has " + std::to_string(model->NumInputChannels())); } - if (model->NumOutputChannels() != 1) + if (model->NumOutputChannels() < 1 || model->NumOutputChannels() > 2) { - throw std::runtime_error("Model must have 1 output channel, but has " + throw std::runtime_error("Model must have 1 or 2 output channels, but has " + std::to_string(model->NumOutputChannels())); } std::unique_ptr temp = std::make_unique(std::move(model), GetSampleRate()); - temp->Reset(GetSampleRate(), GetBlockSize()); + temp->Reset(GetSampleRate(), kMaxInternalBlockSize); if (nam::SlimmableModel* slimmable = temp->GetSlimmableModel()) { slimmable->SetSlimmableSize(GetParam(kSlim)->Value()); @@ -794,15 +803,25 @@ std::string NeuralAmpModeler::_StageCab(const WDL_String& cabPath) { // Finish loading before publishing the model, so a failed load preserves the current cab and path. const auto path = std::filesystem::u8path(cabPath.Get()); - auto model = nam::get_dsp(path); - if (model->NumInputChannels() != 1 || model->NumOutputChannels() != 1) - throw std::runtime_error("Cab model must have 1 input and 1 output channel."); + nam::dspData config; + 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(), GetBlockSize()); + cab->Reset(GetSampleRate(), kMaxInternalBlockSize); + std::unique_ptr right; + if (cab->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); + } 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()); @@ -816,109 +835,47 @@ std::string NeuralAmpModeler::_StageCab(const WDL_String& cabPath) return ""; } -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::_InitToneStack() { // If you want to customize the tone stack, then put it here! mToneStack = std::make_unique(); } -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) - { - mCabinetOutput.resize(numFrames); - 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) +void NeuralAmpModeler::_ProcessInput(iplug::sample** inputs, const size_t nFrames, const size_t nChansIn) { - _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 nChansIn 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. (This would change w/ double mono processing) double gain = mInputGain; #ifndef APP_API - gain /= (float)nChansIn; + if (nChansIn > 0) + gain /= static_cast(nChansIn); #endif - // Assume _PrepareBuffers() was already called + // Also handle a disconnected input without replaying the previous block. + std::fill_n(mInputBuffer.data(), nFrames, 0.0); 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]; + mInputBuffer[s] = gain * inputs[c][s]; else - mInputArray[0][s] += gain * inputs[c][s]; + mInputBuffer[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 = mOutputGain; - // 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++) + for (size_t cout = 0; cout < nChansOut; ++cout) + for (size_t s = 0; s < nFrames; ++s) + { + const double signal = + nChansOut == 1 && nChansIn == 2 ? 0.5 * (inputs[0][s] + inputs[1][s]) : inputs[cout % nChansIn][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]; + outputs[cout][s] = std::clamp(gain * signal, -1.0, 1.0); +#else + outputs[cout][s] = gain * signal; #endif + } } void NeuralAmpModeler::_UpdateControlsFromModel() @@ -981,12 +938,15 @@ void NeuralAmpModeler::_UpdateLatencyAndTail() } void NeuralAmpModeler::_UpdateMeters(sample** inputPointer, sample** outputPointer, const size_t nFrames, - const size_t nChansIn, const size_t nChansOut) + 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); + mInputSender.ProcessBlock(inputPointer, (int)nFrames, kCtrlTagInputMeter, 1); + if (nChansOut > 0) + { + // Mirror the host's mono output on both bars. + sample* meterOutput[]{outputPointer[0], outputPointer[nChansOut == 1 ? 0 : 1]}; + mOutputSender.ProcessBlock(meterOutput, (int)nFrames, kCtrlTagOutputMeter); + } } // HACK diff --git a/NeuralAmpModeler/NeuralAmpModeler.h b/NeuralAmpModeler/NeuralAmpModeler.h index 90a10b4de..8b5c71f04 100644 --- a/NeuralAmpModeler/NeuralAmpModeler.h +++ b/NeuralAmpModeler/NeuralAmpModeler.h @@ -1,5 +1,7 @@ #pragma once +#include + #include "../AudioDSPTools/dsp/NoiseGate.h" #include "../AudioDSPTools/dsp/dsp.h" #include "ResamplingNAM.h" @@ -12,14 +14,15 @@ const int kNumPresets = 1; -// The plugin is mono inside -constexpr size_t kNumChannelsInternal = 1; +// Both slots take mono input and may produce mono or stereo output. +constexpr size_t kMaxNumChannelsInternal = 2; -class NAMSender : public iplug::IPeakAvgSender<> +template +class NAMSender : public iplug::IPeakAvgSender { public: NAMSender() - : iplug::IPeakAvgSender<>(-90.0, true, 5.0f, 1.0f, 300.0f, 500.0f) + : iplug::IPeakAvgSender(-90.0, true, 5.0f, 1.0f, 300.0f, 500.0f) { } }; @@ -81,7 +84,6 @@ class NeuralAmpModeler final : public iplug::Plugin { public: NeuralAmpModeler(const iplug::InstanceInfo& info); - ~NeuralAmpModeler(); void ProcessBlock(iplug::sample** inputs, iplug::sample** outputs, int nFrames) override; void OnReset() override; @@ -97,20 +99,15 @@ class NeuralAmpModeler final : public iplug::Plugin bool OnMessage(int msgTag, int ctrlTag, int dataSize, const void* pData) override; private: - // Allocates mInputPointers and mOutputPointers - void _AllocateIOPointers(const size_t nChans); + 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. void _ApplyDSPStaging(); - // Deallocates mInputPointers and mOutputPointers - void _DeallocateIOPointers(); // 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); - // Sizes based on mInputArray - size_t _GetBufferNumChannels() const; - size_t _GetBufferNumFrames() const; void _InitToneStack(); // Loads a NAM model and stores it to mStagedNAM // Returns an empty string on success, or an error message on failure. @@ -120,21 +117,17 @@ class NeuralAmpModeler final : public iplug::Plugin std::string _StageCab(const WDL_String& cabPath); bool _HaveModel() const { return this->mModel != nullptr; }; - // Prepare the input & output buffers - void _PrepareBuffers(const size_t numChannels, const size_t numFrames); - // Manage pointers - void _PrepareIOPointers(const size_t nChans); - // Copy the input buffer to the object, applying input level. - // :param nChansIn: In from external - // :param nChansOut: Out to the internal of the DSP routine - void _ProcessInput(iplug::sample** inputs, const size_t nFrames, const size_t nChansIn, const size_t nChansOut); + 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. + void _ProcessInput(iplug::sample** inputs, const size_t nFrames, const size_t nChansIn); // Copy the output to the output buffer, applying output level. // :param nChansIn: In from internal // :param nChansOut: Out to external void _ProcessOutput(iplug::sample** inputs, iplug::sample** outputs, const size_t nFrames, const size_t nChansIn, const size_t nChansOut); // Resetting for the model and cab, called by OnReset - void _ResetModelAndCab(const double sampleRate, const int maxBlockSize); + void _ResetModelAndCab(const double sampleRate); void _SetInputGain(); void _SetOutputGain(); @@ -157,35 +150,36 @@ class NeuralAmpModeler final : public iplug::Plugin // Called within ProcessBlock(). // Assume _ProcessInput() and _ProcessOutput() were run immediately before. void _UpdateMeters(iplug::sample** inputPointer, iplug::sample** outputPointer, const size_t nFrames, - const size_t nChansIn, const size_t nChansOut); + const size_t nChansOut); // Member data - // Input arrays to NAM - std::vector> mInputArray; - // Output from NAM - std::vector> mOutputArray; + using SampleBuffer = std::array; + SampleBuffer mInputBuffer{}; + std::array mModelOutput{}; // Separate cab output avoids requiring NAM architectures to support in-place processing. - std::vector mCabinetOutput; - // Pointer versions - iplug::sample** mInputPointers = nullptr; - iplug::sample** mOutputPointers = nullptr; + std::array mCabinetOutput{}; + SampleBuffer mCabinetInput{}; // Input and output gain double mInputGain = 1.0; double mOutputGain = 1.0; // Noise gates - dsp::noise_gate::Trigger mNoiseGateTrigger; - dsp::noise_gate::Gain mNoiseGateGain; + 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. // 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. 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; @@ -199,7 +193,6 @@ class NeuralAmpModeler final : public iplug::Plugin // Post-cab filters recursive_linear_filter::HighPass mHighPass; - // recursive_linear_filter::LowPass mLowPass; // Path to model's config.json or model.nam WDL_String mNAMPath; @@ -210,5 +203,6 @@ class NeuralAmpModeler final : public iplug::Plugin std::unordered_map mNAMParams = {{"Input", 0.0}, {"Output", 0.0}}; - NAMSender mInputSender, mOutputSender; + NAMSender<1> mInputSender; + NAMSender<2> mOutputSender; }; diff --git a/NeuralAmpModeler/NeuralAmpModelerControls.h b/NeuralAmpModeler/NeuralAmpModelerControls.h index f48401c3e..c7e8a5166 100644 --- a/NeuralAmpModeler/NeuralAmpModelerControls.h +++ b/NeuralAmpModeler/NeuralAmpModelerControls.h @@ -595,43 +595,59 @@ class NAMFileBrowserControl : public IDirBrowseControlBase NAMGetButtonControl* mGetButton = nullptr; }; -class NAMMeterControl : public IVPeakAvgMeterControl<>, public IBitmapBase +template +class NAMMeterControl : public IVPeakAvgMeterControl, public IBitmapBase { static constexpr float KMeterMin = -70.0f; static constexpr float KMeterMax = -0.01f; 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, {}) + : IVPeakAvgMeterControl(bounds, "", style.WithShowValue(false).WithDrawFrame(false).WithWidgetFrac(0.8), + EDirection::Vertical, {}, 0, KMeterMin, KMeterMax, {}) , IBitmapBase(bitmap) { - SetPeakSize(1.0f); + this->SetPeakSize(1.0f); } - void OnRescale() override { mBitmap = GetUI()->GetScaledBitmap(mBitmap); } + void OnRescale() override { mBitmap = this->GetUI()->GetScaledBitmap(mBitmap); } - virtual void OnResize() override + void OnResize() override { - SetTargetRECT(MakeRects(mRECT)); - mWidgetBounds = mWidgetBounds.GetMidHPadded(5).GetVPadded(10); - MakeTrackRects(mWidgetBounds); - MakeStepRects(mWidgetBounds, mNSteps); - SetDirty(false); + this->SetTargetRECT(this->MakeRects(this->mRECT)); + this->mWidgetBounds = this->mWidgetBounds.GetMidHPadded(5.0f).GetVPadded(10); + this->MakeTrackRects(this->mWidgetBounds); + this->MakeStepRects(this->mWidgetBounds, this->mNSteps); + this->SetDirty(false); } void DrawBackground(IGraphics& g, const IRECT& r) override { g.DrawFittedBitmap(mBitmap, r); } + void DrawWidget(IGraphics& g) override + { + if constexpr (Channels == 2) + { + // Draw equal levels together so fractional UI scaling can't leave a seam. + if (this->GetValue(0) == this->GetValue(1)) + { + this->DrawTrack(g, this->mWidgetBounds, 0); + return; + } + } + IVPeakAvgMeterControl::DrawWidget(g); + } + void DrawTrackHandle(IGraphics& g, const IRECT& r, int chIdx, bool aboveBaseValue) override { if (r.H() > 2) - g.FillRect(GetColor(kX1), r, &mBlend); + g.FillRect(this->GetColor(kX1), r, &this->mBlend); } void DrawPeak(IGraphics& g, const IRECT& r, int chIdx, bool aboveBaseValue) override { - g.DrawGrid(COLOR_BLACK, mTrackBounds.Get()[chIdx], 10, 2); - g.FillRect(GetColor(kX3), r, &mBlend); + const IRECT track(r.L, this->mWidgetBounds.T, r.R, this->mWidgetBounds.B); + g.DrawGrid(COLOR_BLACK, track, 10, 2); + g.FillRect(this->GetColor(kX3), r, &this->mBlend); } }; diff --git a/NeuralAmpModeler/ResamplingNAM.h b/NeuralAmpModeler/ResamplingNAM.h index 196ee066a..242d2deaf 100644 --- a/NeuralAmpModeler/ResamplingNAM.h +++ b/NeuralAmpModeler/ResamplingNAM.h @@ -7,6 +7,7 @@ #include #include #include +#include #include "../iPlug2/IPlug/IPlugConstants.h" @@ -43,14 +44,10 @@ class ResamplingNAM : public nam::DSP : nam::DSP(encapsulated->NumInputChannels(), encapsulated->NumOutputChannels(), expected_sample_rate) , mEncapsulated(std::move(encapsulated)) , mSupportsArbitrarySampleRate(mEncapsulated->SupportsArbitrarySampleRate()) - , mResampler(GetNAMSampleRate(mEncapsulated)) + , mResampler(MakeResampler(NumInputChannels(), NumOutputChannels(), GetEncapsulatedSampleRate())) + , mBlockProcessFunc( + [this](NAM_SAMPLE** input, NAM_SAMPLE** output, int frames) { mEncapsulated->process(input, output, frames); }) { - // Assign the encapsulated object's processing function to this object's member so that the resampler can use it: - auto ProcessBlockFunc = [&](NAM_SAMPLE** input, NAM_SAMPLE** output, int numFrames) { - mEncapsulated->process(input, output, numFrames); - }; - mBlockProcessFunc = ProcessBlockFunc; - // Get the other information from the encapsulated NAM so that we can tell the outside world about what we're // holding. if (mEncapsulated->HasLoudness()) @@ -97,11 +94,17 @@ class ResamplingNAM : public nam::DSP } else { - mResampler.ProcessBlock(input, output, num_frames, mBlockProcessFunc); + std::visit([&](auto& resampler) { resampler.ProcessBlock(input, output, num_frames, mBlockProcessFunc); }, + mResampler); } }; - int GetLatency() const { return NeedToResample() ? mResampler.GetLatency() : 0; }; + int GetLatency() const + { + if (!NeedToResample()) + return 0; + return std::visit([](const auto& resampler) { return resampler.GetLatency(); }, mResampler); + }; void Reset(const double sampleRate, const int maxBlockSize) override { @@ -113,7 +116,7 @@ class ResamplingNAM : public nam::DSP int maxEncapsulatedBlockSize = maxBlockSize; if (NeedToResample()) { - mResampler.Reset(sampleRate, maxBlockSize); + std::visit([&](auto& resampler) { resampler.Reset(sampleRate, maxBlockSize); }, mResampler); maxEncapsulatedBlockSize = static_cast(std::ceil(static_cast(maxBlockSize) * modelSampleRate / sampleRate)); } @@ -130,6 +133,26 @@ class ResamplingNAM : public nam::DSP } private: + template + using ChannelResampler = dsp::ResamplingContainer; + using Resampler = + std::variant, ChannelResampler<1, 2>, ChannelResampler<2, 1>, ChannelResampler<2, 2>>; + + static Resampler MakeResampler(int inputs, int outputs, double sampleRate) + { + if (inputs > 2 || outputs > 2) + throw std::runtime_error("ResamplingNAM supports at most two input and output channels."); + if (inputs == 1) + { + if (outputs == 1) + return Resampler(std::in_place_type>, sampleRate); + return Resampler(std::in_place_type>, sampleRate); + } + if (outputs == 1) + return Resampler(std::in_place_type>, sampleRate); + return Resampler(std::in_place_type>, sampleRate); + } + bool NeedToResample() const { return !mSupportsArbitrarySampleRate && GetExpectedSampleRate() != GetEncapsulatedSampleRate(); @@ -137,13 +160,9 @@ class ResamplingNAM : public nam::DSP // The encapsulated NAM std::unique_ptr mEncapsulated; const bool mSupportsArbitrarySampleRate; - - // The resampling wrapper - dsp::ResamplingContainer mResampler; + Resampler mResampler; + std::function mBlockProcessFunc; // Used to check that we don't get too large a block to process. int mMaxExternalBlockSize = 0; - - // This function is defined to conform to the interface expected by the iPlug2 resampler. - std::function mBlockProcessFunc; }; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index a0c8b0beb..8fdc18b51 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -33,3 +33,36 @@ target_compile_definitions(test_cabinet_model PRIVATE NAM_TEST_MODELS_DIR="${COR add_test(NAME resampling_nam COMMAND test_resampling_nam) add_test(NAME cabinet_model COMMAND test_cabinet_model) + +# Optional integration tests against a built plugin. The default tests still +# require no plugin SDK; supply a complete Steinberg SDK checkout to enable this. +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) + if(APPLE) + enable_language(OBJCXX) + endif() + set(SMTG_ENABLE_VST3_PLUGIN_EXAMPLES OFF CACHE BOOL "" FORCE) + set(SMTG_ENABLE_VST3_HOSTING_EXAMPLES OFF CACHE BOOL "" FORCE) + set(SMTG_ENABLE_VSTGUI_SUPPORT OFF CACHE BOOL "" FORCE) + add_subdirectory("${NAM_VST3_SDK_ROOT}" "${CMAKE_CURRENT_BINARY_DIR}/vst3sdk" EXCLUDE_FROM_ALL) + add_executable(test_stereo_plugin test_stereo_plugin.cpp + "${NAM_VST3_SDK_ROOT}/public.sdk/source/vst/hosting/plugprovider.cpp" + "${NAM_VST3_SDK_ROOT}/public.sdk/source/common/memorystream.cpp" + ) + # 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) + 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") + target_link_libraries(test_stereo_plugin PRIVATE "-framework Cocoa") + elseif(WIN32) + set(MODULE_SOURCE "${NAM_VST3_SDK_ROOT}/public.sdk/source/vst/hosting/module_win32.cpp") + else() + set(MODULE_SOURCE "${NAM_VST3_SDK_ROOT}/public.sdk/source/vst/hosting/module_linux.cpp") + endif() + target_sources(test_stereo_plugin PRIVATE "${MODULE_SOURCE}") + add_test(NAME stereo_plugin COMMAND test_stereo_plugin "${NAM_VST3_TEST_PLUGIN}") +endif() diff --git a/tests/test_resampling_nam.cpp b/tests/test_resampling_nam.cpp index 67522a9f3..4644c2105 100644 --- a/tests/test_resampling_nam.cpp +++ b/tests/test_resampling_nam.cpp @@ -165,6 +165,52 @@ void test_fixed_rate_sequential_audio() require_matching_audio(actual, expected); } } + +class StereoDSP : public nam::DSP +{ +public: + StereoDSP() + : nam::DSP(1, 2, 48000.0) + { + } + + void process(NAM_SAMPLE** input, NAM_SAMPLE** output, int frames) override + { + for (int i = 0; i < frames; ++i) + { + output[0][i] = 0.5 * input[0][i]; + output[1][i] = -0.25 * input[0][i]; + } + } +}; + +void test_mono_to_stereo_resampling() +{ + ResamplingNAM wrapped(std::make_unique(), 48000.0); + for (const double rate : {48000.0, 44100.0, 96000.0, 48000.0}) + { + wrapped.Reset(rate, 256); + std::vector input(4096), left(4096), right(4096, 123.0); + for (size_t i = 0; i < input.size(); ++i) + input[i] = 0.2 * std::sin(0.071 * i); + for (size_t offset = 0; offset < input.size();) + { + const int frames = std::min(137, input.size() - offset); + NAM_SAMPLE* in[]{input.data() + offset}; + NAM_SAMPLE* out[]{left.data() + offset, right.data() + offset}; + wrapped.process(in, out, frames); + offset += frames; + } + double energy = 0.0; + for (size_t i = 0; i < input.size(); ++i) + { + require(std::isfinite(right[i]) && std::abs(right[i] + 0.5 * left[i]) < 1.0e-6, + "Stereo channels were lost or mixed during resampling"); + energy += left[i] * left[i]; + } + require(energy > 1.0, "Stereo model produced no audio"); + } +} } // namespace int main() @@ -174,6 +220,7 @@ int main() test_reset_rates_and_metadata(); test_native_linear_audio(); test_fixed_rate_sequential_audio(); + test_mono_to_stereo_resampling(); std::cout << "Sample-rate integration tests passed\n"; } catch (const std::exception& error) diff --git a/tests/test_stereo_plugin.cpp b/tests/test_stereo_plugin.cpp new file mode 100644 index 000000000..b45775b00 --- /dev/null +++ b/tests/test_stereo_plugin.cpp @@ -0,0 +1,472 @@ +// Integration coverage against a built VST3, including its saved-state loading path. +#include "public.sdk/source/vst/hosting/module.h" +#include "public.sdk/source/vst/hosting/plugprovider.h" +#include "public.sdk/source/vst/hosting/hostclasses.h" +#include "public.sdk/source/common/memorystream.h" +#include "pluginterfaces/vst/ivstaudioprocessor.h" +#include "pluginterfaces/vst/ivstcomponent.h" +#include "pluginterfaces/vst/ivsteditcontroller.h" +#include "pluginterfaces/vst/vstspeaker.h" +#include "json.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Steinberg; +using namespace Steinberg::Vst; +namespace +{ +using Audio = std::vector>; +void require(bool condition, const char* message) +{ + if (!condition) + throw std::runtime_error(message); +} + +struct Fixtures +{ + std::filesystem::path directory = + std::filesystem::temp_directory_path() + / ("nam-stereo-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + Fixtures() { std::filesystem::create_directories(directory); } + ~Fixtures() { std::filesystem::remove_all(directory); } + + std::string nam(const char* name, const Audio& kernels, double rate, bool fixedRate = false) + { + std::vector weights; + for (const auto& kernel : kernels) + weights.insert(weights.end(), kernel.begin(), kernel.end()); + nlohmann::json model{ + {"version", "0.7.0"}, + {"architecture", "Linear"}, + {"sample_rate", rate}, + {"config", + {{"in_channels", 1}, {"out_channels", kernels.size()}, {"receptive_field", kernels[0].size()}, {"bias", false}}}, + {"weights", weights}}; + if (fixedRate) + model = {{"version", "0.7.0"}, + {"architecture", "Sequential"}, + {"sample_rate", rate}, + {"config", {{"models", nlohmann::json::array({model})}}}, + {"weights", nlohmann::json::array()}}; + const auto path = directory / name; + std::ofstream(path) << model; + return path.string(); + } + + std::string wav(const char* name, const Audio& kernels, int rate) + { + const auto path = directory / name; + std::ofstream file(path, std::ios::binary); + auto integer = [&](uint32_t n, int bytes) { + for (int i = 0; i < bytes; ++i) + file.put(static_cast((n >> (8 * i)) & 255)); + }; + const auto bytes = 4 * kernels.size() * kernels[0].size(); + file.write("RIFF", 4); + integer(36 + bytes, 4); + file.write("WAVEfmt ", 8); + integer(16, 4); + integer(3, 2); + integer(kernels.size(), 2); + integer(rate, 4); + integer(rate * kernels.size() * 4, 4); + integer(kernels.size() * 4, 2); + integer(32, 2); + file.write("data", 4); + integer(bytes, 4); + for (size_t i = 0; i < kernels[0].size(); ++i) + for (const auto& kernel : kernels) + { + const float sample = kernel[i]; + uint32_t bits; + std::memcpy(&bits, &sample, 4); + integer(bits, 4); + } + return path.string(); + } +}; + +class HostedPlugin +{ +public: + HostedPlugin(const VST3::Hosting::PluginFactory& factory, const VST3::Hosting::ClassInfo& info, double rate, + int outputs, int inputs = 1, int maxBlockSize = 256) + : mOutputs(outputs) + , mInputs(inputs) + { + mProvider = owned(new PlugProvider(factory, info, true)); + require(mProvider->initialize(), "Plugin initialization failed"); + mComponent = mProvider->getComponentPtr(); + mProcessor = mComponent; + SpeakerArrangement in = inputs == 1 ? SpeakerArr::kMono : SpeakerArr::kStereo; + SpeakerArrangement out = outputs == 1 ? SpeakerArr::kMono : SpeakerArr::kStereo; + require(mProcessor->setBusArrangements(&in, 1, &out, 1) == kResultOk, "Bus arrangement rejected"); + ProcessSetup setup{kRealtime, kSample64, maxBlockSize, rate}; + require(mProcessor->setupProcessing(setup) == kResultOk, "Processing setup failed"); + mComponent->activateBus(kAudio, kInput, 0, true); + mComponent->activateBus(kAudio, kOutput, 0, true); + mComponent->setActive(true); + mProcessor->setProcessing(true); + } + ~HostedPlugin() + { + mProcessor->setProcessing(false); + mComponent->setActive(false); + } + + void load(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"); + auto* data = static_cast(saved.getData()); + size_t pos = 0; + auto readString = [&]() { + require(pos + 4 <= size_t(saved.getSize()), "Invalid saved-state header"); + int n; + std::memcpy(&n, data + pos, 4); + pos += 4; + require(n >= 0 && pos + n <= size_t(saved.getSize()), "Invalid saved-state string"); + std::string s(data + pos, n); + pos += n; + return s; + }; + const auto header = readString(), version = readString(); + readString(); + readString(); + std::vector state; + auto putString = [&](const std::string& s) { + const int n = s.size(); + const auto* p = reinterpret_cast(&n); + state.insert(state.end(), p, p + 4); + state.insert(state.end(), s.begin(), s.end()); + }; + putString(header); + putString(version); + putString(model); + putString(cab); + std::vector params(data + pos, data + saved.getSize()); + // Saved parameter order is part of the plugin's session compatibility contract. + auto param = [&](int index, double value) { + require((index + 1) * sizeof(double) <= params.size(), "Missing saved parameter"); + std::memcpy(params.data() + index * sizeof(double), &value, sizeof(double)); + }; + param(0, 0); + param(5, 0); + param(6, gateAndEQ); + param(7, gateAndEQ); + param(8, cabEnabled); + param(11, 0); // cab toggle and raw output mode + param(2, 7); + param(3, 3); + param(4, 8); + state.insert(state.end(), params.begin(), params.end()); + MemoryStream stream(state.data(), state.size()); + require(mComponent->setState(&stream) == kResultOk, "Could not restore plugin state"); + } + + Audio render(const Audio& input, std::initializer_list blockSizes = {1, 7, 127, 256, 31}) + { + Audio output(mOutputs, std::vector(input[0].size(), 123.0)); + for (size_t offset = 0, block = 0; offset < input[0].size(); ++block) + { + const int count = std::min(blockSizes.begin()[block % blockSizes.size()], input[0].size() - offset); + std::array in{}, out{}; + for (int ch = 0; ch < mInputs; ++ch) + in[ch] = const_cast(input[ch].data() + offset); + for (int ch = 0; ch < mOutputs; ++ch) + out[ch] = output[ch].data() + offset; + AudioBusBuffers ib{}, ob{}; + ib.numChannels = mInputs; + ob.numChannels = mOutputs; + ib.channelBuffers64 = in.data(); + ob.channelBuffers64 = out.data(); + ProcessData process{}; + process.processMode = kRealtime; + process.symbolicSampleSize = kSample64; + process.numSamples = count; + process.numInputs = process.numOutputs = 1; + process.inputs = &ib; + process.outputs = &ob; + require(mProcessor->process(process) == kResultOk, "Plugin processing failed"); + offset += count; + } + return output; + } + + uint32 tail() const { return mProcessor->getTailSamples(); } + uint32 latency() const { return mProcessor->getLatencySamples(); } + +private: + IPtr mProvider; + IPtr mComponent; + FUnknownPtr mProcessor; + int mOutputs, mInputs; +}; + +std::vector convolve(const std::vector& input, const std::vector& kernel) +{ + std::vector output(input.size(), 0.0); + for (size_t i = 0; i < input.size(); ++i) + for (size_t k = 0; k < kernel.size() && k <= i; ++k) + output[i] += input[i - k] * kernel[k]; + return output; +} + +Audio expected_audio(const std::vector& input, const Audio& amp, const Audio& cab, int outputs, double rate, + double gain) +{ + Audio signal; + if (amp.empty()) + signal = {input}; + else + for (const auto& kernel : amp) + signal.push_back(convolve(input, kernel)); + if (!cab.empty()) + { + Audio filtered; + if (cab.size() == 2) + { + auto mono = signal[0]; + if (signal.size() == 2) + for (size_t i = 0; i < mono.size(); ++i) + mono[i] = 0.5 * (signal[0][i] + signal[1][i]); + for (const auto& kernel : cab) + filtered.push_back(convolve(mono, kernel)); + } + else + for (const auto& channel : signal) + filtered.push_back(convolve(channel, cab[0])); + signal = std::move(filtered); + } + const double alpha = 1.0 / (1.0 + 2.0 * std::acos(-1.0) * 5.0 / rate); + for (auto& channel : signal) + { + double previousInput = 0.0, previousOutput = 0.0; + for (auto& value : channel) + { + const double next = alpha * (previousOutput + value - previousInput); + previousInput = value; + previousOutput = next; + value = gain * next; + } + } + if (outputs == 1 && signal.size() == 2) + { + for (size_t i = 0; i < signal[0].size(); ++i) + signal[0][i] = 0.5 * (signal[0][i] + signal[1][i]); + signal.resize(1); + } + if (outputs == 2 && signal.size() == 1) + signal.push_back(signal[0]); + return signal; +} + +void compare(const Audio& actual, const Audio& expected) +{ + require(actual.size() == expected.size(), "Wrong output channel count"); + for (size_t ch = 0; ch < actual.size(); ++ch) + for (size_t i = 0; i < actual[ch].size(); ++i) + if (!std::isfinite(actual[ch][i]) || std::abs(actual[ch][i] - expected[ch][i]) > 2.0e-6) + { + std::cerr << "Mismatch: channel " << ch << ", sample " << i << ": " << actual[ch][i] << " expected " + << expected[ch][i] << '\n'; + throw std::runtime_error("Stereo routing changed the expected audio"); + } +} + +void test_routing(const VST3::Hosting::PluginFactory& factory, const VST3::Hosting::ClassInfo& info) +{ + Fixtures files; + const Audio monoAmp{{0.5, 0.0, 0.125, 0.0}}; + const Audio stereoAmp{monoAmp[0], {0.0, -0.25, 0.0, 0.0625}}; + const Audio monoCab{{0.75, 0.0, -0.125, 0.0}}; + const Audio stereoCab{monoCab[0], {0.0, 0.0, 0.125, 0.0}}; + std::vector input(1024); + input[0] = 1.0; + input[113] = -0.25; + input[479] = 0.125; + int cases = 0; + for (const double rate : {44100.0, 48000.0, 96000.0}) + { + const std::vector