From 0b6cca85015261551eb286e2d34ebc56ec2f4352 Mon Sep 17 00:00:00 2001 From: appdess Date: Mon, 3 Aug 2026 14:59:05 +0200 Subject: [PATCH 1/3] Add real-time octave transpose --- .github/workflows/macos-ci.yml | 9 +- AudioDSPTools/tests/test_au_offline.mm | 95 ++- NeuralAmpModeler/NeuralAmpModeler.cpp | 57 +- NeuralAmpModeler/NeuralAmpModeler.h | 5 + NeuralAmpModeler/NeuralAmpModelerControls.h | 64 ++ NeuralAmpModeler/TransposeProcessor.h | 450 +++++++++++++ NeuralAmpModeler/Unserialization.cpp | 49 +- NeuralAmpModeler/Unserialization.h | 41 ++ NeuralAmpModeler/config.h | 4 +- .../experiments/transpose/ErbPitchPrototype.h | 363 +++++++++++ .../transpose/HybridErbPitchPrototype.h | 161 +++++ .../experiments/transpose/README.md | 113 ++++ .../experiments/transpose/benchmark_erb.cpp | 612 ++++++++++++++++++ .../experiments/transpose/render_erb_audio.sh | 30 + .../experiments/transpose/render_erb_file.cpp | 112 ++++ .../transpose/render_reference_au.cpp | 210 ++++++ .../transpose/render_reference_au.sh | 25 + .../transpose/run_erb_benchmark.sh | 10 + NeuralAmpModeler/installer/DessMetal.iss | 4 +- NeuralAmpModeler/installer/intro.rtf | 2 +- .../DessMetal-macOS.xcodeproj/project.pbxproj | 60 +- .../resources/DessMetal-AAX-Info.plist | 6 +- .../resources/DessMetal-AU-Info.plist | 10 +- .../resources/DessMetal-VST2-Info.plist | 6 +- .../resources/DessMetal-VST3-Info.plist | 6 +- .../resources/DessMetal-macOS-AUv3-Info.plist | 8 +- .../DessMetal-macOS-AUv3Framework-Info.plist | 4 +- .../resources/DessMetal-macOS-Info.plist | 6 +- .../tests/run_transpose_processor_tests.sh | 11 + .../tests/test_au_state_migration.mm | 26 +- .../tests/test_transpose_processor.cpp | 381 +++++++++++ .../tests/test_unserialization_layout.cpp | 28 +- README.md | 7 +- THIRD_PARTY_NOTICES.md | 1 + licenses/terrarium-poly-octave-MIT.txt | 21 + package_mac.sh | 28 + 36 files changed, 2946 insertions(+), 79 deletions(-) create mode 100644 NeuralAmpModeler/TransposeProcessor.h create mode 100644 NeuralAmpModeler/experiments/transpose/ErbPitchPrototype.h create mode 100644 NeuralAmpModeler/experiments/transpose/HybridErbPitchPrototype.h create mode 100644 NeuralAmpModeler/experiments/transpose/README.md create mode 100644 NeuralAmpModeler/experiments/transpose/benchmark_erb.cpp create mode 100644 NeuralAmpModeler/experiments/transpose/render_erb_audio.sh create mode 100644 NeuralAmpModeler/experiments/transpose/render_erb_file.cpp create mode 100644 NeuralAmpModeler/experiments/transpose/render_reference_au.cpp create mode 100644 NeuralAmpModeler/experiments/transpose/render_reference_au.sh create mode 100644 NeuralAmpModeler/experiments/transpose/run_erb_benchmark.sh create mode 100755 NeuralAmpModeler/tests/run_transpose_processor_tests.sh create mode 100644 NeuralAmpModeler/tests/test_transpose_processor.cpp create mode 100644 licenses/terrarium-poly-octave-MIT.txt diff --git a/.github/workflows/macos-ci.yml b/.github/workflows/macos-ci.yml index 392763f..5259254 100644 --- a/.github/workflows/macos-ci.yml +++ b/.github/workflows/macos-ci.yml @@ -59,8 +59,10 @@ jobs: echo "- \`git archive\` SHA-256: \`$source_hash\`" } >> "$GITHUB_STEP_SUMMARY" - - name: Versioned state-layout migration tests - run: bash NeuralAmpModeler/tests/run_unserialization_layout_tests.sh + - name: Versioned state-layout and transpose DSP tests + run: | + bash NeuralAmpModeler/tests/run_unserialization_layout_tests.sh + bash NeuralAmpModeler/tests/run_transpose_processor_tests.sh - name: Python trainer security regression tests run: | @@ -89,6 +91,7 @@ jobs: AudioDSPTools/tests/run_wav_tests.sh \ AudioDSPTools/tests/run_au_offline_test.sh \ NeuralAmpModeler/tests/run_unserialization_layout_tests.sh \ + NeuralAmpModeler/tests/run_transpose_processor_tests.sh \ NeuralAmpModeler/tests/run_au_state_migration_test.sh plutil -lint NeuralAmpModeler/resources/*.plist NeuralAmpModeler/resources/DessMetal-macOS-release.entitlements version="$DESSMETAL_VERSION" @@ -174,7 +177,7 @@ jobs: mkdir -p "$dmg_mount" hdiutil attach -readonly -nobrowse -mountpoint "$dmg_mount" "$dmg" trap 'hdiutil detach "$dmg_mount" >/dev/null 2>&1 || true' EXIT - for license in RtAudio-MIT.txt RtMidi-MIT.txt nlohmann-json-MIT.txt stb-MIT.txt; do + for license in RtAudio-MIT.txt RtMidi-MIT.txt nlohmann-json-MIT.txt stb-MIT.txt terrarium-poly-octave-MIT.txt; do test -f "$dmg_mount/THIRD_PARTY_LICENSES/$license" done hdiutil detach "$dmg_mount" diff --git a/AudioDSPTools/tests/test_au_offline.mm b/AudioDSPTools/tests/test_au_offline.mm index b9b3ee8..a3c7680 100644 --- a/AudioDSPTools/tests/test_au_offline.mm +++ b/AudioDSPTools/tests/test_au_offline.mm @@ -20,6 +20,7 @@ constexpr AudioUnitParameterID kDriveModelParameter = 14; constexpr AudioUnitParameterID kAmpModelParameter = 18; constexpr AudioUnitParameterID kAmpActiveParameter = 19; +constexpr AudioUnitParameterID kTransposeParameter = 20; struct InputState { @@ -64,6 +65,23 @@ AudioStreamBasicDescription MakeFormat(const UInt32 channels) format.mBitsPerChannel = 8 * sizeof(float); return format; } + +double ToneMagnitude(const std::vector& signal, const double frequency) +{ + double real = 0.0; + double imaginary = 0.0; + double windowSum = 0.0; + for (std::size_t index = 0; index < signal.size(); ++index) + { + const double window = 0.5 - 0.5 * std::cos(2.0 * M_PI * index / (signal.size() - 1)); + const double angle = 2.0 * M_PI * frequency * index / kSampleRate; + const double sample = signal[index] * window; + real += sample * std::cos(angle); + imaginary -= sample * std::sin(angle); + windowSum += window; + } + return 2.0 * std::hypot(real, imaginary) / windowSum; +} } // namespace int main() @@ -137,7 +155,8 @@ int main() bool finite = true; UInt32 renderedBlocks = 0; const auto renderBlocks = [&](const UInt32 blockCount, double& measuredPeak, double* maxAdjacentStep = nullptr, - double* previousLeftSample = nullptr) { + double* previousLeftSample = nullptr, + std::vector* capturedLeft = nullptr) { measuredPeak = 0.0; if (maxAdjacentStep != nullptr) *maxAdjacentStep = 0.0; @@ -153,6 +172,8 @@ int main() AudioUnitRenderActionFlags flags = 0; if (!Check(AudioUnitRender(unit, &flags, ×tamp, 0, kFramesPerBlock, &output.list), "AudioUnitRender")) return false; + if (capturedLeft != nullptr) + capturedLeft->insert(capturedLeft->end(), left.begin(), left.end()); for (const float sample : left) { finite = finite && std::isfinite(sample); @@ -274,6 +295,74 @@ int main() return 1; } + // Exercise the exact installed AU's new processing path with the nonlinear + // stages bypassed. The target carrier must dominate nearby output at both + // octave extremes, automation must remain bounded, and host PDC must not + // change with the transpose value. + std::vector transposeCarrierDeficits; + double transposeMaxStep = 0.0; + if (!Check(AudioUnitSetParameter(unit, kDriveActiveParameter, kAudioUnitScope_Global, 0, 0.0f, 0), + "disable drive for transpose test")) + { + dispose(); + return 1; + } + for (const int semitones : {-12, 12}) + { + double transitionPeak = 0.0; + double transitionStep = 0.0; + std::vector captured; + captured.reserve(64 * kFramesPerBlock); + if (!Check(AudioUnitSetParameter(unit, kTransposeParameter, kAudioUnitScope_Global, 0, + static_cast(semitones), 0), + "set transpose") + || !renderBlocks(16, transitionPeak, &transitionStep, &bypassPreviousSample) + || !renderBlocks(64, transitionPeak, nullptr, nullptr, &captured)) + { + dispose(); + return 1; + } + transposeMaxStep = std::max(transposeMaxStep, transitionStep); + const double expectedHz = 220.0 * std::pow(2.0, semitones / 12.0); + const double targetMagnitude = ToneMagnitude(captured, expectedHz); + double strongestMagnitude = 0.0; + for (double candidate = expectedHz * 0.85; candidate <= expectedHz * 1.15; candidate += 0.25) + strongestMagnitude = std::max(strongestMagnitude, ToneMagnitude(captured, candidate)); + const double carrierDeficit = 20.0 * std::log10(std::max(strongestMagnitude, 1.0e-15) + / std::max(targetMagnitude, 1.0e-15)); + transposeCarrierDeficits.push_back(carrierDeficit); + if (targetMagnitude < 1.0e-5 || carrierDeficit > 3.0) + { + std::cerr << "Transpose " << semitones << " target carrier failed: magnitude=" << targetMagnitude + << " deficit=" << carrierDeficit << " dB\n"; + dispose(); + return 1; + } + } + + Float64 latencyAfterTransposeSeconds = 0.0; + UInt32 latencyAfterTransposeSize = sizeof(latencyAfterTransposeSeconds); + if (!Check(AudioUnitGetProperty(unit, kAudioUnitProperty_Latency, kAudioUnitScope_Global, 0, + &latencyAfterTransposeSeconds, &latencyAfterTransposeSize), + "get latency after transpose") + || std::abs(latencyAfterTransposeSeconds - latencySeconds) > (0.5 / kSampleRate) + || transposeMaxStep > 0.25) + { + std::cerr << "Transpose automation changed latency or continuity: latency=" + << latencyAfterTransposeSeconds * kSampleRate << " samples, max-step=" << transposeMaxStep << '\n'; + dispose(); + return 1; + } + + double transposeBypassPeak = 0.0; + if (!Check(AudioUnitSetParameter(unit, kTransposeParameter, kAudioUnitScope_Global, 0, 0.0f, 0), + "reset transpose") + || !renderBlocks(8, transposeBypassPeak)) + { + dispose(); + return 1; + } + Float64 latencyDuringBypassSelectionSeconds = 0.0; UInt32 latencyDuringBypassSelectionSize = sizeof(latencyDuringBypassSelectionSeconds); if (!Check(AudioUnitGetProperty(unit, kAudioUnitProperty_Latency, kAudioUnitScope_Global, 0, @@ -339,6 +428,8 @@ int main() << ", SickDess=" << sickDessPeak << ", drive models=" << drivePeaks[0] << "/" << drivePeaks[1] << "/" << drivePeaks[2] << "/" << drivePeaks[3] << ", bypass model-switch max-step=" << modelSwitchBypassMaxStep << ", latency=" - << latencySeconds * kSampleRate << " samples, elapsed=" << elapsed << "s\n"; + << latencySeconds * kSampleRate << " samples, transpose deficits=" + << transposeCarrierDeficits[0] << "/" << transposeCarrierDeficits[1] + << " dB, transpose max-step=" << transposeMaxStep << ", elapsed=" << elapsed << "s\n"; return 0; } diff --git a/NeuralAmpModeler/NeuralAmpModeler.cpp b/NeuralAmpModeler/NeuralAmpModeler.cpp index 908bfe5..c5d6285 100644 --- a/NeuralAmpModeler/NeuralAmpModeler.cpp +++ b/NeuralAmpModeler/NeuralAmpModeler.cpp @@ -185,12 +185,21 @@ NeuralAmpModeler::NeuralAmpModeler(const InstanceInfo& info) GetParam(kBoostModel)->InitEnum("Boost Model", 0, {"OD808", "SD1", "TS9", "aesahaettr"}); GetParam(kNAMActive)->InitBool("Amp Enabled", true); // Default Amp On + GetParam(kTransposeSemitones)->InitInt("Transpose", 0, -12, 12, "st"); + GetParam(kTransposeSemitones)->SetDisplayFunc([](const double value, WDL_String& display) { + const int semitones = static_cast(std::lround(value)); + if (semitones > 0) + display.SetFormatted(16, "+%d", semitones); + else + display.SetFormatted(16, "%d", semitones); + }); mAmpModelIdx.store(GetParam(kAmpModel)->Int(), std::memory_order_relaxed); mAmpActiveTarget.store(GetParam(kNAMActive)->Bool(), std::memory_order_relaxed); mBoostModelIdx.store(GetParam(kBoostModel)->Int(), std::memory_order_relaxed); mBoostActiveTarget.store(GetParam(kBoostActive)->Bool(), std::memory_order_relaxed); mIRActiveTarget.store(GetParam(kIRToggle)->Bool(), std::memory_order_relaxed); + mTransposeSemitones.store(GetParam(kTransposeSemitones)->Int(), std::memory_order_relaxed); mNoiseGateTrigger.AddListener(&mNoiseGateGain); mCurrentParams.resize(1, 0.5); // Init params @@ -301,6 +310,7 @@ NeuralAmpModeler::NeuralAmpModeler(const InstanceInfo& info) // the amp controls. It avoids squeezing long model names into a small menu. const auto ampModelLabelArea = IRECT(370, 132, 455, 164); const auto ampModelSwitchArea = IRECT(455, 132, 910, 164); + const auto transposeArea = IRECT(74, 110, 336, 178); // Text-labelled effect buttons share one clear row on the lower amp panel. const auto ampBypassArea = IRECT(400, 294, 530, 359); @@ -373,6 +383,26 @@ NeuralAmpModeler::NeuralAmpModeler(const InstanceInfo& info) const auto driveMenuStyle = actionButtonStyle.WithValueText(IText(14.f, EAlign::Center, COLOR_WHITE)); const auto pedalKnobStyle = style.WithShowLabel(false).WithShowValue(false); + const auto transposeStyle = + style.WithShowLabel(true) + .WithShowValue(true) + .WithDrawFrame(true) + .WithDrawShadows(false) + .WithEmboss(false) + .WithRoundness(0.18f) + .WithFrameThickness(1.f) + .WithWidgetFrac(0.70f) + .WithColor(kBG, COLOR_BLACK.WithOpacity(0.72f)) + .WithColor(kFG, PluginColors::NAM_THEMECOLOR.WithOpacity(0.82f)) + .WithColor(kFR, COLOR_WHITE.WithOpacity(0.28f)) + .WithColor(kHL, COLOR_WHITE.WithOpacity(0.12f)) + .WithLabelText(IText(13.f, EAlign::Center, PluginColors::NAM_THEMEFONTCOLOR)) + .WithValueText(IText(17.f, EAlign::Center, COLOR_WHITE)); + + auto* transposeControl = + pGraphics->AttachControl(new NAMTransposeControl(transposeArea, kTransposeSemitones, transposeStyle)); + transposeControl->SetTooltip( + "Retune the guitar from -12 to +12 semitones. Double-click to return to standard pitch."); auto* irSwitchControl = pGraphics->AttachControl( new IVToggleControl(irSwitchArea, kIRToggle, "", actionButtonStyle, "CAB IR OFF", "CAB IR ON")); @@ -614,6 +644,11 @@ void NeuralAmpModeler::ProcessBlock(iplug::sample** inputs, iplug::sample** outp } } + // Retune the calibrated mono guitar before every nonlinear stage. The + // filter bank has no buffered look-ahead, so this does not change host PDC. + mTransposeProcessor.ProcessInPlace( + mInputPointers[0], nFrames, mTransposeSemitones.load(std::memory_order_acquire)); + const bool noiseGateActive = GetParam(kNoiseGateActive)->Value(); const bool toneStackActive = GetParam(kEQActive)->Value(); @@ -764,6 +799,8 @@ void NeuralAmpModeler::OnReset() mNoiseGateTrigger.PrepareBuffers(kNumChannelsInternal, maxBlockSize); mNoiseGateGain.PrepareBuffers(kNumChannelsInternal, maxBlockSize); mHighPass.PrepareBuffers(kNumChannelsInternal, maxBlockSize); + mTransposeSemitones.store(GetParam(kTransposeSemitones)->Int(), std::memory_order_release); + mTransposeProcessor.Reset(sampleRate, mTransposeSemitones.load(std::memory_order_acquire)); const double bass = GetParam(kToneBass)->Value(); const double middle = GetParam(kToneMid)->Value(); @@ -1098,12 +1135,17 @@ void NeuralAmpModeler::OnUIOpen() } const WDL_String boostPath = _GetBoostNAMPathSnapshot(); - if (boostPath.GetLength()) + // The fixed drive selector replaced the historical Boost file browser. Old + // standalone preferences can still contain a path, so never message the + // removed control during editor attachment. + if (boostPath.GetLength() && GetUI() != nullptr + && GetUI()->GetControlWithTag(kCtrlTagBoostModelFileBrowser) != nullptr) { - SendControlMsgFromDelegate(kCtrlTagBoostModelFileBrowser, kMsgTagLoadedBoostModel, boostPath.GetLength(), boostPath.Get()); - if (mBoostModel.load(std::memory_order_acquire) == nullptr - && mPendingBoostModel.load(std::memory_order_acquire) == nullptr) - SendControlMsgFromDelegate(kCtrlTagBoostModelFileBrowser, kMsgTagLoadFailed); + SendControlMsgFromDelegate(kCtrlTagBoostModelFileBrowser, kMsgTagLoadedBoostModel, boostPath.GetLength(), + boostPath.Get()); + if (mBoostModel.load(std::memory_order_acquire) == nullptr + && mPendingBoostModel.load(std::memory_order_acquire) == nullptr) + SendControlMsgFromDelegate(kCtrlTagBoostModelFileBrowser, kMsgTagLoadFailed); } } @@ -1165,6 +1207,9 @@ void NeuralAmpModeler::OnParamChange(int paramIdx) mIRLoadRequest.fetch_add(1, std::memory_order_release); break; } + case kTransposeSemitones: + mTransposeSemitones.store(GetParam(kTransposeSemitones)->Int(), std::memory_order_release); + break; // Changes to the input gain case kCalibrateInput: @@ -1961,6 +2006,8 @@ void NeuralAmpModeler::_UpdateLatency() && mModelMetadataEpoch.load(std::memory_order_relaxed) == mAudioConfigEpoch.load(std::memory_order_acquire)) latency += mModelMetadataLatency.load(std::memory_order_relaxed); // Other things that add latency here... + // Transpose uses causal analytic filters without a buffered look-ahead, so + // its host-reported latency is intentionally zero at every semitone value. // Feels weird to have to do this. if (GetLatency() != latency) diff --git a/NeuralAmpModeler/NeuralAmpModeler.h b/NeuralAmpModeler/NeuralAmpModeler.h index 4608ee6..c7236d3 100644 --- a/NeuralAmpModeler/NeuralAmpModeler.h +++ b/NeuralAmpModeler/NeuralAmpModeler.h @@ -14,6 +14,7 @@ #include "Colors.h" #include "ToneStack.h" +#include "TransposeProcessor.h" #include "IPlug_include_in_plug_hdr.h" #include "ISender.h" @@ -57,6 +58,8 @@ enum EParams // restores the owner-authored SickDess capture. kAmpModel, kNAMActive, // Bypass NAM Processing + // Append new host parameters after the complete 0.1 layout. + kTransposeSemitones, kNumParams }; @@ -418,6 +421,7 @@ class NeuralAmpModeler final : public iplug::Plugin // Noise gates dsp::noise_gate::Trigger mNoiseGateTrigger; dsp::noise_gate::Gain mNoiseGateGain; + dessmetal::transpose::Processor mTransposeProcessor; // Live DSP pointers are owned by the plug-in, but are intentionally raw: // ProcessBlock may swap them without running a destructor. Producers publish // complete objects through the atomic pending slots; the serialized loader @@ -486,6 +490,7 @@ class NeuralAmpModeler final : public iplug::Plugin std::atomic mBoostModelIdx{0}; std::atomic mBoostActiveTarget{false}; std::atomic mIRActiveTarget{true}; + std::atomic mTransposeSemitones{0}; std::atomic mTargetGain{0.5}; std::atomic mAudioSampleRate{48000.0}; std::atomic mAudioMaxBlockSize{2048}; diff --git a/NeuralAmpModeler/NeuralAmpModelerControls.h b/NeuralAmpModeler/NeuralAmpModelerControls.h index e20a4d7..04aa042 100644 --- a/NeuralAmpModeler/NeuralAmpModelerControls.h +++ b/NeuralAmpModeler/NeuralAmpModelerControls.h @@ -4,6 +4,7 @@ #include // std::stringstream #include // std::unordered_map #include "IControls.h" +#include "IVNumberBoxControl.h" #define PLUG() static_cast(GetDelegate()) #define NAM_KNOB_HEIGHT 120.0f @@ -103,6 +104,69 @@ class NAMStompToggleControl : public IVToggleControl } }; +class NAMTransposeControl : public IVNumberBoxControl +{ +public: + NAMTransposeControl(const IRECT& bounds, const int paramIdx, const IVStyle& style) + : IVNumberBoxControl(bounds, paramIdx, nullptr, "TRANSPOSE", style, true, 0.0, -12.0, 12.0, + "%+.0f", false) + { + } + + void OnAttached() override + { + IVNumberBoxControl::OnAttached(); + + // The stock number-box stacks two half-height buttons on the right. That + // works for mouse-heavy desktop utilities, but it is unnecessarily fiddly + // for a control guitarists may change mid-session. Keep the parameter and + // host-notification behavior from IVNumberBoxControl while giving both + // directions a full-height, 54 px target and a more legible glyph. + const auto buttonStyle = + mStyle.WithShowLabel(true) + .WithShowValue(false) + .WithWidgetFrac(1.f) + .WithLabelText(IText(25.f, EAlign::Center, COLOR_WHITE)) + .WithValueText(IText(25.f, EAlign::Center, COLOR_WHITE)); + mDecButton->SetStyle(buttonStyle); + mIncButton->SetStyle(buttonStyle); + OnResize(); + } + + void OnResize() override + { + MakeRects(mRECT, false); + + auto sections = mWidgetBounds.GetPadded(-1.f); + constexpr float buttonWidth = 54.f; + constexpr float controlGap = 4.f; + const auto decBounds = sections.GetFromLeft(buttonWidth); + const auto incBounds = sections.GetFromRight(buttonWidth); + const auto valueBounds = IRECT(decBounds.R + controlGap, sections.T, + incBounds.L - controlGap, sections.B); + + if (mTextReadout) + mTextReadout->SetTargetAndDrawRECTs(valueBounds); + if (mDecButton) + mDecButton->SetTargetAndDrawRECTs(decBounds); + if (mIncButton) + mIncButton->SetTargetAndDrawRECTs(incBounds); + + SetTargetRECT(valueBounds); + SetDirty(false); + } + + void OnMouseDblClick(float, float, const IMouseMod&) override + { + if (IsDisabled() || GetParam() == nullptr) + return; + GetDelegate()->BeginInformHostOfParamChangeFromUI(GetParamIdx()); + mRealValue = 0.0; + OnValueChanged(); + GetDelegate()->EndInformHostOfParamChangeFromUI(GetParamIdx()); + } +}; + // Scaled bitmap background control - draws bitmap scaled to fill the entire bounds class NAMScaledBitmapControl : public IControl, public IBitmapBase { diff --git a/NeuralAmpModeler/TransposeProcessor.h b/NeuralAmpModeler/TransposeProcessor.h new file mode 100644 index 0000000..7f11bd6 --- /dev/null +++ b/NeuralAmpModeler/TransposeProcessor.h @@ -0,0 +1,450 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace dessmetal::transpose +{ +// Low-latency polyphonic pitch shifting for live guitar. The analytic +// filter-bank topology and ERB-like spacing are derived from Steven Schulteis' +// MIT-licensed Terrarium Poly Pitch implementation (Copyright 2024) and the +// ERB-PS research it cites. DessMetal adds a two-resolution transient/body +// path, phase-continuous ratio automation, and a click-free dry transition. +// See licenses/terrarium-poly-octave-MIT.txt. +class Processor +{ +public: + static constexpr int kMinSemitones = -12; + static constexpr int kMaxSemitones = 12; + static constexpr int kBandCount = 83; + + bool Reset(const double sampleRate, const int initialSemitones = 0) + { + mConfigured = false; + if (!std::isfinite(sampleRate) || sampleRate < 8000.0) + return false; + + const int clampedSemitones = ClampSemitones(initialSemitones); + const float initialScale = SemitonesToScale(clampedSemitones); + if (!mQuality.Configure(sampleRate, 0.5, initialScale) + || !mFast.Configure(sampleRate, 2.0, initialScale)) + return false; + + mSampleRate = sampleRate; + mTransitionSamples = std::max(1, static_cast(std::lround(0.008 * sampleRate))); + mFastAttackCoefficient = Coefficient(0.0005); + mFastReleaseCoefficient = Coefficient(0.010); + mSlowAttackCoefficient = Coefficient(0.020); + mSlowReleaseCoefficient = Coefficient(0.100); + mBlendReleaseCoefficient = Coefficient(0.015); + mTransientHighpassCoefficient = + static_cast(std::exp(-2.0 * kPi * 1200.0 / sampleRate)); + mHoldDurationSamples = std::max(1, static_cast(std::lround(0.008 * sampleRate))); + + mTargetSemitones = clampedSemitones; + mCurrentSemitones = static_cast(clampedSemitones); + mTargetScale = initialScale; + mCurrentScale = initialScale; + mScaleStep = 0.0f; + mSemitoneStep = 0.0f; + mScaleRampRemaining = 0; + mTargetWetMix = clampedSemitones == 0 ? 0.0f : 1.0f; + mWetMix = mTargetWetMix; + mWetMixStep = 0.0f; + mWetRampRemaining = 0; + ClearTransientState(); + mConfigured = true; + return true; + } + + void Process(const double* input, double* output, const int numFrames, const int semitones) noexcept + { + if (output == nullptr || numFrames <= 0) + return; + if (input == nullptr) + { + std::fill(output, output + numFrames, 0.0); + return; + } + if (!mConfigured) + { + for (int frame = 0; frame < numFrames; ++frame) + output[frame] = std::isfinite(input[frame]) ? input[frame] : 0.0; + return; + } + + SetSemitones(semitones); + for (int frame = 0; frame < numFrames; ++frame) + { + const double drySample = std::isfinite(input[frame]) ? input[frame] : 0.0; + const float sample = static_cast(drySample); + AdvancePitchRamp(); + + const float quality = kQualityGain * mQuality.Process(sample, mCurrentScale); + const float positiveShift = std::max(mCurrentSemitones, 0.0f) / 12.0f; + const float positiveShiftSquared = positiveShift * positiveShift; + const float fastGain = 1.0f + 5.0f * positiveShiftSquared * positiveShiftSquared; + const float fast = fastGain * mFast.Process(sample, mCurrentScale); + + // A slew envelope reacts quickly to pick edges without continuously + // retriggering on ordinary amplitude beating inside a chord. + const float onsetMagnitude = std::abs(sample - mPreviousInput); + mPreviousInput = sample; + mFastEnvelope = Follow(onsetMagnitude, mFastEnvelope, + onsetMagnitude > mFastEnvelope ? mFastAttackCoefficient + : mFastReleaseCoefficient); + mSlowEnvelope = Follow(onsetMagnitude, mSlowEnvelope, + onsetMagnitude > mSlowEnvelope ? mSlowAttackCoefficient + : mSlowReleaseCoefficient); + + if (mDetectorArmed && mFastEnvelope > 1.0e-5f + && mFastEnvelope > std::max(3.0f * mSlowEnvelope, 2.0e-5f)) + { + mTransientBlend = 1.0f; + mHoldSamplesRemaining = mHoldDurationSamples; + mDetectorArmed = false; + } + if (!mDetectorArmed + && (mFastEnvelope < 1.25f * mSlowEnvelope || mSlowEnvelope < 1.0e-6f)) + mDetectorArmed = true; + + if (mHoldSamplesRemaining > 0) + { + --mHoldSamplesRemaining; + mTransientBlend = 1.0f; + } + else + { + mTransientBlend *= mBlendReleaseCoefficient; + if (mTransientBlend < 1.0e-6f) + mTransientBlend = 0.0f; + } + + mTransientHighpass = mTransientHighpassCoefficient + * (mTransientHighpass + sample - mHighpassPreviousInput); + mHighpassPreviousInput = sample; + + const float shifted = mTransientBlend * (fast + kTransientHighpassGain * mTransientHighpass) + + (1.0f - mTransientBlend) * quality; + AdvanceWetRamp(); + if (mWetMix == 0.0f) + { + output[frame] = drySample; + continue; + } + const double result = (1.0 - static_cast(mWetMix)) * drySample + + static_cast(mWetMix) * shifted; + if (std::isfinite(result)) + { + output[frame] = static_cast(result); + } + else + { + output[frame] = 0.0; + ClearSignalState(); + } + } + } + + void ProcessInPlace(double* samples, const int numFrames, const int semitones) noexcept + { + Process(samples, samples, numFrames, semitones); + } + + bool IsConfigured() const noexcept { return mConfigured; } + int GetLatencySamples() const noexcept { return 0; } + int GetBandCount() const noexcept { return mQuality.GetBandCount(); } + int GetTargetSemitones() const noexcept { return mTargetSemitones; } + +private: + static constexpr float kPi = 3.14159265358979323846f; + static constexpr float kTwoPi = 2.0f * kPi; + static constexpr float kQualityGain = 2.8f; + static constexpr float kTransientHighpassGain = 0.65f; + + static int ClampSemitones(const int semitones) noexcept + { + return std::clamp(semitones, kMinSemitones, kMaxSemitones); + } + + static float SemitonesToScale(const int semitones) + { + return static_cast(std::pow(2.0, static_cast(semitones) / 12.0)); + } + + static float CenterFrequency(const int index) + { + return 480.0f * std::pow(2.0f, static_cast(index) / 19.0f) - 420.0f; + } + + static float Bandwidth(const int index) + { + const float lower = CenterFrequency(index - 1); + const float center = CenterFrequency(index); + const float upper = CenterFrequency(index + 1); + const float upperDistance = upper - center; + const float lowerDistance = center - lower; + return 2.0f * upperDistance * lowerDistance / (upperDistance + lowerDistance); + } + + static float BalancedAtan2(const float y, const float x) noexcept + { + if (x == 0.0f) + return y > 0.0f ? 0.5f * kPi : (y < 0.0f ? -0.5f * kPi : 0.0f); + + const float absX = std::abs(x); + const float absY = std::abs(y); + const bool invert = absY > absX; + const float ratio = invert ? absX / std::max(absY, std::numeric_limits::min()) + : absY / std::max(absX, std::numeric_limits::min()); + const float ratio2 = ratio * ratio; + float angle = (((0.0208351f * ratio2 - 0.0851330f) * ratio2 + 0.1801410f) * ratio2 + - 0.3302995f) + * ratio2 * ratio + + ratio; + if (invert) + angle = 0.5f * kPi - angle; + if (x < 0.0f) + angle = kPi - angle; + return std::copysign(angle, y); + } + + static float BalancedSine(const float radians) noexcept + { + const float wrapped = radians - kTwoPi * std::floor((radians + kPi) / kTwoPi); + constexpr float b = 4.0f / kPi; + constexpr float c = -4.0f / (kPi * kPi); + float estimate = b * wrapped + c * wrapped * std::abs(wrapped); + constexpr float correction = 0.225f; + return correction * (estimate * std::abs(estimate) - estimate) + estimate; + } + + class Band + { + public: + Band(const double center, const double sampleRate, const double bandwidth, const float initialScale) + : mScale(initialScale) + { + const std::complex imaginary{0.0, 1.0}; + const double omega0 = static_cast(kPi) * bandwidth / sampleRate; + const double cosOmega0 = std::cos(omega0); + const double sinOmega0 = std::sin(omega0); + const double sqrtTwo = std::sqrt(2.0); + const double a0 = 1.0 + sqrtTwo * sinOmega0 * 0.5; + const double gain = (1.0 - cosOmega0) / (2.0 * a0); + const double omega1 = static_cast(kTwoPi) * center / sampleRate; + const std::complex rotation1 = std::exp(imaginary * omega1); + const std::complex rotation2 = std::exp(imaginary * omega1 * 2.0); + + mD0 = static_cast(gain); + mD1 = ToFloat(rotation1 * (2.0 * gain)); + mD2 = ToFloat(rotation2 * gain); + mC1 = ToFloat(rotation1 * (-2.0 * cosOmega0 / a0)); + mC2 = ToFloat(rotation2 * ((1.0 - sqrtTwo * sinOmega0 * 0.5) / a0)); + } + + float Process(const float sample, const float scale) noexcept + { + const bool previousImaginarySign = std::signbit(mY.imag()); + mY = mState2 + mD0 * sample; + mState2 = mState1 + mD1 * sample - mC1 * mY; + mState1 = mD2 * sample - mC2 * mY; + + if (!std::isfinite(mY.real()) || !std::isfinite(mY.imag())) + { + ClearState(); + mScale = scale; + return 0.0f; + } + + const bool wrapped = mY.real() < 0.0f && std::signbit(mY.imag()) != previousImaginarySign; + const float norm = std::norm(mY); + if (!(norm > std::numeric_limits::min())) + { + mScale = scale; + return 0.0f; + } + + const float phaseTurns = BalancedAtan2(mY.imag(), mY.real()) / kTwoPi; + if (wrapped) + mPhaseOffsetTurns += mScale; + + // Retune without a phase jump. Changing the scale normally moves the + // current point on the waveform; the compensating offset keeps that + // point continuous while the following samples adopt the new ratio. + mPhaseOffsetTurns += (mScale - scale) * phaseTurns; + mPhaseOffsetTurns -= std::floor(mPhaseOffsetTurns); + mScale = scale; + + const float magnitude = std::sqrt(norm); + return magnitude * BalancedSine(kTwoPi * (scale * phaseTurns + mPhaseOffsetTurns)); + } + + void ClearState() noexcept + { + mState1 = {}; + mState2 = {}; + mY = {}; + mPhaseOffsetTurns = 0.25f; + } + + private: + static std::complex ToFloat(const std::complex& value) + { + return {static_cast(value.real()), static_cast(value.imag())}; + } + + float mScale = 1.0f; + float mPhaseOffsetTurns = 0.25f; + float mD0 = 0.0f; + std::complex mD1{}; + std::complex mD2{}; + std::complex mC1{}; + std::complex mC2{}; + std::complex mState1{}; + std::complex mState2{}; + std::complex mY{}; + }; + + class FilterBank + { + public: + bool Configure(const double sampleRate, const double bandwidthScale, const float initialScale) + { + mBands.clear(); + mBands.reserve(kBandCount); + for (int index = 0; index < kBandCount; ++index) + { + const double center = CenterFrequency(index); + if (center >= sampleRate * 0.475) + break; + mBands.emplace_back(center, sampleRate, Bandwidth(index) * bandwidthScale, initialScale); + } + return !mBands.empty(); + } + + float Process(const float sample, const float scale) noexcept + { + float output = 0.0f; + for (auto& band : mBands) + output += band.Process(sample, scale); + return output; + } + + void ClearState() noexcept + { + for (auto& band : mBands) + band.ClearState(); + } + + int GetBandCount() const noexcept { return static_cast(mBands.size()); } + + private: + std::vector mBands; + }; + + float Coefficient(const double seconds) const + { + return static_cast(std::exp(-1.0 / std::max(seconds * mSampleRate, 1.0))); + } + + static float Follow(const float input, const float state, const float coefficient) noexcept + { + return input + coefficient * (state - input); + } + + void SetSemitones(const int semitones) noexcept + { + const int clamped = ClampSemitones(semitones); + if (clamped == mTargetSemitones) + return; + + mTargetSemitones = clamped; + mTargetScale = SemitonesToScale(clamped); + mScaleStep = (mTargetScale - mCurrentScale) / static_cast(mTransitionSamples); + mSemitoneStep = (static_cast(clamped) - mCurrentSemitones) + / static_cast(mTransitionSamples); + mScaleRampRemaining = mTransitionSamples; + + mTargetWetMix = clamped == 0 ? 0.0f : 1.0f; + mWetMixStep = (mTargetWetMix - mWetMix) / static_cast(mTransitionSamples); + mWetRampRemaining = mTransitionSamples; + } + + void AdvancePitchRamp() noexcept + { + if (mScaleRampRemaining <= 0) + return; + mCurrentScale += mScaleStep; + mCurrentSemitones += mSemitoneStep; + if (--mScaleRampRemaining == 0) + { + mCurrentScale = mTargetScale; + mCurrentSemitones = static_cast(mTargetSemitones); + } + } + + void AdvanceWetRamp() noexcept + { + if (mWetRampRemaining <= 0) + return; + mWetMix += mWetMixStep; + if (--mWetRampRemaining == 0) + mWetMix = mTargetWetMix; + } + + void ClearTransientState() noexcept + { + mFastEnvelope = 0.0f; + mSlowEnvelope = 0.0f; + mTransientBlend = 0.0f; + mPreviousInput = 0.0f; + mHighpassPreviousInput = 0.0f; + mTransientHighpass = 0.0f; + mHoldSamplesRemaining = 0; + mDetectorArmed = true; + } + + void ClearSignalState() noexcept + { + mQuality.ClearState(); + mFast.ClearState(); + ClearTransientState(); + } + + FilterBank mQuality; + FilterBank mFast; + double mSampleRate = 48000.0; + int mTransitionSamples = 384; + int mTargetSemitones = 0; + float mCurrentSemitones = 0.0f; + float mTargetScale = 1.0f; + float mCurrentScale = 1.0f; + float mScaleStep = 0.0f; + float mSemitoneStep = 0.0f; + int mScaleRampRemaining = 0; + float mTargetWetMix = 0.0f; + float mWetMix = 0.0f; + float mWetMixStep = 0.0f; + int mWetRampRemaining = 0; + float mFastAttackCoefficient = 0.0f; + float mFastReleaseCoefficient = 0.0f; + float mSlowAttackCoefficient = 0.0f; + float mSlowReleaseCoefficient = 0.0f; + float mBlendReleaseCoefficient = 0.0f; + float mTransientHighpassCoefficient = 0.0f; + float mFastEnvelope = 0.0f; + float mSlowEnvelope = 0.0f; + float mTransientBlend = 0.0f; + float mPreviousInput = 0.0f; + float mHighpassPreviousInput = 0.0f; + float mTransientHighpass = 0.0f; + int mHoldDurationSamples = 0; + int mHoldSamplesRemaining = 0; + bool mDetectorArmed = true; + bool mConfigured = false; +}; +} // namespace dessmetal::transpose diff --git a/NeuralAmpModeler/Unserialization.cpp b/NeuralAmpModeler/Unserialization.cpp index 3ef3013..26add44 100644 --- a/NeuralAmpModeler/Unserialization.cpp +++ b/NeuralAmpModeler/Unserialization.cpp @@ -122,6 +122,44 @@ int _UnserializePathsAndExpectedKeys(const iplug::IByteChunk& chunk, int startPo return _UnserializeExpectedKeys(chunk, pos, config, paramNames); } +// DessMetal 0.2 establishes the 21-value layout with Transpose appended after +// every 0.1 host parameter. Accept only its exact payload shape. +int _GetConfigFrom_0_2_x(const iplug::IByteChunk& chunk, int startPos, nlohmann::json& config) +{ +#if defined(VST3_API) || defined(VST3C_API) || defined(VST3P_API) + constexpr bool allowVST3BypassSuffix = true; +#else + constexpr bool allowVST3BypassSuffix = false; +#endif + + int pos = _UnserializePaths(chunk, startPos, config); + const auto remainingBytes = static_cast(chunk.Size() - pos); + if (dessmetal::state::DetectParameterLayout02(remainingBytes, allowVST3BypassSuffix) + != dessmetal::state::ParameterLayout02::Current21) + { + std::ostringstream message; + message << "Unsupported DessMetal 0.2.x parameter layout: " << remainingBytes + << " bytes remain; expected " + << dessmetal::state::ParameterBytes(dessmetal::state::kCurrent02ParameterNames.size()); + if (allowVST3BypassSuffix) + message << " plus an optional " << dessmetal::state::kVST3BypassSuffixBytes + << "-byte VST3 bypass value"; + throw std::runtime_error(message.str()); + } + + pos = _UnserializeExpectedKeys(chunk, pos, config, dessmetal::state::kCurrent02ParameterNames); + const auto parameterBytes = + dessmetal::state::ParameterBytes(dessmetal::state::kCurrent02ParameterNames.size()); + if (remainingBytes == parameterBytes + dessmetal::state::kVST3BypassSuffixBytes) + { + std::int32_t bypass = 0; + const int suffixEnd = chunk.Get(&bypass, pos); + if (suffixEnd < 0 || (bypass != 0 && bypass != 1)) + throw std::runtime_error("Preset contains an invalid VST3 bypass suffix"); + } + return pos; +} + // DessMetal 0.1.0 was built with both a 14-parameter and a later // 20-parameter positional layout. Distinguish them by the exact bytes remaining // after the two bounded path strings; never reinterpret a partial layout. @@ -354,7 +392,11 @@ int NeuralAmpModeler::_UnserializeStateWithKnownVersion(const iplug::IByteChunk& _Version version(versionStr); // Act accordingly nlohmann::json config; - if (version.GetMajor() == 0 && version.GetMinor() == 1) + if (version.GetMajor() == 0 && version.GetMinor() == 2) + { + pos = _GetConfigFrom_0_2_x(chunk, pos, config); + } + else if (version.GetMajor() == 0 && version.GetMinor() == 1) { // Only 0.1.0 emitted the historical 14-value layout. 0.1.1 establishes // the current 20-value layout while still accepting existing 20-value @@ -377,6 +419,10 @@ int NeuralAmpModeler::_UnserializeStateWithKnownVersion(const iplug::IByteChunk& { throw std::runtime_error("Unsupported preset version: " + versionStr); } + // Every state predating 0.2 must deterministically bypass the newly added + // processor, even when a host restores into an already-used instance. + if (!config.contains("Transpose")) + config["Transpose"] = 0.0; _UnserializeApplyConfig(config); return pos; } @@ -385,6 +431,7 @@ int NeuralAmpModeler::_UnserializeStateWithUnknownVersion(const iplug::IByteChun { nlohmann::json config; int pos = _GetConfigFrom_Earlier(chunk, startPos, config); + config["Transpose"] = 0.0; _UnserializeApplyConfig(config); return pos; } diff --git a/NeuralAmpModeler/Unserialization.h b/NeuralAmpModeler/Unserialization.h index 64c6b63..5791a98 100644 --- a/NeuralAmpModeler/Unserialization.h +++ b/NeuralAmpModeler/Unserialization.h @@ -51,6 +51,33 @@ inline constexpr std::array kCurrent01ParameterNames{ "Amp Enabled", }; +// DessMetal 0.2 appends Transpose without changing any established host +// parameter identifier. New parameters must continue to be appended here and +// in EParams so positional state remains deterministic. +inline constexpr std::array kCurrent02ParameterNames{ + "Input", + "Gain", + "Threshold", + "Bass", + "Middle", + "Treble", + "Output", + "Boost Level", + "Boost Tone", + "NoiseGateActive", + "ToneStack", + "Boost", + "BoostOutput", + "IRToggle", + "Boost Model", + "CalibrateInput", + "InputCalibrationLevel", + "OutputMode", + "Amp Model", + "Amp Enabled", + "Transpose", +}; + struct NamedDefault { std::string_view name; @@ -78,6 +105,12 @@ enum class ParameterLayout01 Current20, }; +enum class ParameterLayout02 +{ + Invalid, + Current21, +}; + inline constexpr std::size_t ParameterBytes(const std::size_t parameterCount) { return parameterCount * sizeof(double); @@ -111,6 +144,14 @@ inline constexpr ParameterLayout01 DetectParameterLayout01(const std::size_t rem return ParameterLayout01::Invalid; } +inline constexpr ParameterLayout02 DetectParameterLayout02(const std::size_t remainingBytes, + const bool allowVST3BypassSuffix) +{ + return MatchesParameterPayload(remainingBytes, kCurrent02ParameterNames.size(), allowVST3BypassSuffix) + ? ParameterLayout02::Current21 + : ParameterLayout02::Invalid; +} + // The original DessMetal enum was DessTortion=0, DessBlock=1. The current // stable host enum keeps DessTortion-blue at 0 and DessBlock-green at 2. inline constexpr bool IsSupportedLegacy010AmpModel(const double legacyValue) diff --git a/NeuralAmpModeler/config.h b/NeuralAmpModeler/config.h index 56eb1cf..17578fc 100644 --- a/NeuralAmpModeler/config.h +++ b/NeuralAmpModeler/config.h @@ -1,7 +1,7 @@ #define PLUG_NAME "DessMetal" #define PLUG_MFR "Alexander Dess" -#define PLUG_VERSION_HEX 0x000101 -#define PLUG_VERSION_STR "0.1.1" +#define PLUG_VERSION_HEX 0x000200 +#define PLUG_VERSION_STR "0.2.0" #define PLUG_UNIQUE_ID '1YEo' #define PLUG_MFR_ID 'AdMs' #define PLUG_URL_STR "https://github.com/appdess/dessmetal" diff --git a/NeuralAmpModeler/experiments/transpose/ErbPitchPrototype.h b/NeuralAmpModeler/experiments/transpose/ErbPitchPrototype.h new file mode 100644 index 0000000..667ce23 --- /dev/null +++ b/NeuralAmpModeler/experiments/transpose/ErbPitchPrototype.h @@ -0,0 +1,363 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace dessmetal::experiments::transpose +{ +// Evaluation implementation of the ERB-style analytic filter-bank approach used +// by the MIT-licensed Terrarium Poly Pitch project. The coefficient topology, +// phase-wrap strategy, and default 83-band spacing are derived from: +// https://github.com/schult/terrarium-poly-octave/tree/arbitrary-shift +// Copyright (c) 2024 Steven Schulteis, used under the MIT License. +// +// This is deliberately isolated from the plug-in until the objective and musical +// quality gates pass. The desktop modes let the benchmark distinguish algorithm +// limitations from approximations intended for an embedded processor. +class ErbPitchPrototype +{ +public: + enum class MathMode + { + kEmbeddedApproximation, + kBalancedApproximation, + kAccurate + }; + + static constexpr int kMinSemitones = -12; + static constexpr int kMaxSemitones = 12; + static constexpr int kDefaultBandCount = 83; + + bool Reset(const double sampleRate, const int maxBlockSize, const MathMode mathMode, + const int bandCount = kDefaultBandCount, const double density = 19.0, + const double bandwidthScale = 1.0, const double lowBandwidthScale = 0.0, + const double bandwidthTransitionHz = 300.0, const bool compensateFilterPhase = false, + const int dominanceExponent = 0) + { + mConfigured = false; + if (!std::isfinite(sampleRate) || sampleRate < 8000.0 || maxBlockSize <= 0 || bandCount <= 0 + || !std::isfinite(density) || density < 4.0 || !std::isfinite(bandwidthScale) + || bandwidthScale <= 0.0 || !std::isfinite(lowBandwidthScale) + || !std::isfinite(bandwidthTransitionHz) || bandwidthTransitionHz <= 0.0 + || dominanceExponent < 0 || dominanceExponent > 8) + return false; + + mSampleRate = sampleRate; + mMathMode = mathMode; + mBands.clear(); + mBands.reserve(static_cast(bandCount)); + for (int index = 0; index < bandCount; ++index) + { + const double center = CenterFrequency(index, density); + if (center >= sampleRate * 0.475) + break; + const double lowScale = lowBandwidthScale > 0.0 ? lowBandwidthScale : bandwidthScale; + const double normalizedCenter = center / bandwidthTransitionHz; + const double lowWeight = 1.0 / (1.0 + normalizedCenter * normalizedCenter + * normalizedCenter * normalizedCenter); + const double shapedBandwidthScale = bandwidthScale + (lowScale - bandwidthScale) * lowWeight; + mBands.emplace_back(center, sampleRate, Bandwidth(index, density) * shapedBandwidthScale, mathMode, + compensateFilterPhase); + } + if (mBands.empty()) + return false; + + mBandOutputs.assign(mBands.size(), 0.0f); + mBandMagnitudePowers.assign(mBands.size(), 0.0f); + mDominanceExponent = dominanceExponent; + + ApplySemitones(0); + mConfigured = true; + return true; + } + + void Process(const double* input, double* output, const int numFrames, const int semitones) + { + if (output == nullptr || numFrames <= 0) + return; + if (!mConfigured || input == nullptr) + { + std::fill(output, output + numFrames, 0.0); + return; + } + + const int clampedSemitones = std::clamp(semitones, kMinSemitones, kMaxSemitones); + if (clampedSemitones != mAppliedSemitones) + ApplySemitones(clampedSemitones); + + for (int frame = 0; frame < numFrames; ++frame) + { + const float sample = static_cast(input[frame]); + float shifted = 0.0f; + if (mDominanceExponent == 0) + { + for (auto& band : mBands) + shifted += band.Process(sample); + } + else + { + for (std::size_t index = 0; index < mBands.size(); ++index) + { + mBandOutputs[index] = mBands[index].Process(sample); + float power = mBands[index].GetMagnitude(); + for (int exponent = 1; exponent < mDominanceExponent; ++exponent) + power *= mBands[index].GetMagnitude(); + mBandMagnitudePowers[index] = power; + } + for (std::size_t index = 0; index < mBands.size(); ++index) + { + double neighborhoodPower = mBandMagnitudePowers[index]; + if (index > 0) + neighborhoodPower += mBandMagnitudePowers[index - 1]; + if (index + 1 < mBands.size()) + neighborhoodPower += mBandMagnitudePowers[index + 1]; + if (neighborhoodPower > std::numeric_limits::min()) + shifted += mBandOutputs[index] + * static_cast(mBandMagnitudePowers[index] / neighborhoodPower); + } + } + output[frame] = static_cast(shifted); + } + } + + bool IsConfigured() const { return mConfigured; } + int GetLatencySamples() const { return 0; } + int GetBandCount() const { return static_cast(mBands.size()); } + int GetAppliedSemitones() const { return mAppliedSemitones; } + + static double CenterFrequency(const int index) + { + return CenterFrequency(index, 19.0); + } + + static double CenterFrequency(const int index, const double density) + { + return 480.0 * std::pow(2.0, static_cast(index) / density) - 420.0; + } + + static double Bandwidth(const int index) + { + return Bandwidth(index, 19.0); + } + + static double Bandwidth(const int index, const double density) + { + const double lower = CenterFrequency(index - 1, density); + const double center = CenterFrequency(index, density); + const double upper = CenterFrequency(index + 1, density); + const double upperDistance = upper - center; + const double lowerDistance = center - lower; + return 2.0 * upperDistance * lowerDistance / (upperDistance + lowerDistance); + } + +private: + static constexpr float kPi = 3.14159265358979323846f; + static constexpr float kTwoPi = 2.0f * kPi; + + static float EmbeddedInverseSqrt(const float value) + { + if (!(value > 0.0f)) + return 0.0f; + std::uint32_t bits = 0; + std::memcpy(&bits, &value, sizeof(bits)); + bits = 0x5F1FFFF9u - (bits >> 1u); + float estimate = 0.0f; + std::memcpy(&estimate, &bits, sizeof(estimate)); + return estimate * (0.703952253f * (2.38924456f - value * estimate * estimate)); + } + + static float EmbeddedAtan2Turns(const float y, const float x) + { + constexpr float halfTurn = 0.5f; + constexpr float quarterTurn = 0.25f; + const float absY = std::abs(y) + std::numeric_limits::epsilon(); + const float absX = std::abs(x); + const float ratio = (x - std::copysign(absY, x)) / (absY + absX); + const float turns = halfTurn - std::copysign(quarterTurn, x) - quarterTurn * ratio; + return std::copysign(turns, y); + } + + static float EmbeddedSineTurns(const float turns) + { + const float z = 2.0f * (turns - std::floor(turns) - 0.5f); + return 4.0f * z * (1.0f - std::abs(z)); + } + + // Low-cost atan approximation with substantially lower angular error than the + // embedded linear approximation. Input and output are conventional radians. + static float BalancedAtan2(const float y, const float x) + { + if (x == 0.0f) + return y > 0.0f ? 0.5f * kPi : (y < 0.0f ? -0.5f * kPi : 0.0f); + + const float absX = std::abs(x); + const float absY = std::abs(y); + const bool invert = absY > absX; + const float ratio = invert ? absX / std::max(absY, std::numeric_limits::min()) + : absY / std::max(absX, std::numeric_limits::min()); + const float ratio2 = ratio * ratio; + // Minimax-style odd polynomial on [0, 1]. + float angle = (((0.0208351f * ratio2 - 0.0851330f) * ratio2 + 0.1801410f) * ratio2 + - 0.3302995f) * ratio2 * ratio + ratio; + if (invert) + angle = 0.5f * kPi - angle; + if (x < 0.0f) + angle = kPi - angle; + return std::copysign(angle, y); + } + + static float BalancedSine(const float radians) + { + float wrapped = radians - kTwoPi * std::floor((radians + kPi) / kTwoPi); + constexpr float b = 4.0f / kPi; + constexpr float c = -4.0f / (kPi * kPi); + float estimate = b * wrapped + c * wrapped * std::abs(wrapped); + constexpr float correction = 0.225f; + estimate = correction * (estimate * std::abs(estimate) - estimate) + estimate; + return estimate; + } + + class Band + { + public: + Band(const double center, const double sampleRate, const double bandwidth, const MathMode mathMode, + const bool compensateFilterPhase) + : mMathMode(mathMode), mCompensateFilterPhase(compensateFilterPhase), + mCenterHz(static_cast(center)), mBandwidthHz(static_cast(bandwidth)), + mSampleRate(static_cast(sampleRate)) + { + const std::complex imaginary{0.0, 1.0}; + const double omega0 = static_cast(kPi) * bandwidth / sampleRate; + const double cosOmega0 = std::cos(omega0); + const double sinOmega0 = std::sin(omega0); + const double sqrtTwo = std::sqrt(2.0); + const double a0 = 1.0 + sqrtTwo * sinOmega0 * 0.5; + const double gain = (1.0 - cosOmega0) / (2.0 * a0); + const double omega1 = static_cast(kTwoPi) * center / sampleRate; + const std::complex rotation1 = std::exp(imaginary * omega1); + const std::complex rotation2 = std::exp(imaginary * omega1 * 2.0); + + mD0 = static_cast(gain); + mD1 = ToFloat(rotation1 * (2.0 * gain)); + mD2 = ToFloat(rotation2 * gain); + mC1 = ToFloat(rotation1 * (-2.0 * cosOmega0 / a0)); + mC2 = ToFloat(rotation2 * ((1.0 - sqrtTwo * sinOmega0 * 0.5) / a0)); + } + + void SetScale(const float scale) + { + mScale = scale; + mOffsetStepTurns = scale; + } + + float Process(const float sample) + { + const bool previousImaginarySign = std::signbit(mY.imag()); + mY = mState2 + mD0 * sample; + mState2 = mState1 + mD1 * sample - mC1 * mY; + mState1 = mD2 * sample - mC2 * mY; + + if (mY.real() < 0.0f && std::signbit(mY.imag()) != previousImaginarySign) + { + mPhaseOffsetTurns += mOffsetStepTurns; + mPhaseOffsetTurns -= std::floor(mPhaseOffsetTurns); + } + + const float norm = std::norm(mY); + if (!(norm > std::numeric_limits::min())) + return 0.0f; + + float magnitude = 0.0f; + float phaseTurns = 0.0f; + switch (mMathMode) + { + case MathMode::kEmbeddedApproximation: + magnitude = norm * EmbeddedInverseSqrt(norm); + phaseTurns = EmbeddedAtan2Turns(mY.imag(), mY.real()); + break; + case MathMode::kBalancedApproximation: + magnitude = std::sqrt(norm); + phaseTurns = BalancedAtan2(mY.imag(), mY.real()) / kTwoPi; + break; + case MathMode::kAccurate: + magnitude = std::sqrt(norm); + phaseTurns = std::atan2(mY.imag(), mY.real()) / kTwoPi; + break; + } + + float responsePhaseTurns = 0.0f; + if (mCompensateFilterPhase && mHasPreviousPhase) + { + float phaseDelta = phaseTurns - mPreviousPhaseTurns; + phaseDelta -= std::round(phaseDelta); + const float instantaneousHz = phaseDelta * mSampleRate; + const float normalizedOffset = std::clamp( + 2.0f * (instantaneousHz - mCenterHz) / std::max(mBandwidthHz, 1.0e-6f), -4.0f, 4.0f); + const float numerator = 1.41421356237f * normalizedOffset; + const float denominator = 1.0f - normalizedOffset * normalizedOffset; + responsePhaseTurns = -BalancedAtan2(numerator, denominator) / kTwoPi; + } + mPreviousPhaseTurns = phaseTurns; + mHasPreviousPhase = true; + mLastMagnitude = magnitude; + + const float outputTurns = mScale * (phaseTurns - responsePhaseTurns) + mPhaseOffsetTurns; + if (mMathMode == MathMode::kEmbeddedApproximation) + return magnitude * EmbeddedSineTurns(outputTurns); + if (mMathMode == MathMode::kAccurate) + return magnitude * std::sin(kTwoPi * outputTurns); + return magnitude * BalancedSine(kTwoPi * outputTurns); + } + + float GetMagnitude() const { return mLastMagnitude; } + + private: + static std::complex ToFloat(const std::complex value) + { + return {static_cast(value.real()), static_cast(value.imag())}; + } + + MathMode mMathMode = MathMode::kBalancedApproximation; + bool mCompensateFilterPhase = false; + bool mHasPreviousPhase = false; + float mCenterHz = 0.0f; + float mBandwidthHz = 1.0f; + float mSampleRate = 48000.0f; + float mPreviousPhaseTurns = 0.0f; + float mLastMagnitude = 0.0f; + float mScale = 1.0f; + float mOffsetStepTurns = 1.0f; + float mPhaseOffsetTurns = 0.25f; + float mD0 = 0.0f; + std::complex mD1{}; + std::complex mD2{}; + std::complex mC1{}; + std::complex mC2{}; + std::complex mState1{}; + std::complex mState2{}; + std::complex mY{}; + }; + + void ApplySemitones(const int semitones) + { + mAppliedSemitones = std::clamp(semitones, kMinSemitones, kMaxSemitones); + const float scale = static_cast(std::pow(2.0, static_cast(mAppliedSemitones) / 12.0)); + for (auto& band : mBands) + band.SetScale(scale); + } + + std::vector mBands; + std::vector mBandOutputs; + std::vector mBandMagnitudePowers; + double mSampleRate = 48000.0; + MathMode mMathMode = MathMode::kBalancedApproximation; + int mAppliedSemitones = 0; + int mDominanceExponent = 0; + bool mConfigured = false; +}; +} // namespace dessmetal::experiments::transpose diff --git a/NeuralAmpModeler/experiments/transpose/HybridErbPitchPrototype.h b/NeuralAmpModeler/experiments/transpose/HybridErbPitchPrototype.h new file mode 100644 index 0000000..e00c55e --- /dev/null +++ b/NeuralAmpModeler/experiments/transpose/HybridErbPitchPrototype.h @@ -0,0 +1,161 @@ +#pragma once + +#include "ErbPitchPrototype.h" + +#include +#include +#include + +namespace dessmetal::experiments::transpose +{ +// Evaluation-only two-resolution extension. A broad filter bank supplies the +// first part of detected attacks while the normal bank continuously builds its +// cleaner steady-state response. This mirrors the transient/body split suggested +// by measured commercial octave-pedal responses without copying proprietary DSP. +class HybridErbPitchPrototype +{ +public: + using MathMode = ErbPitchPrototype::MathMode; + static constexpr int kMinSemitones = ErbPitchPrototype::kMinSemitones; + static constexpr int kMaxSemitones = ErbPitchPrototype::kMaxSemitones; + static constexpr int kDefaultBandCount = ErbPitchPrototype::kDefaultBandCount; + + bool Reset(const double sampleRate, const int maxBlockSize, const MathMode mathMode) + { + mConfigured = false; + if (!std::isfinite(sampleRate) || sampleRate < 8000.0 || maxBlockSize <= 0) + return false; + if (!mQuality.Reset(sampleRate, maxBlockSize, mathMode, kDefaultBandCount, 19.0, 0.5) + || !mFast.Reset(sampleRate, maxBlockSize, mathMode, kDefaultBandCount, 19.0, 2.0)) + return false; + + mQualityOutput.assign(static_cast(maxBlockSize), 0.0); + mFastOutput.assign(static_cast(maxBlockSize), 0.0); + mSampleRate = sampleRate; + mFastAttackCoefficient = Coefficient(0.0005); + mFastReleaseCoefficient = Coefficient(0.010); + mSlowAttackCoefficient = Coefficient(0.020); + mSlowReleaseCoefficient = Coefficient(0.100); + mBlendReleaseCoefficient = Coefficient(0.015); + mTransientHighpassCoefficient = std::exp(-2.0 * 3.14159265358979323846 * 1200.0 / sampleRate); + mHoldDurationSamples = std::max(1, static_cast(std::lround(0.008 * sampleRate))); + mFastEnvelope = 0.0; + mSlowEnvelope = 0.0; + mTransientBlend = 0.0; + mPreviousInput = 0.0; + mHighpassPreviousInput = 0.0; + mTransientHighpass = 0.0; + mHoldSamplesRemaining = 0; + mDetectorArmed = true; + mConfigured = true; + return true; + } + + void Process(const double* input, double* output, const int numFrames, const int semitones) + { + if (output == nullptr || numFrames <= 0) + return; + if (!mConfigured || input == nullptr || numFrames > static_cast(mQualityOutput.size())) + { + std::fill(output, output + numFrames, 0.0); + return; + } + + const int clampedSemitones = std::clamp(semitones, kMinSemitones, kMaxSemitones); + mQuality.Process(input, mQualityOutput.data(), numFrames, clampedSemitones); + mFast.Process(input, mFastOutput.data(), numFrames, clampedSemitones); + + const double positiveShift = std::max(clampedSemitones, 0) / 12.0; + const double positiveShiftSquared = positiveShift * positiveShift; + const double fastGain = 1.0 + 5.0 * positiveShiftSquared * positiveShiftSquared; + constexpr double qualityGain = 2.8; + for (int frame = 0; frame < numFrames; ++frame) + { + // A slew envelope reacts to pick edges but is much less likely than a raw + // amplitude envelope to retrigger on the normal beating inside a chord. + const double onsetMagnitude = std::abs(input[frame] - mPreviousInput); + mPreviousInput = input[frame]; + mFastEnvelope = Follow(onsetMagnitude, mFastEnvelope, + onsetMagnitude > mFastEnvelope ? mFastAttackCoefficient + : mFastReleaseCoefficient); + mSlowEnvelope = Follow(onsetMagnitude, mSlowEnvelope, + onsetMagnitude > mSlowEnvelope ? mSlowAttackCoefficient + : mSlowReleaseCoefficient); + + if (mDetectorArmed && mFastEnvelope > 1.0e-5 + && mFastEnvelope > std::max(3.0 * mSlowEnvelope, 2.0e-5)) + { + mTransientBlend = 1.0; + mHoldSamplesRemaining = mHoldDurationSamples; + mDetectorArmed = false; + } + if (!mDetectorArmed && (mFastEnvelope < 1.25 * mSlowEnvelope || mSlowEnvelope < 1.0e-6)) + mDetectorArmed = true; + + if (mHoldSamplesRemaining > 0) + { + --mHoldSamplesRemaining; + mTransientBlend = 1.0; + } + else + { + mTransientBlend *= mBlendReleaseCoefficient; + if (mTransientBlend < 1.0e-6) + mTransientBlend = 0.0; + } + + mTransientHighpass = mTransientHighpassCoefficient + * (mTransientHighpass + input[frame] - mHighpassPreviousInput); + mHighpassPreviousInput = input[frame]; + + if (clampedSemitones == 0) + { + output[frame] = input[frame]; + continue; + } + const double quality = qualityGain * mQualityOutput[static_cast(frame)]; + const double fast = fastGain * mFastOutput[static_cast(frame)]; + constexpr double transientHighpassGain = 0.65; + output[frame] = mTransientBlend * (fast + transientHighpassGain * mTransientHighpass) + + (1.0 - mTransientBlend) * quality; + } + } + + bool IsConfigured() const { return mConfigured; } + int GetLatencySamples() const { return 0; } + int GetBandCount() const { return mQuality.GetBandCount(); } + +private: + double Coefficient(const double seconds) const + { + return std::exp(-1.0 / std::max(seconds * mSampleRate, 1.0)); + } + + static double Follow(const double input, const double state, const double coefficient) + { + return input + coefficient * (state - input); + } + + ErbPitchPrototype mQuality; + ErbPitchPrototype mFast; + std::vector mQualityOutput; + std::vector mFastOutput; + double mSampleRate = 48000.0; + double mFastAttackCoefficient = 0.0; + double mFastReleaseCoefficient = 0.0; + double mSlowAttackCoefficient = 0.0; + double mSlowReleaseCoefficient = 0.0; + double mBlendReleaseCoefficient = 0.0; + double mTransientHighpassCoefficient = 0.0; + double mFastEnvelope = 0.0; + double mSlowEnvelope = 0.0; + double mTransientBlend = 0.0; + double mPreviousInput = 0.0; + double mHighpassPreviousInput = 0.0; + double mTransientHighpass = 0.0; + int mHoldDurationSamples = 0; + int mHoldSamplesRemaining = 0; + bool mDetectorArmed = true; + bool mConfigured = false; +}; +} // namespace dessmetal::experiments::transpose diff --git a/NeuralAmpModeler/experiments/transpose/README.md b/NeuralAmpModeler/experiments/transpose/README.md new file mode 100644 index 0000000..fd91a07 --- /dev/null +++ b/NeuralAmpModeler/experiments/transpose/README.md @@ -0,0 +1,113 @@ +# DessMetal transpose-engine evaluation + +Status: **production implementation selected and integrated** + +Evaluation date: 2026-08-03 + +Branch: `codex/transpose-engine-spike` + +Base commit: `176ed27a77a8073ff4cde1c55bef4ad6ad5332a5` + +## Outcome + +DessMetal now has a self-contained, real-time polyphonic transpose processor +covering every integer semitone from `-12` through `+12`. It is implemented in +[`TransposeProcessor.h`](../../TransposeProcessor.h), has no runtime dependency +on a proprietary SDK, allocates no memory in `Process()`, adds no buffered +look-ahead, and returns the exact dry samples after the transition back to zero. + +The selected design is an ERB-spaced analytic filter bank derived from Steven +Schulteis' MIT-licensed Terrarium Poly Pitch work. DessMetal adds a second, +wider-band transient path, onset-controlled blending, phase-continuous pitch +automation, finite-value recovery, and an 8 ms wet/dry transition. The original +license is preserved in `licenses/terrarium-poly-octave-MIT.txt` and the +attribution is listed in `THIRD_PARTY_NOTICES.md`. + +This is not a copy of Neural DSP code. Neural DSP was used only as a black-box +product reference for range, interaction, and rendered A/B evaluation. + +## Why this engine + +The first spike tested common permissive and platform alternatives. They can +produce good offline or high-latency pitch shifting, but their live modes did +not meet this project's combination of octave range, polyphonic guitar input, +and low latency. The filter-bank approach was the strongest open foundation and +was small enough to harden directly inside DessMetal. + +| Candidate | Result in this evaluation | Decision | +|---|---|---| +| DessMetal hybrid ERB processor | Zero buffered latency; exact target carrier in the production sine gates; allocation-free and block-invariant render path; onset gate below 10 ms | **Selected** | +| Signalsmith Stretch 1.3.2 (MIT) | Stable and allocation-free at a 1024-sample setup, but low-string octave tests produced dominant sidebands or mistuning | Rejected; not retained in the production tree | +| Bungee Basic 2.4.24 (MPL-2.0) | Supported configurations were roughly 93–235 ms in the spike; unsupported low-granularity settings reduced latency but degraded quality | Rejected | +| Apple NewTimePitch / AUPitch | Correct pitch but measured roughly 85 ms / 128 ms and would be macOS-only | Rejected | +| Rubber Band LiveShifter / SoundTouch | Published live/typical delays are outside the target for direct guitar monitoring | Rejected | + +Primary open references: + +- [Terrarium Poly Pitch arbitrary-shift branch](https://github.com/schult/terrarium-poly-octave/tree/arbitrary-shift) +- [Low-Latency Polyphonic Pitch-Shifting of Guitar Signals (Aalto thesis)](https://aaltodoc.aalto.fi/items/6fd2cfc9-db61-4b0a-b11f-ea8c2925509f) +- [Latenzoptimierte Tonhoehenverschiebung (HAW Hamburg thesis)](https://reposit.haw-hamburg.de/bitstream/20.500.12738/15713/1/MA_Latenzoptimierte%20Tonh%C3%B6henverschiebung.pdf) +- [IDMT-SMT-Guitar direct-input dataset](https://zenodo.org/records/4988354) + +## Production signal path + +The processor runs after input calibration, sanitization, and mono collapse, +before the drive, gate detector, NAM amp, tone stack, and cabinet IR. This lets +the virtual amp react to the retuned guitar rather than shifting the already +distorted output. + +`Transpose` is parameter ID 20, appended after the historical 20 parameters so +all earlier IDs remain unchanged. Version `0.2.x` state contains 21 parameters; +all accepted `0.1.x` and legacy layouts migrate with `Transpose = 0`. The fifth +historical hidden amp state remains untouched for host compatibility. + +The UI exposes a large `minus | value | plus` control. It uses integer steps, +shows signed values, and resets to zero on double-click. Host automation glides +the pitch ratio and wet mix over 8 ms to avoid abrupt phase or sample jumps. + +## Reproducible gates + +Run the production processor tests: + +```sh +bash NeuralAmpModeler/tests/run_transpose_processor_tests.sh +``` + +The suite covers: + +- bit-exact zero bypass and return-to-zero settling; +- target-carrier accuracy at every integer shift at 48 kHz; +- finite, non-silent, bounded output at every shift at 44.1, 48, 88.2, and 96 kHz; +- standard guitar open strings at both octave extremes; +- fixed and irregular host block equivalence; +- sub-10 ms half-level onset gates at the four frequency/shift extremes; +- bounded automation discontinuity, silence, and NaN/Inf recovery; and +- zero tracked allocations across repeated render blocks and automation. + +Run state-layout compatibility tests: + +```sh +bash NeuralAmpModeler/tests/run_unserialization_layout_tests.sh +``` + +Run the retained ERB research benchmark: + +```sh +bash NeuralAmpModeler/experiments/transpose/run_erb_benchmark.sh +``` + +The baseline ERB benchmark on the development M1 Max reported 83 bands, zero +buffered samples, about 5.6% of one real-time core, exact single-sine octave +carriers, and chord target SNR from about 9.0 to 15.4 dB. Those screening +numbers are useful for regression, but they are not a listening-quality claim. +The production processor uses two such banks and adds transient blending, so +the plug-in and host tests are the authoritative gates. + +## Remaining human gate + +Automated tests can establish pitch, stability, latency behavior, state +compatibility, and finite/non-silent output. They cannot certify feel or tone. +Before merge, audition the exact staged AU in the disposable Logic demo project +on clean DI single notes, palm-muted chugs, power/open chords, bends, slides, +pick transients, and decays. Test every integer shift, with special attention to +`-12`, `-7`, `-5`, `+5`, `+7`, and `+12`, and compare at matched loudness. diff --git a/NeuralAmpModeler/experiments/transpose/benchmark_erb.cpp b/NeuralAmpModeler/experiments/transpose/benchmark_erb.cpp new file mode 100644 index 0000000..50f8678 --- /dev/null +++ b/NeuralAmpModeler/experiments/transpose/benchmark_erb.cpp @@ -0,0 +1,612 @@ +#include "ErbPitchPrototype.h" +#include "HybridErbPitchPrototype.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +std::atomic gTrackAllocations{false}; +std::atomic gAllocationCount{0}; + +constexpr double kSampleRate = 48000.0; +constexpr int kMaxBlockSize = 512; +constexpr int kRenderFrames = 72000; +constexpr int kAnalysisStart = 36000; +constexpr int kAnalysisLength = 24000; +constexpr double kPi = 3.14159265358979323846; + +using ErbPrototype = dessmetal::experiments::transpose::ErbPitchPrototype; +using HybridPrototype = dessmetal::experiments::transpose::HybridErbPitchPrototype; + +bool gUseHybrid = false; + +class BenchmarkPrototype +{ +public: + using MathMode = ErbPrototype::MathMode; + static constexpr int kDefaultBandCount = ErbPrototype::kDefaultBandCount; + + bool Reset(const double sampleRate, const int maxBlockSize, const MathMode mathMode, + const int bandCount = kDefaultBandCount, const double density = 19.0, + const double bandwidthScale = 1.0, const double lowBandwidthScale = 0.0, + const double transitionHz = 300.0, const bool phaseCompensation = false, + const int dominanceExponent = 0) + { + mHybrid = gUseHybrid; + if (mHybrid) + return mHybridProcessor.Reset(sampleRate, maxBlockSize, mathMode); + return mErbProcessor.Reset(sampleRate, maxBlockSize, mathMode, bandCount, density, + bandwidthScale, lowBandwidthScale, transitionHz, + phaseCompensation, dominanceExponent); + } + + void Process(const double* input, double* output, const int frames, const int semitones) + { + if (mHybrid) + mHybridProcessor.Process(input, output, frames, semitones); + else + mErbProcessor.Process(input, output, frames, semitones); + } + + bool IsConfigured() const + { + return mHybrid ? mHybridProcessor.IsConfigured() : mErbProcessor.IsConfigured(); + } + int GetLatencySamples() const + { + return mHybrid ? mHybridProcessor.GetLatencySamples() : mErbProcessor.GetLatencySamples(); + } + int GetBandCount() const + { + return mHybrid ? mHybridProcessor.GetBandCount() : mErbProcessor.GetBandCount(); + } + +private: + ErbPrototype mErbProcessor; + HybridPrototype mHybridProcessor; + bool mHybrid = false; +}; + +using Prototype = BenchmarkPrototype; + +int gBandCount = Prototype::kDefaultBandCount; +double gDensity = 19.0; +double gBandwidthScale = 1.0; +double gLowBandwidthScale = 0.0; +double gBandwidthTransitionHz = 300.0; +bool gCompensateFilterPhase = false; +int gDominanceExponent = 0; + +bool ResetProcessor(Prototype& processor, const Prototype::MathMode mathMode) +{ + return processor.Reset(kSampleRate, kMaxBlockSize, mathMode, gBandCount, gDensity, gBandwidthScale, + gLowBandwidthScale, gBandwidthTransitionHz, gCompensateFilterPhase, + gDominanceExponent); +} + +struct Measurement +{ + double inputHz = 0.0; + int semitones = 0; + double expectedHz = 0.0; + double dominantHz = 0.0; + double errorCents = 0.0; + double carrierDeficitDb = 0.0; + double outputRms = 0.0; +}; + +struct ChordMeasurement +{ + int semitones = 0; + double targetSnrDb = 0.0; + double outputRms = 0.0; +}; + +struct OnsetMeasurement +{ + double inputHz = 0.0; + int semitones = 0; + int tenPercentSample = 0; + int fiftyPercentSample = 0; +}; + +void Require(const bool condition, const char* message) +{ + if (!condition) + throw std::runtime_error(message); +} + +Prototype::MathMode ParseMathMode(const std::string& name) +{ + if (name == "embedded") + return Prototype::MathMode::kEmbeddedApproximation; + if (name == "balanced") + return Prototype::MathMode::kBalancedApproximation; + if (name == "accurate") + return Prototype::MathMode::kAccurate; + throw std::runtime_error("unknown math mode: " + name); +} + +const char* MathModeName(const Prototype::MathMode mode) +{ + switch (mode) + { + case Prototype::MathMode::kEmbeddedApproximation: return "embedded"; + case Prototype::MathMode::kBalancedApproximation: return "balanced"; + case Prototype::MathMode::kAccurate: return "accurate"; + } + return "unknown"; +} + +std::vector RenderSine(const double inputFrequency, const int semitones, + const std::vector& blockPattern, const Prototype::MathMode mathMode, + const int renderFrames = kRenderFrames) +{ + Prototype processor; + Require(ResetProcessor(processor, mathMode), "processor reset failed"); + std::vector rendered(static_cast(renderFrames)); + std::vector input(kMaxBlockSize); + double phase = 0.0; + int frame = 0; + std::size_t patternIndex = 0; + while (frame < renderFrames) + { + const int frames = std::min(blockPattern[patternIndex++ % blockPattern.size()], renderFrames - frame); + for (int index = 0; index < frames; ++index) + { + input[static_cast(index)] = 0.2 * std::sin(phase); + phase += 2.0 * kPi * inputFrequency / kSampleRate; + if (phase >= 2.0 * kPi) + phase -= 2.0 * kPi; + } + processor.Process(input.data(), rendered.data() + frame, frames, semitones); + frame += frames; + } + return rendered; +} + +std::vector WindowAnalysis(const std::vector& rendered) +{ + std::vector result(kAnalysisLength); + for (int index = 0; index < kAnalysisLength; ++index) + { + const double hann = 0.5 - 0.5 * std::cos(2.0 * kPi * index / (kAnalysisLength - 1)); + result[static_cast(index)] = + rendered[static_cast(kAnalysisStart + index)] * hann; + } + return result; +} + +double MagnitudeAt(const std::vector& samples, const double frequency) +{ + std::complex sum{0.0, 0.0}; + const std::complex rotation = std::polar(1.0, -2.0 * kPi * frequency / kSampleRate); + std::complex oscillator{1.0, 0.0}; + for (const double sample : samples) + { + sum += sample * oscillator; + oscillator *= rotation; + } + return std::abs(sum) / samples.size(); +} + +void FourierTransform(std::vector>& values) +{ + const std::size_t size = values.size(); + Require(size > 0 && (size & (size - 1)) == 0, "FFT size must be a power of two"); + for (std::size_t index = 1, reversed = 0; index < size; ++index) + { + std::size_t bit = size >> 1; + while (reversed & bit) + { + reversed ^= bit; + bit >>= 1; + } + reversed ^= bit; + if (index < reversed) + std::swap(values[index], values[reversed]); + } + + for (std::size_t length = 2; length <= size; length <<= 1) + { + const std::complex step = std::polar(1.0, -2.0 * kPi / static_cast(length)); + for (std::size_t offset = 0; offset < size; offset += length) + { + std::complex rotation{1.0, 0.0}; + for (std::size_t index = 0; index < length / 2; ++index) + { + const std::complex even = values[offset + index]; + const std::complex odd = values[offset + index + length / 2] * rotation; + values[offset + index] = even + odd; + values[offset + index + length / 2] = even - odd; + rotation *= step; + } + } + } +} + +std::vector> GuitarChordPartials() +{ + const std::vector fundamentals{82.4069, 123.471, 164.814, 195.998, 246.942, 329.628}; + std::vector> partials; + for (std::size_t stringIndex = 0; stringIndex < fundamentals.size(); ++stringIndex) + { + for (int harmonic = 1; harmonic <= 16; ++harmonic) + { + const double frequency = fundamentals[stringIndex] * harmonic; + if (frequency >= 9000.0) + break; + const double stringBalance = 1.0 - 0.06 * static_cast(stringIndex); + const double amplitude = stringBalance / std::pow(static_cast(harmonic), 1.15); + partials.emplace_back(frequency, amplitude); + } + } + return partials; +} + +std::vector RenderChord(const int semitones, const Prototype::MathMode mathMode, + const int renderFrames = 96000) +{ + const auto partials = GuitarChordPartials(); + std::vector phases(partials.size(), 0.0); + for (std::size_t index = 0; index < phases.size(); ++index) + phases[index] = std::fmod(0.754877666 * static_cast(index * index + 1), 1.0) * 2.0 * kPi; + + Prototype processor; + Require(ResetProcessor(processor, mathMode), "processor reset failed"); + std::vector rendered(static_cast(renderFrames)); + std::vector input(kMaxBlockSize); + int frame = 0; + while (frame < renderFrames) + { + const int frames = std::min(kMaxBlockSize, renderFrames - frame); + for (int index = 0; index < frames; ++index) + { + double sample = 0.0; + for (std::size_t partial = 0; partial < partials.size(); ++partial) + { + sample += partials[partial].second * std::sin(phases[partial]); + phases[partial] += 2.0 * kPi * partials[partial].first / kSampleRate; + if (phases[partial] >= 2.0 * kPi) + phases[partial] -= 2.0 * kPi; + } + input[static_cast(index)] = sample * 0.0125; + } + processor.Process(input.data(), rendered.data() + frame, frames, semitones); + frame += frames; + } + return rendered; +} + +ChordMeasurement MeasureChord(const int semitones, const Prototype::MathMode mathMode) +{ + constexpr int fftSize = 32768; + const auto rendered = RenderChord(semitones, mathMode); + std::vector> spectrum(fftSize); + const int start = static_cast(rendered.size()) - fftSize; + double outputEnergy = 0.0; + for (int index = 0; index < fftSize; ++index) + { + const double sample = rendered[static_cast(start + index)]; + const double hann = 0.5 - 0.5 * std::cos(2.0 * kPi * index / (fftSize - 1)); + spectrum[static_cast(index)] = sample * hann; + outputEnergy += sample * sample; + } + FourierTransform(spectrum); + + std::vector expectedBins(static_cast(fftSize / 2 + 1), false); + const double scale = std::pow(2.0, semitones / 12.0); + for (const auto& [frequency, amplitude] : GuitarChordPartials()) + { + (void) amplitude; + const double shiftedFrequency = frequency * scale; + if (shiftedFrequency < 20.0 || shiftedFrequency >= kSampleRate * 0.495) + continue; + const int centerBin = static_cast(std::lround(shiftedFrequency * fftSize / kSampleRate)); + for (int bin = std::max(centerBin - 2, 1); bin <= std::min(centerBin + 2, fftSize / 2); ++bin) + expectedBins[static_cast(bin)] = true; + } + + double targetPower = 0.0; + double residualPower = 0.0; + for (int bin = 1; bin <= fftSize / 2; ++bin) + { + const double frequency = static_cast(bin) * kSampleRate / fftSize; + if (frequency < 20.0) + continue; + const double power = std::norm(spectrum[static_cast(bin)]); + if (expectedBins[static_cast(bin)]) + targetPower += power; + else + residualPower += power; + } + + ChordMeasurement result; + result.semitones = semitones; + result.targetSnrDb = 10.0 * std::log10(std::max(targetPower, 1.0e-30) + / std::max(residualPower, 1.0e-30)); + result.outputRms = std::sqrt(outputEnergy / fftSize); + return result; +} + +OnsetMeasurement MeasureOnset(const double inputFrequency, const int semitones, + const Prototype::MathMode mathMode) +{ + constexpr int onsetSample = 1024; + constexpr int frameCount = 24000; + constexpr int windowSize = 48; + Prototype processor; + Require(ResetProcessor(processor, mathMode), "processor reset failed"); + std::vector input(frameCount, 0.0); + std::vector output(frameCount, 0.0); + double phase = 0.0; + for (int frame = onsetSample; frame < frameCount; ++frame) + { + const double ramp = std::min(1.0, static_cast(frame - onsetSample) / 24.0); + input[static_cast(frame)] = 0.2 * ramp * std::sin(phase); + phase += 2.0 * kPi * inputFrequency / kSampleRate; + if (phase >= 2.0 * kPi) + phase -= 2.0 * kPi; + } + for (int offset = 0; offset < frameCount; offset += kMaxBlockSize) + processor.Process(input.data() + offset, output.data() + offset, + std::min(kMaxBlockSize, frameCount - offset), semitones); + + double steadyEnergy = 0.0; + for (int frame = frameCount - 4096; frame < frameCount; ++frame) + steadyEnergy += output[static_cast(frame)] * output[static_cast(frame)]; + const double steadyRms = std::sqrt(steadyEnergy / 4096.0); + + int tenPercentSample = frameCount - onsetSample; + int fiftyPercentSample = frameCount - onsetSample; + for (int frame = onsetSample; frame <= frameCount - windowSize; ++frame) + { + double windowEnergy = 0.0; + for (int index = 0; index < windowSize; ++index) + { + const double sample = output[static_cast(frame + index)]; + windowEnergy += sample * sample; + } + const double rms = std::sqrt(windowEnergy / windowSize); + if (tenPercentSample == frameCount - onsetSample && rms >= steadyRms * 0.1) + tenPercentSample = frame - onsetSample; + if (fiftyPercentSample == frameCount - onsetSample && rms >= steadyRms * 0.5) + { + fiftyPercentSample = frame - onsetSample; + break; + } + } + + return {inputFrequency, semitones, tenPercentSample, fiftyPercentSample}; +} + +Measurement Measure(const double inputFrequency, const int semitones, const Prototype::MathMode mathMode) +{ + const auto rendered = RenderSine(inputFrequency, semitones, {31, 64, 127, 256, 511}, mathMode); + Require(std::all_of(rendered.begin(), rendered.end(), [](const double x) { return std::isfinite(x); }), + "processor produced a non-finite sample"); + const auto analysis = WindowAnalysis(rendered); + const double expected = inputFrequency * std::pow(2.0, semitones / 12.0); + const double carrierMagnitude = MagnitudeAt(analysis, expected); + double dominantFrequency = expected; + double dominantMagnitude = 0.0; + for (double cents = -300.0; cents <= 300.0; cents += 1.0) + { + const double frequency = expected * std::pow(2.0, cents / 1200.0); + const double magnitude = MagnitudeAt(analysis, frequency); + if (magnitude > dominantMagnitude) + { + dominantMagnitude = magnitude; + dominantFrequency = frequency; + } + } + + double energy = 0.0; + for (const double sample : analysis) + energy += sample * sample; + + Measurement result; + result.inputHz = inputFrequency; + result.semitones = semitones; + result.expectedHz = expected; + result.dominantHz = dominantFrequency; + result.errorCents = 1200.0 * std::log2(dominantFrequency / expected); + result.carrierDeficitDb = 20.0 * std::log10(std::max(carrierMagnitude, 1.0e-15) + / std::max(dominantMagnitude, 1.0e-15)); + result.outputRms = std::sqrt(energy / analysis.size()) / std::sqrt(0.375); + return result; +} + +double MeasureRealtimeCpuPercent(const Prototype::MathMode mathMode) +{ + Prototype processor; + Require(ResetProcessor(processor, mathMode), "processor reset failed"); + std::vector input(kMaxBlockSize, 0.0); + std::vector output(kMaxBlockSize, 0.0); + for (int frame = 0; frame < kMaxBlockSize; ++frame) + { + const double time = frame / kSampleRate; + input[static_cast(frame)] = 0.08 * std::sin(2.0 * kPi * 82.4069 * time) + + 0.05 * std::sin(2.0 * kPi * 123.471 * time) + + 0.03 * std::sin(2.0 * kPi * 329.628 * time); + } + constexpr int frames = static_cast(kSampleRate * 5.0); + const auto started = std::chrono::steady_clock::now(); + for (int offset = 0; offset < frames; offset += kMaxBlockSize) + processor.Process(input.data(), output.data(), std::min(kMaxBlockSize, frames - offset), -7); + const double elapsed = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); + return elapsed / 5.0 * 100.0; +} + +void RunFunctionalChecks(const Prototype::MathMode mathMode) +{ + Prototype processor; + Require(!processor.Reset(0.0, kMaxBlockSize, mathMode), "invalid sample rate was accepted"); + Require(!processor.Reset(kSampleRate, 0, mathMode), "invalid block size was accepted"); + Require(ResetProcessor(processor, mathMode), "valid reset failed"); + Require(processor.IsConfigured(), "processor did not become configured"); + Require(processor.GetLatencySamples() == 0, "unexpected buffered latency"); + Require(processor.GetBandCount() == gBandCount, "unexpected band count"); + + std::vector input(kMaxBlockSize, 0.1); + std::vector output(kMaxBlockSize, 0.0); + processor.Process(input.data(), output.data(), kMaxBlockSize, 0); + gAllocationCount.store(0, std::memory_order_relaxed); + gTrackAllocations.store(true, std::memory_order_release); + for (int block = 0; block < 128; ++block) + processor.Process(input.data(), output.data(), kMaxBlockSize, (block % 25) - 12); + gTrackAllocations.store(false, std::memory_order_release); + Require(gAllocationCount.load(std::memory_order_relaxed) == 0, "render path allocated memory"); + + constexpr int blockCheckFrames = 8192; + const auto fixedBlocks = RenderSine(110.0, -5, {512}, mathMode, blockCheckFrames); + const auto varyingBlocks = RenderSine(110.0, -5, {31, 64, 127, 256, 511}, mathMode, blockCheckFrames); + double maximumDifference = 0.0; + for (std::size_t index = 0; index < fixedBlocks.size(); ++index) + maximumDifference = std::max(maximumDifference, std::abs(fixedBlocks[index] - varyingBlocks[index])); + Require(maximumDifference == 0.0, "output depends on host block boundaries"); +} +} // namespace + +void* operator new(const std::size_t size) +{ + if (gTrackAllocations.load(std::memory_order_relaxed)) + gAllocationCount.fetch_add(1, std::memory_order_relaxed); + if (void* memory = std::malloc(size)) + return memory; + throw std::bad_alloc(); +} + +void operator delete(void* memory) noexcept { std::free(memory); } +void operator delete(void* memory, std::size_t) noexcept { std::free(memory); } + +int main(int argc, char** argv) +{ + try + { + Prototype::MathMode mathMode = Prototype::MathMode::kBalancedApproximation; + bool functionalOnly = false; + for (int index = 1; index < argc; ++index) + { + const std::string argument(argv[index]); + if (argument == "--functional-only") + functionalOnly = true; + else if (argument == "--hybrid") + gUseHybrid = true; + else if (argument.rfind("--math=", 0) == 0) + mathMode = ParseMathMode(argument.substr(7)); + else if (argument.rfind("--bands=", 0) == 0) + gBandCount = std::stoi(argument.substr(8)); + else if (argument.rfind("--density=", 0) == 0) + gDensity = std::stod(argument.substr(10)); + else if (argument.rfind("--bandwidth-scale=", 0) == 0) + gBandwidthScale = std::stod(argument.substr(18)); + else if (argument.rfind("--low-bandwidth-scale=", 0) == 0) + gLowBandwidthScale = std::stod(argument.substr(22)); + else if (argument.rfind("--bandwidth-transition=", 0) == 0) + gBandwidthTransitionHz = std::stod(argument.substr(23)); + else if (argument == "--compensate-filter-phase") + gCompensateFilterPhase = true; + else if (argument.rfind("--dominance-exponent=", 0) == 0) + gDominanceExponent = std::stoi(argument.substr(21)); + else + throw std::runtime_error("unknown argument: " + argument); + } + + RunFunctionalChecks(mathMode); + if (functionalOnly) + { + std::cout << "engine=erb math=" << MathModeName(mathMode) << " functional_gate=PASS\n"; + return 0; + } + + const std::vector openStringHz{82.4069, 110.0, 146.832, 195.998, 246.942, 329.628}; + const std::vector shifts{-12, 12}; + bool qualityPassed = true; + std::cout << std::fixed << std::setprecision(3); + std::cout << "engine=" << (gUseHybrid ? "hybrid-erb" : "erb") + << " math=" << MathModeName(mathMode) << " bands=" << gBandCount + << " density=" << gDensity << " bandwidth_scale=" << gBandwidthScale + << " low_bandwidth_scale=" << gLowBandwidthScale + << " bandwidth_transition_hz=" << gBandwidthTransitionHz + << " phase_compensation=" << (gCompensateFilterPhase ? "on" : "off") + << " dominance_exponent=" << gDominanceExponent << '\n'; + std::cout << "input_hz,semitones,expected_hz,dominant_hz,error_cents,carrier_deficit_db,output_rms\n"; + for (const double inputFrequency : openStringHz) + { + for (const int semitones : shifts) + { + const auto result = Measure(inputFrequency, semitones, mathMode); + std::cout << result.inputHz << ',' << result.semitones << ',' << result.expectedHz << ',' + << result.dominantHz << ',' << result.errorCents << ',' << result.carrierDeficitDb << ',' + << result.outputRms << '\n'; + qualityPassed = qualityPassed && std::abs(result.errorCents) <= 5.0 && result.carrierDeficitDb >= -3.0; + } + } + + double maximumIntermediatePitchError = 0.0; + double worstIntermediateCarrierDeficit = 0.0; + int worstPitchShift = 0; + int worstCarrierShift = 0; + for (int semitones = -12; semitones <= 12; ++semitones) + { + if (semitones == -12 || semitones == 12) + continue; + const auto result = Measure(110.0, semitones, mathMode); + if (std::abs(result.errorCents) > maximumIntermediatePitchError) + { + maximumIntermediatePitchError = std::abs(result.errorCents); + worstPitchShift = semitones; + } + if (result.carrierDeficitDb < worstIntermediateCarrierDeficit) + { + worstIntermediateCarrierDeficit = result.carrierDeficitDb; + worstCarrierShift = semitones; + } + } + std::cout << "intermediate_a2_max_abs_error_cents=" << maximumIntermediatePitchError + << " shift=" << worstPitchShift + << " worst_carrier_deficit_db=" << worstIntermediateCarrierDeficit + << " shift=" << worstCarrierShift << '\n'; + + std::cout << "chord_shift,target_snr_db,output_rms\n"; + for (const int semitones : std::vector{-12, -7, 7, 12}) + { + const auto result = MeasureChord(semitones, mathMode); + std::cout << result.semitones << ',' << result.targetSnrDb << ',' << result.outputRms << '\n'; + } + + std::cout << "onset_input_hz,semitones,ten_percent_samples,fifty_percent_samples," + "ten_percent_ms,fifty_percent_ms\n"; + for (const auto [inputFrequency, semitones] : + std::vector>{{82.4069, -12}, {82.4069, 12}, {329.628, -12}, {329.628, 12}}) + { + const auto result = MeasureOnset(inputFrequency, semitones, mathMode); + std::cout << result.inputHz << ',' << result.semitones << ',' << result.tenPercentSample << ',' + << result.fiftyPercentSample << ',' << result.tenPercentSample * 1000.0 / kSampleRate << ',' + << result.fiftyPercentSample * 1000.0 / kSampleRate << '\n'; + } + + std::cout << "buffered_latency_samples=0 band_count=" << gBandCount + << " realtime_cpu_percent=" << MeasureRealtimeCpuPercent(mathMode) << '\n'; + std::cout << "functional_gate=PASS sine_quality_gate=" << (qualityPassed ? "PASS" : "FAIL") << '\n'; + return qualityPassed ? 0 : 2; + } + catch (const std::exception& error) + { + std::cerr << "benchmark error: " << error.what() << '\n'; + return 1; + } +} diff --git a/NeuralAmpModeler/experiments/transpose/render_erb_audio.sh b/NeuralAmpModeler/experiments/transpose/render_erb_audio.sh new file mode 100644 index 0000000..6e7ed3a --- /dev/null +++ b/NeuralAmpModeler/experiments/transpose/render_erb_audio.sh @@ -0,0 +1,30 @@ +#!/bin/sh +set -eu + +if [ "$#" -lt 3 ] || [ "$#" -gt 8 ]; then + echo "usage: $0 input-audio output-wav semitones [bandwidth-scale [low-bandwidth-scale [transition-hz [dominance-exponent [engine]]]]]" >&2 + exit 64 +fi + +input_path=$1 +output_path=$2 +semitones=$3 +bandwidth_scale=${4:-1.0} +low_bandwidth_scale=${5:-0.0} +transition_hz=${6:-300.0} +dominance_exponent=${7:-0} +engine=${8:-erb} +script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +render_dir=$(mktemp -d "${TMPDIR:-/tmp}/dessmetal-erb-render.XXXXXX") +trap 'rm -rf "$render_dir"' EXIT HUP INT TERM + +sample_rate=$(ffprobe -v error -select_streams a:0 -show_entries stream=sample_rate \ + -of default=noprint_wrappers=1:nokey=1 "$input_path") +ffmpeg -v error -y -i "$input_path" -map 0:a:0 -ac 1 -f f64le "$render_dir/input.f64le" +c++ -std=c++17 -O3 -DNDEBUG -Wall -Wextra -Wpedantic \ + "$script_dir/render_erb_file.cpp" -o "$render_dir/render_erb_file" +"$render_dir/render_erb_file" "$render_dir/input.f64le" "$render_dir/output.f64le" \ + "$sample_rate" "$semitones" "$bandwidth_scale" "$low_bandwidth_scale" "$transition_hz" \ + "$dominance_exponent" "$engine" +ffmpeg -v error -y -f f64le -ar "$sample_rate" -ac 1 -i "$render_dir/output.f64le" \ + -c:a pcm_s24le "$output_path" diff --git a/NeuralAmpModeler/experiments/transpose/render_erb_file.cpp b/NeuralAmpModeler/experiments/transpose/render_erb_file.cpp new file mode 100644 index 0000000..d7ffa69 --- /dev/null +++ b/NeuralAmpModeler/experiments/transpose/render_erb_file.cpp @@ -0,0 +1,112 @@ +#include "ErbPitchPrototype.h" +#include "HybridErbPitchPrototype.h" +#include "../../TransposeProcessor.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +using Prototype = dessmetal::experiments::transpose::ErbPitchPrototype; +using HybridPrototype = dessmetal::experiments::transpose::HybridErbPitchPrototype; +using ProductionProcessor = dessmetal::transpose::Processor; + +void Require(const bool condition, const char* message) +{ + if (!condition) + throw std::runtime_error(message); +} + +std::vector ReadRawDoubles(const std::string& path) +{ + std::ifstream input(path, std::ios::binary | std::ios::ate); + Require(input.good(), "could not open raw input"); + const std::streamsize byteCount = input.tellg(); + Require(byteCount >= 0 && byteCount % static_cast(sizeof(double)) == 0, + "raw input size is invalid"); + input.seekg(0); + std::vector samples(static_cast(byteCount / sizeof(double))); + input.read(reinterpret_cast(samples.data()), byteCount); + Require(input.good(), "could not read raw input"); + return samples; +} + +void WriteRawDoubles(const std::string& path, const std::vector& samples) +{ + std::ofstream output(path, std::ios::binary); + Require(output.good(), "could not open raw output"); + output.write(reinterpret_cast(samples.data()), + static_cast(samples.size() * sizeof(double))); + Require(output.good(), "could not write raw output"); +} +} // namespace + +int main(int argc, char** argv) +{ + try + { + if (argc < 5 || argc > 10) + throw std::runtime_error( + "usage: render_erb_file input.f64le output.f64le sample-rate semitones " + "[bandwidth-scale [low-bandwidth-scale [transition-hz [dominance-exponent [engine]]]]]"); + + const std::string inputPath = argv[1]; + const std::string outputPath = argv[2]; + const double sampleRate = std::stod(argv[3]); + const int semitones = std::stoi(argv[4]); + const double bandwidthScale = argc >= 6 ? std::stod(argv[5]) : 1.0; + const double lowBandwidthScale = argc >= 7 ? std::stod(argv[6]) : 0.0; + const double transitionHz = argc >= 8 ? std::stod(argv[7]) : 300.0; + const int dominanceExponent = argc >= 9 ? std::stoi(argv[8]) : 0; + const std::string engine = argc >= 10 ? argv[9] : "erb"; + Require(engine == "erb" || engine == "hybrid" || engine == "production", + "engine must be erb, hybrid, or production"); + + auto input = ReadRawDoubles(inputPath); + std::vector output(input.size(), 0.0); + Prototype processor; + HybridPrototype hybridProcessor; + ProductionProcessor productionProcessor; + constexpr int blockSize = 512; + const bool reset = engine == "production" + ? productionProcessor.Reset(sampleRate, semitones) + : (engine == "hybrid" + ? hybridProcessor.Reset(sampleRate, blockSize, + Prototype::MathMode::kBalancedApproximation) + : processor.Reset(sampleRate, blockSize, + Prototype::MathMode::kBalancedApproximation, + Prototype::kDefaultBandCount, 19.0, bandwidthScale, + lowBandwidthScale, transitionHz, false, + dominanceExponent)); + Require(reset, "processor reset failed"); + for (std::size_t offset = 0; offset < input.size(); offset += blockSize) + { + const int frames = static_cast(std::min(blockSize, input.size() - offset)); + if (engine == "production") + productionProcessor.Process(input.data() + offset, output.data() + offset, frames, semitones); + else if (engine == "hybrid") + hybridProcessor.Process(input.data() + offset, output.data() + offset, frames, semitones); + else + processor.Process(input.data() + offset, output.data() + offset, frames, semitones); + } + Require(std::all_of(output.begin(), output.end(), [](const double sample) { return std::isfinite(sample); }), + "processor produced a non-finite output"); + WriteRawDoubles(outputPath, output); + std::cout << "rendered_samples=" << output.size() << " sample_rate=" << sampleRate + << " semitones=" << semitones << " bandwidth_scale=" << bandwidthScale + << " low_bandwidth_scale=" << lowBandwidthScale << " transition_hz=" << transitionHz + << " dominance_exponent=" << dominanceExponent << " engine=" << engine << '\n'; + return 0; + } + catch (const std::exception& error) + { + std::cerr << "render error: " << error.what() << '\n'; + return 1; + } +} diff --git a/NeuralAmpModeler/experiments/transpose/render_reference_au.cpp b/NeuralAmpModeler/experiments/transpose/render_reference_au.cpp new file mode 100644 index 0000000..9c180c1 --- /dev/null +++ b/NeuralAmpModeler/experiments/transpose/render_reference_au.cpp @@ -0,0 +1,210 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +void Require(const bool condition, const char* message) +{ + if (!condition) + throw std::runtime_error(message); +} + +void Check(const OSStatus status, const char* operation) +{ + if (status != noErr) + throw std::runtime_error(std::string(operation) + " failed with OSStatus " + std::to_string(status)); +} + +std::vector ReadRawFloats(const std::string& path) +{ + std::ifstream input(path, std::ios::binary | std::ios::ate); + Require(input.good(), "could not open raw input"); + const std::streamsize byteCount = input.tellg(); + Require(byteCount >= 0 && byteCount % static_cast(sizeof(float)) == 0, + "raw input size is invalid"); + input.seekg(0); + std::vector samples(static_cast(byteCount / sizeof(float))); + input.read(reinterpret_cast(samples.data()), byteCount); + Require(input.good(), "could not read raw input"); + return samples; +} + +void WriteRawFloats(const std::string& path, const std::vector& samples) +{ + std::ofstream output(path, std::ios::binary); + Require(output.good(), "could not open raw output"); + output.write(reinterpret_cast(samples.data()), + static_cast(samples.size() * sizeof(float))); + Require(output.good(), "could not write raw output"); +} + +struct InputContext +{ + const std::vector* samples = nullptr; + std::size_t callbackCount = 0; + float peak = 0.0f; +}; + +OSStatus InputCallback(void* userData, AudioUnitRenderActionFlags* flags, + const AudioTimeStamp* timestamp, UInt32, UInt32 frameCount, + AudioBufferList* buffers) +{ + auto& context = *static_cast(userData); + ++context.callbackCount; + const std::size_t start = timestamp->mSampleTime >= 0.0 + ? static_cast(timestamp->mSampleTime) + : 0; + bool silent = true; + for (UInt32 bufferIndex = 0; bufferIndex < buffers->mNumberBuffers; ++bufferIndex) + { + auto* destination = static_cast(buffers->mBuffers[bufferIndex].mData); + for (UInt32 frame = 0; frame < frameCount; ++frame) + { + const std::size_t sourceIndex = start + frame; + const float sample = sourceIndex < context.samples->size() ? (*context.samples)[sourceIndex] : 0.0f; + destination[frame] = sample; + context.peak = std::max(context.peak, std::abs(sample)); + silent = silent && sample == 0.0f; + } + buffers->mBuffers[bufferIndex].mDataByteSize = frameCount * sizeof(float); + } + if (silent) + *flags |= kAudioUnitRenderAction_OutputIsSilence; + return noErr; +} + +struct StereoBufferList +{ + UInt32 numberBuffers = 2; + AudioBuffer buffers[2]{}; +}; +} // namespace + +int main(int argc, char** argv) +{ + AudioUnit unit = nullptr; + try + { + if (argc != 5 && argc != 6) + throw std::runtime_error( + "usage: render_reference_au input.f32le output.f32le sample-rate semitones [section-mask]"); + const std::string inputPath = argv[1]; + const std::string outputPath = argv[2]; + const double sampleRate = std::stod(argv[3]); + const int semitones = std::stoi(argv[4]); + const int sectionMask = argc == 6 ? std::stoi(argv[5]) : 31; + Require(semitones >= -12 && semitones <= 12, "semitones must be between -12 and +12"); + auto input = ReadRawFloats(inputPath); + std::vector output(input.size(), 0.0f); + + AudioComponentDescription description{}; + description.componentType = 'aumf'; + description.componentSubType = 'FNMX'; + description.componentManufacturer = 'NDSP'; + AudioComponent component = AudioComponentFindNext(nullptr, &description); + Require(component != nullptr, "Fortin Nameless Suite X Audio Unit was not found"); + Check(AudioComponentInstanceNew(component, &unit), "AudioComponentInstanceNew"); + + constexpr UInt32 blockSize = 512; + UInt32 maximumFrames = blockSize; + Check(AudioUnitSetProperty(unit, kAudioUnitProperty_MaximumFramesPerSlice, + kAudioUnitScope_Global, 0, &maximumFrames, sizeof(maximumFrames)), + "set maximum frames"); + + AudioStreamBasicDescription format{}; + format.mSampleRate = sampleRate; + format.mFormatID = kAudioFormatLinearPCM; + format.mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked + | kAudioFormatFlagIsNonInterleaved | kAudioFormatFlagsNativeEndian; + format.mBytesPerPacket = sizeof(float); + format.mFramesPerPacket = 1; + format.mBytesPerFrame = sizeof(float); + format.mChannelsPerFrame = 2; + format.mBitsPerChannel = 8 * sizeof(float); + Check(AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, 0, &format, sizeof(format)), + "set input format"); + Check(AudioUnitSetProperty(unit, kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Output, 0, &format, sizeof(format)), + "set output format"); + + InputContext inputContext{&input}; + AURenderCallbackStruct callback{InputCallback, &inputContext}; + Check(AudioUnitSetProperty(unit, kAudioUnitProperty_SetRenderCallback, + kAudioUnitScope_Input, 0, &callback, sizeof(callback)), + "set input callback"); + + // Leave only the input transpose module active. These are public Audio Unit + // parameters observed from the installed reference plug-in; no proprietary + // code or state is read or copied. + const std::vector> settings{ + {0, 0.5f}, // Input Gain (unity) + {1, 0.5f}, // Output Gain (unity) + {2, 0.0f}, // Gate + {4, static_cast(semitones + 12) / 24.0f}, + {5, 0.0f}, // Doubler + {7, (sectionMask & 1) != 0 ? 1.0f : 0.0f}, + {16, (sectionMask & 2) != 0 ? 1.0f : 0.0f}, + {26, (sectionMask & 4) != 0 ? 1.0f : 0.0f}, + {47, (sectionMask & 8) != 0 ? 1.0f : 0.0f}, + {59, (sectionMask & 16) != 0 ? 1.0f : 0.0f} + }; + Check(AudioUnitInitialize(unit), "AudioUnitInitialize"); + for (const auto [identifier, value] : settings) + Check(AudioUnitSetParameter(unit, identifier, kAudioUnitScope_Global, 0, value, 0), "set parameter"); + std::vector left(blockSize, 0.0f); + std::vector right(blockSize, 0.0f); + for (std::size_t offset = 0; offset < output.size(); offset += blockSize) + { + const UInt32 frames = static_cast(std::min(blockSize, output.size() - offset)); + StereoBufferList storage; + storage.buffers[0] = {1, frames * static_cast(sizeof(float)), left.data()}; + storage.buffers[1] = {1, frames * static_cast(sizeof(float)), right.data()}; + AudioTimeStamp timestamp{}; + timestamp.mFlags = kAudioTimeStampSampleTimeValid; + timestamp.mSampleTime = static_cast(offset); + AudioUnitRenderActionFlags flags = 0; + Check(AudioUnitRender(unit, &flags, ×tamp, 0, frames, + reinterpret_cast(&storage)), + "AudioUnitRender"); + std::copy(left.begin(), left.begin() + frames, output.begin() + static_cast(offset)); + } + + Float64 reportedLatencySeconds = 0.0; + UInt32 latencySize = sizeof(reportedLatencySeconds); + Check(AudioUnitGetProperty(unit, kAudioUnitProperty_Latency, kAudioUnitScope_Global, 0, + &reportedLatencySeconds, &latencySize), + "get latency"); + float outputPeak = 0.0f; + for (const float sample : output) + outputPeak = std::max(outputPeak, std::abs(sample)); + AudioUnitParameterValue transposeReadback = 0.0f; + Check(AudioUnitGetParameter(unit, 4, kAudioUnitScope_Global, 0, &transposeReadback), + "get transpose parameter"); + WriteRawFloats(outputPath, output); + std::cout << "rendered_samples=" << output.size() << " sample_rate=" << sampleRate + << " semitones=" << semitones + << " section_mask=" << sectionMask + << " reported_latency_samples=" << reportedLatencySeconds * sampleRate + << " callbacks=" << inputContext.callbackCount << " input_peak=" << inputContext.peak + << " output_peak=" << outputPeak << " transpose_readback=" << transposeReadback << '\n'; + AudioUnitUninitialize(unit); + AudioComponentInstanceDispose(unit); + return 0; + } + catch (const std::exception& error) + { + if (unit != nullptr) + AudioComponentInstanceDispose(unit); + std::cerr << "reference render error: " << error.what() << '\n'; + return 1; + } +} diff --git a/NeuralAmpModeler/experiments/transpose/render_reference_au.sh b/NeuralAmpModeler/experiments/transpose/render_reference_au.sh new file mode 100644 index 0000000..e453544 --- /dev/null +++ b/NeuralAmpModeler/experiments/transpose/render_reference_au.sh @@ -0,0 +1,25 @@ +#!/bin/sh +set -eu + +if [ "$#" -lt 3 ] || [ "$#" -gt 4 ]; then + echo "usage: $0 input-audio output-wav semitones [section-mask]" >&2 + exit 64 +fi + +input_path=$1 +output_path=$2 +semitones=$3 +section_mask=${4:-31} +script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +render_dir=$(mktemp -d "${TMPDIR:-/tmp}/dessmetal-reference-render.XXXXXX") +trap 'rm -rf "$render_dir"' EXIT HUP INT TERM + +sample_rate=$(ffprobe -v error -select_streams a:0 -show_entries stream=sample_rate \ + -of default=noprint_wrappers=1:nokey=1 "$input_path") +ffmpeg -v error -y -i "$input_path" -map 0:a:0 -ac 1 -f f32le "$render_dir/input.f32le" +clang++ -std=c++17 -O2 -Wall -Wextra -Wpedantic "$script_dir/render_reference_au.cpp" \ + -framework AudioToolbox -o "$render_dir/render_reference_au" +"$render_dir/render_reference_au" "$render_dir/input.f32le" "$render_dir/output.f32le" \ + "$sample_rate" "$semitones" "$section_mask" +ffmpeg -v error -y -f f32le -ar "$sample_rate" -ac 1 -i "$render_dir/output.f32le" \ + -c:a pcm_s24le "$output_path" diff --git a/NeuralAmpModeler/experiments/transpose/run_erb_benchmark.sh b/NeuralAmpModeler/experiments/transpose/run_erb_benchmark.sh new file mode 100644 index 0000000..4df80e1 --- /dev/null +++ b/NeuralAmpModeler/experiments/transpose/run_erb_benchmark.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu + +script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +build_dir=$(mktemp -d "${TMPDIR:-/tmp}/dessmetal-erb-benchmark.XXXXXX") +trap 'rm -rf "$build_dir"' EXIT HUP INT TERM + +c++ -std=c++17 -O3 -DNDEBUG -Wall -Wextra -Wpedantic \ + "$script_dir/benchmark_erb.cpp" -o "$build_dir/benchmark_erb" +"$build_dir/benchmark_erb" "$@" diff --git a/NeuralAmpModeler/installer/DessMetal.iss b/NeuralAmpModeler/installer/DessMetal.iss index 237a9c5..41943c4 100644 --- a/NeuralAmpModeler/installer/DessMetal.iss +++ b/NeuralAmpModeler/installer/DessMetal.iss @@ -5,8 +5,8 @@ AppCopyright=Copyright (C) 2026 Alexander Dess AppPublisher=Alexander Dess AppPublisherURL=https://github.com/appdess/dessmetal AppSupportURL=https://github.com/appdess/dessmetal/issues -AppVersion=0.1.1 -VersionInfoVersion=0.1.1 +AppVersion=0.2.0 +VersionInfoVersion=0.2.0 DefaultDirName={pf}\DessMetal DefaultGroupName=DessMetal Compression=lzma2 diff --git a/NeuralAmpModeler/installer/intro.rtf b/NeuralAmpModeler/installer/intro.rtf index c4a9609..030e6c5 100644 --- a/NeuralAmpModeler/installer/intro.rtf +++ b/NeuralAmpModeler/installer/intro.rtf @@ -1,5 +1,5 @@ {\rtf1\ansi\deff0{\fonttbl{\f0 Helvetica;}} -\f0\fs28\b Welcome to DessMetal 0.1.1\b0\fs24\par +\f0\fs28\b Welcome to DessMetal 0.2.0\b0\fs24\par \par This installer contains the universal macOS standalone application, Audio Unit v2, and VST3 plug-in.\par \par diff --git a/NeuralAmpModeler/projects/DessMetal-macOS.xcodeproj/project.pbxproj b/NeuralAmpModeler/projects/DessMetal-macOS.xcodeproj/project.pbxproj index 78a083f..d414a4c 100644 --- a/NeuralAmpModeler/projects/DessMetal-macOS.xcodeproj/project.pbxproj +++ b/NeuralAmpModeler/projects/DessMetal-macOS.xcodeproj/project.pbxproj @@ -3338,7 +3338,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_IDENTITY = ""; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DSTROOT = "$(VST2_PATH)"; GCC_PREPROCESSOR_DEFINITIONS = ( @@ -3349,7 +3349,7 @@ ); INFOPLIST_FILE = "../resources/DessMetal-VST2-Info.plist"; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; PRODUCT_BUNDLE_IDENTIFIER = "com.AlexanderDess.vst.${BINARY_NAME}"; SKIP_INSTALL = NO; WARNING_CFLAGS = "-Wno-main"; @@ -3362,7 +3362,7 @@ buildSettings = { CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; DSTROOT = "$(VST2_PATH)"; @@ -3374,7 +3374,7 @@ ); INFOPLIST_FILE = "../resources/DessMetal-VST2-Info.plist"; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; PRODUCT_BUNDLE_IDENTIFIER = "com.AlexanderDess.vst.${BINARY_NAME}"; PROVISIONING_PROFILE_SPECIFIER = ""; SKIP_INSTALL = NO; @@ -3387,7 +3387,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_IDENTITY = ""; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DSTROOT = "$(VST2_PATH)"; GCC_PREPROCESSOR_DEFINITIONS = ( @@ -3398,7 +3398,7 @@ ); INFOPLIST_FILE = "../resources/DessMetal-VST2-Info.plist"; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; PRODUCT_BUNDLE_IDENTIFIER = "com.AlexanderDess.vst.${BINARY_NAME}"; SKIP_INSTALL = NO; WARNING_CFLAGS = "-Wno-main"; @@ -3423,7 +3423,7 @@ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; CODE_SIGN_ENTITLEMENTS = "DessMetal-macOS.entitlements"; CODE_SIGN_IDENTITY = "Mac Developer"; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_HARDENED_RUNTIME = YES; @@ -3440,7 +3440,7 @@ "@executable_path/../../iPlug2/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; MTL_ENABLE_DEBUG_INFO = YES; OTHER_LDFLAGS = "$(inherited)"; PRODUCT_BUNDLE_IDENTIFIER = com.AlexanderDess.app.DessMetal.AUv3; @@ -3470,7 +3470,7 @@ CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Manual; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; ENABLE_HARDENED_RUNTIME = YES; @@ -3488,7 +3488,7 @@ "@executable_path/../../iPlug2/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; MTL_ENABLE_DEBUG_INFO = NO; OTHER_LDFLAGS = "$(inherited)"; PRODUCT_BUNDLE_IDENTIFIER = com.AlexanderDess.app.DessMetal.AUv3; @@ -3517,7 +3517,7 @@ CODE_SIGN_ENTITLEMENTS = "DessMetal-macOS.entitlements"; CODE_SIGN_IDENTITY = "Mac Developer"; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; ENABLE_HARDENED_RUNTIME = YES; ENABLE_NS_ASSERTIONS = NO; @@ -3534,7 +3534,7 @@ "@executable_path/../../iPlug2/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; MTL_ENABLE_DEBUG_INFO = NO; OTHER_LDFLAGS = "$(inherited)"; PRODUCT_BUNDLE_IDENTIFIER = com.AlexanderDess.app.DessMetal.AUv3; @@ -3550,7 +3550,7 @@ buildSettings = { CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; DSTROOT = "$(AU_PATH)"; @@ -3562,7 +3562,7 @@ ); INFOPLIST_FILE = "../resources/DessMetal-AU-Info.plist"; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; OTHER_LDFLAGS = ( "$(AU_FRAMEWORKS)", "$(inherited)", @@ -3584,7 +3584,7 @@ buildSettings = { CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; DSTROOT = "$(AU_PATH)"; @@ -3596,7 +3596,7 @@ ); INFOPLIST_FILE = "../resources/DessMetal-AU-Info.plist"; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; OTHER_LDFLAGS = ( "$(AU_FRAMEWORKS)", "$(inherited)", @@ -3618,7 +3618,7 @@ buildSettings = { CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; DSTROOT = "$(AU_PATH)"; @@ -3630,7 +3630,7 @@ ); INFOPLIST_FILE = "../resources/DessMetal-AU-Info.plist"; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; OTHER_LDFLAGS = ( "$(AU_FRAMEWORKS)", "$(inherited)", @@ -3963,7 +3963,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_IDENTITY = ""; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; "DEVELOPMENT_TEAM[sdk=macosx*]" = 77BKRC84G3; DSTROOT = "$(VST3_PATH)"; @@ -3979,7 +3979,7 @@ ); INFOPLIST_FILE = "../resources/DessMetal-VST3-Info.plist"; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; PRODUCT_BUNDLE_IDENTIFIER = "com.AlexanderDess.vst3.${BINARY_NAME}"; SKIP_INSTALL = NO; WRAPPER_EXTENSION = vst3; @@ -3991,7 +3991,7 @@ buildSettings = { CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = ""; DSTROOT = "$(VST3_PATH)"; @@ -4007,7 +4007,7 @@ ); INFOPLIST_FILE = "../resources/DessMetal-VST3-Info.plist"; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; PRODUCT_BUNDLE_IDENTIFIER = "com.AlexanderDess.vst3.${BINARY_NAME}"; PROVISIONING_PROFILE_SPECIFIER = ""; SKIP_INSTALL = NO; @@ -4019,7 +4019,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_IDENTITY = ""; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DSTROOT = "$(VST3_PATH)"; GCC_PREPROCESSOR_DEFINITIONS = ( @@ -4034,7 +4034,7 @@ ); INFOPLIST_FILE = "../resources/DessMetal-VST3-Info.plist"; MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; PRODUCT_BUNDLE_IDENTIFIER = "com.AlexanderDess.vst3.${BINARY_NAME}"; SKIP_INSTALL = NO; WRAPPER_EXTENSION = vst3; @@ -4051,7 +4051,7 @@ CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = NO; CLANG_WARN__EXIT_TIME_DESTRUCTORS = NO; CODE_SIGN_IDENTITY = ""; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DEPLOYMENT_LOCATION = YES; DSTROOT = "$(AAX_PATH)"; @@ -4092,7 +4092,7 @@ "$(AAX_SDK)/Libs/Debug", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; PRODUCT_BUNDLE_IDENTIFIER = "com.AlexanderDess.aax.${BINARY_NAME}"; SDKROOT = "$(BASE_SDK_MAC)"; SKIP_INSTALL = NO; @@ -4117,7 +4117,7 @@ CLANG_WARN__EXIT_TIME_DESTRUCTORS = NO; CODE_SIGN_IDENTITY = ""; CODE_SIGN_STYLE = Manual; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEPLOYMENT_LOCATION = YES; @@ -4161,7 +4161,7 @@ "$(AAX_SDK)/Libs/Release", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; OTHER_LDFLAGS = ( "$(EXTRA_LNK_FLAGS)", "$(ALL_FRAMEWORKS)", @@ -4194,7 +4194,7 @@ CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = NO; CLANG_WARN__EXIT_TIME_DESTRUCTORS = NO; CODE_SIGN_IDENTITY = ""; - CURRENT_PROJECT_VERSION = 0.1.1; + CURRENT_PROJECT_VERSION = 0.2.0; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; DEPLOYMENT_LOCATION = YES; @@ -4237,7 +4237,7 @@ "$(AAX_SDK)/Libs/Release", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 0.1.1; + MARKETING_VERSION = 0.2.0; OTHER_LDFLAGS = ( "$(EXTRA_LNK_FLAGS)", "$(EXTRA_ALL_FRAMEWORKS)", diff --git a/NeuralAmpModeler/resources/DessMetal-AAX-Info.plist b/NeuralAmpModeler/resources/DessMetal-AAX-Info.plist index 4f9b21b..2164bfa 100755 --- a/NeuralAmpModeler/resources/DessMetal-AAX-Info.plist +++ b/NeuralAmpModeler/resources/DessMetal-AAX-Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable DessMetal CFBundleGetInfoString - DessMetal v0.1.1 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson + DessMetal v0.2.0 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson CFBundleIdentifier com.AlexanderDess.aax.DessMetal CFBundleInfoDictionaryVersion @@ -17,11 +17,11 @@ CFBundlePackageType TDMw CFBundleShortVersionString - 0.1.1 + 0.2.0 CFBundleSignature PTul CFBundleVersion - 0.1.1 + 0.2.0 CSResourcesFileMapped LSMinimumSystemVersion diff --git a/NeuralAmpModeler/resources/DessMetal-AU-Info.plist b/NeuralAmpModeler/resources/DessMetal-AU-Info.plist index 166406c..d876b42 100644 --- a/NeuralAmpModeler/resources/DessMetal-AU-Info.plist +++ b/NeuralAmpModeler/resources/DessMetal-AU-Info.plist @@ -20,17 +20,17 @@ type aufx version - 257 + 512 AudioUnit Version - 0x000101 + 0x000200 CFBundleDevelopmentRegion English CFBundleExecutable DessMetal CFBundleGetInfoString - DessMetal v0.1.1 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson + DessMetal v0.2.0 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson CFBundleIdentifier com.AlexanderDess.audiounit.DessMetal CFBundleInfoDictionaryVersion @@ -40,11 +40,11 @@ CFBundlePackageType BNDL CFBundleShortVersionString - 0.1.1 + 0.2.0 CFBundleSignature 1YEo CFBundleVersion - 0.1.1 + 0.2.0 CSResourcesFileMapped LSMinimumSystemVersion diff --git a/NeuralAmpModeler/resources/DessMetal-VST2-Info.plist b/NeuralAmpModeler/resources/DessMetal-VST2-Info.plist index 69fc518..c533ac5 100644 --- a/NeuralAmpModeler/resources/DessMetal-VST2-Info.plist +++ b/NeuralAmpModeler/resources/DessMetal-VST2-Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable DessMetal CFBundleGetInfoString - DessMetal v0.1.1 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson + DessMetal v0.2.0 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson CFBundleIdentifier com.AlexanderDess.vst.DessMetal CFBundleInfoDictionaryVersion @@ -17,11 +17,11 @@ CFBundlePackageType BNDL CFBundleShortVersionString - 0.1.1 + 0.2.0 CFBundleSignature 1YEo CFBundleVersion - 0.1.1 + 0.2.0 CSResourcesFileMapped LSMinimumSystemVersion diff --git a/NeuralAmpModeler/resources/DessMetal-VST3-Info.plist b/NeuralAmpModeler/resources/DessMetal-VST3-Info.plist index 18917ce..3c22a5d 100644 --- a/NeuralAmpModeler/resources/DessMetal-VST3-Info.plist +++ b/NeuralAmpModeler/resources/DessMetal-VST3-Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable DessMetal CFBundleGetInfoString - DessMetal v0.1.1 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson + DessMetal v0.2.0 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson CFBundleIdentifier com.AlexanderDess.vst3.DessMetal CFBundleInfoDictionaryVersion @@ -17,11 +17,11 @@ CFBundlePackageType BNDL CFBundleShortVersionString - 0.1.1 + 0.2.0 CFBundleSignature 1YEo CFBundleVersion - 0.1.1 + 0.2.0 CSResourcesFileMapped LSMinimumSystemVersion diff --git a/NeuralAmpModeler/resources/DessMetal-macOS-AUv3-Info.plist b/NeuralAmpModeler/resources/DessMetal-macOS-AUv3-Info.plist index 7dc297b..7358d56 100644 --- a/NeuralAmpModeler/resources/DessMetal-macOS-AUv3-Info.plist +++ b/NeuralAmpModeler/resources/DessMetal-macOS-AUv3-Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable DessMetal CFBundleGetInfoString - DessMetal v0.1.1 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson + DessMetal v0.2.0 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson CFBundleIdentifier com.AlexanderDess.app.DessMetal.AUv3 CFBundleInfoDictionaryVersion @@ -17,9 +17,9 @@ CFBundlePackageType XPC! CFBundleShortVersionString - 0.1.1 + 0.2.0 CFBundleVersion - 0.1.1 + 0.2.0 LSMinimumSystemVersion 10.12.0 NSExtension @@ -48,7 +48,7 @@ type aufx version - 257 + 512 diff --git a/NeuralAmpModeler/resources/DessMetal-macOS-AUv3Framework-Info.plist b/NeuralAmpModeler/resources/DessMetal-macOS-AUv3Framework-Info.plist index f17c9c7..60ad938 100644 --- a/NeuralAmpModeler/resources/DessMetal-macOS-AUv3Framework-Info.plist +++ b/NeuralAmpModeler/resources/DessMetal-macOS-AUv3Framework-Info.plist @@ -15,8 +15,8 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 0.1.1 + 0.2.0 CFBundleVersion - 0.1.1 + 0.2.0 diff --git a/NeuralAmpModeler/resources/DessMetal-macOS-Info.plist b/NeuralAmpModeler/resources/DessMetal-macOS-Info.plist index 2ed07c7..5a51038 100644 --- a/NeuralAmpModeler/resources/DessMetal-macOS-Info.plist +++ b/NeuralAmpModeler/resources/DessMetal-macOS-Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable DessMetal CFBundleGetInfoString - DessMetal v0.1.1 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson + DessMetal v0.2.0 Copyright 2026 Alexander Dess; Original content Copyright Steven Atkinson CFBundleIconFile AppIcon CFBundleIdentifier @@ -19,11 +19,11 @@ CFBundlePackageType APPL CFBundleShortVersionString - 0.1.1 + 0.2.0 CFBundleSignature 1YEo CFBundleVersion - 0.1.1 + 0.2.0 CSResourcesFileMapped LSApplicationCategoryType diff --git a/NeuralAmpModeler/tests/run_transpose_processor_tests.sh b/NeuralAmpModeler/tests/run_transpose_processor_tests.sh new file mode 100755 index 0000000..e3f9103 --- /dev/null +++ b/NeuralAmpModeler/tests/run_transpose_processor_tests.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +source_file="$repo_root/NeuralAmpModeler/tests/test_transpose_processor.cpp" +build_dir="${TMPDIR:-/tmp}/dessmetal-transpose-processor-test" +binary="$build_dir/test_transpose_processor" + +mkdir -p "$build_dir" +clang++ -std=c++17 -O3 -DNDEBUG -Wall -Wextra -Werror "$source_file" -o "$binary" +"$binary" diff --git a/NeuralAmpModeler/tests/test_au_state_migration.mm b/NeuralAmpModeler/tests/test_au_state_migration.mm index c1ad458..4c977b1 100644 --- a/NeuralAmpModeler/tests/test_au_state_migration.mm +++ b/NeuralAmpModeler/tests/test_au_state_migration.mm @@ -12,7 +12,7 @@ { constexpr UInt32 kDessMetalSubtype = '1YEo'; constexpr UInt32 kDessMetalManufacturer = 'AdMs'; -constexpr std::size_t kCurrentParameterCount = 20; +constexpr std::size_t kCurrentParameterCount = 21; template void AppendNative(std::vector& bytes, const T& value) @@ -79,7 +79,7 @@ OSStatus ApplyState(AudioUnit unit, const std::string& version, const std::vecto CFMutableDictionaryRef dictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - SetDictionaryNumber(dictionary, kAUPresetVersionKey, 0x000101); + SetDictionaryNumber(dictionary, kAUPresetVersionKey, 0x000200); SetDictionaryNumber(dictionary, kAUPresetTypeKey, static_cast(kAudioUnitType_Effect)); SetDictionaryNumber(dictionary, kAUPresetSubtypeKey, static_cast(kDessMetalSubtype)); SetDictionaryNumber(dictionary, kAUPresetManufacturerKey, static_cast(kDessMetalManufacturer)); @@ -170,7 +170,7 @@ int main() }; const std::array expectedLegacy{ -3.0, 8.0, -45.0, 2.0, 3.0, 4.0, -2.0, 0.0, 5.0, 0.0, - 1.0, 0.0, 5.0, 0.0, 0.0, 0.0, 10.0, 0.0, 2.0, 1.0, + 1.0, 0.0, 5.0, 0.0, 0.0, 0.0, 10.0, 0.0, 2.0, 1.0, 0.0, }; // Existing 20-value states were also mislabeled 0.1.0 and must remain exact. @@ -180,7 +180,7 @@ int main() }; const std::array expectedCurrent010{ -1.0, 7.0, -55.0, 6.0, 5.0, 4.0, 1.0, -4.0, 8.0, 1.0, - 0.0, 1.0, 7.0, 1.0, 3.0, 1.0, 11.0, 0.0, 4.0, 0.0, + 0.0, 1.0, 7.0, 1.0, 3.0, 1.0, 11.0, 0.0, 4.0, 0.0, 0.0, }; // 0.1.1 establishes the unambiguous current layout. @@ -190,7 +190,16 @@ int main() }; const std::array expectedCurrent011{ 2.0, 3.0, -65.0, 4.0, 5.0, 6.0, -3.0, 2.0, 1.0, 0.0, - 1.0, 0.0, 4.0, 0.0, 2.0, 0.0, 12.0, 0.0, 0.0, 1.0, + 1.0, 0.0, 4.0, 0.0, 2.0, 0.0, 12.0, 0.0, 0.0, 1.0, 0.0, + }; + + const std::vector current020{ + 1.0, 6.0, -60.0, 5.0, 4.0, 3.0, -1.0, 1.0, 5.0, 1.0, + 0.0, 1.0, 6.0, 1.0, 1.0, 0.0, 12.0, 0.0, 4.0, 1.0, -7.0, + }; + const std::array expectedCurrent020{ + 1.0, 6.0, -60.0, 5.0, 4.0, 3.0, -1.0, 1.0, 5.0, 1.0, + 0.0, 1.0, 6.0, 1.0, 1.0, 0.0, 12.0, 0.0, 4.0, 1.0, -7.0, }; // Unsupported historical custom slots depended on path-based loading, which @@ -205,9 +214,11 @@ int main() "current 20-value 0.1.0") && ExpectAppliedState(unit, "0.1.1", current011, expectedCurrent011, "current 20-value 0.1.1") - && ExpectRejectedState(unit, "0.1.0", unsupportedLegacyCustom, expectedCurrent011, + && ExpectAppliedState(unit, "0.2.0", current020, expectedCurrent020, + "current 21-value 0.2.0") + && ExpectRejectedState(unit, "0.1.0", unsupportedLegacyCustom, expectedCurrent020, "unsupported legacy custom amp") - && ExpectRejectedState(unit, "0.1.0", unsupportedWip18, expectedCurrent011, + && ExpectRejectedState(unit, "0.1.0", unsupportedWip18, expectedCurrent020, "unsupported 18-value WIP layout"); AudioComponentInstanceDispose(unit); @@ -215,6 +226,7 @@ int main() return 1; std::cout << "DessMetal AU state migration passed: legacy14, current20@0.1.0, current20@0.1.1, " + "current21@0.2.0, " "atomic rejection for legacy custom and WIP18\n"; return 0; } diff --git a/NeuralAmpModeler/tests/test_transpose_processor.cpp b/NeuralAmpModeler/tests/test_transpose_processor.cpp new file mode 100644 index 0000000..338a3dc --- /dev/null +++ b/NeuralAmpModeler/tests/test_transpose_processor.cpp @@ -0,0 +1,381 @@ +#include "../TransposeProcessor.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +std::atomic gTrackAllocations{false}; +std::atomic gAllocationCount{0}; + +constexpr double kPi = 3.14159265358979323846; + +void Require(const bool condition, const char* message) +{ + if (!condition) + throw std::runtime_error(message); +} + +double ToneMagnitude(const std::vector& signal, const int start, const int length, + const double frequency, const double sampleRate) +{ + double real = 0.0; + double imaginary = 0.0; + double windowSum = 0.0; + for (int index = 0; index < length; ++index) + { + const double window = 0.5 - 0.5 * std::cos(2.0 * kPi * index / (length - 1)); + const double angle = 2.0 * kPi * frequency * index / sampleRate; + const double sample = signal[static_cast(start + index)] * window; + real += sample * std::cos(angle); + imaginary -= sample * std::sin(angle); + windowSum += window; + } + return 2.0 * std::hypot(real, imaginary) / windowSum; +} + +std::vector RenderSine(const double sampleRate, const double frequency, const int semitones, + const std::vector& blockPattern) +{ + constexpr int seconds = 2; + const int frames = static_cast(sampleRate) * seconds; + dessmetal::transpose::Processor processor; + Require(processor.Reset(sampleRate, semitones), "valid reset failed"); + std::vector input(static_cast(frames)); + std::vector output(static_cast(frames)); + for (int frame = 0; frame < frames; ++frame) + input[static_cast(frame)] = 0.2 * std::sin(2.0 * kPi * frequency * frame / sampleRate); + + int offset = 0; + std::size_t patternIndex = 0; + while (offset < frames) + { + const int block = std::min(blockPattern[patternIndex++ % blockPattern.size()], frames - offset); + processor.Process(input.data() + offset, output.data() + offset, block, semitones); + offset += block; + } + return output; +} + +void TestConfigurationAndBypass() +{ + dessmetal::transpose::Processor processor; + Require(!processor.Reset(std::numeric_limits::quiet_NaN()), "NaN sample rate accepted"); + Require(!processor.Reset(7999.0), "too-low sample rate accepted"); + Require(processor.Reset(48000.0), "48 kHz reset failed"); + Require(processor.IsConfigured(), "processor not configured"); + Require(processor.GetLatencySamples() == 0, "unexpected buffered latency"); + Require(processor.GetBandCount() == dessmetal::transpose::Processor::kBandCount, + "unexpected band count"); + + std::vector input(4096); + std::vector output(input.size()); + for (std::size_t index = 0; index < input.size(); ++index) + input[index] = 0.3 * std::sin(0.013 * static_cast(index)) + + 0.1 * std::cos(0.031 * static_cast(index)); + processor.Process(input.data(), output.data(), static_cast(input.size()), 0); + Require(input == output, "zero-semitone bypass is not bit exact"); + + processor.ProcessInPlace(input.data(), static_cast(input.size()), 0); + Require(input == output, "in-place zero-semitone bypass changed samples"); +} + +void TestPitchAccuracyAndBlockInvariance() +{ + constexpr double sampleRate = 48000.0; + constexpr double frequencies[]{82.407, 110.0, 146.832, 195.998, 246.942, 329.628}; + constexpr int shifts[]{-12, 12}; + for (const double frequency : frequencies) + { + for (const int semitones : shifts) + { + const auto fixed = RenderSine(sampleRate, frequency, semitones, {512}); + const auto irregular = RenderSine(sampleRate, frequency, semitones, {1, 17, 64, 3, 255, 31, 128}); + Require(fixed == irregular, "render changed with host block partitioning"); + + const int analysisLength = 24000; + const int analysisStart = static_cast(fixed.size()) - analysisLength; + const double expected = frequency * std::pow(2.0, semitones / 12.0); + const double target = ToneMagnitude(fixed, analysisStart, analysisLength, expected, sampleRate); + double strongest = 0.0; + double dominant = expected; + for (double candidate = expected * 0.85; candidate <= expected * 1.15; candidate += 0.25) + { + const double magnitude = ToneMagnitude(fixed, analysisStart, analysisLength, candidate, sampleRate); + if (magnitude > strongest) + { + strongest = magnitude; + dominant = candidate; + } + } + const double cents = 1200.0 * std::log2(dominant / expected); + const double deficitDb = 20.0 * std::log10(std::max(strongest, 1.0e-15) + / std::max(target, 1.0e-15)); + Require(std::abs(cents) <= 6.0, "dominant pitch missed the target by more than 6 cents"); + Require(deficitDb <= 3.0, "target carrier is more than 3 dB below a nearby component"); + } + } +} + +void TestEveryIntegerShift() +{ + constexpr double sampleRate = 48000.0; + constexpr double inputFrequency = 146.832; + constexpr int frames = 48000; + constexpr int analysisLength = 24000; + + for (int semitones = -12; semitones <= 12; ++semitones) + { + dessmetal::transpose::Processor processor; + Require(processor.Reset(sampleRate, semitones), "integer-shift reset failed"); + std::vector buffer(frames); + for (int frame = 0; frame < frames; ++frame) + buffer[static_cast(frame)] = + 0.2 * std::sin(2.0 * kPi * inputFrequency * frame / sampleRate); + + for (int offset = 0; offset < frames; offset += 257) + processor.ProcessInPlace(buffer.data() + offset, std::min(257, frames - offset), semitones); + + const double expected = inputFrequency * std::pow(2.0, semitones / 12.0); + const double target = ToneMagnitude(buffer, frames - analysisLength, analysisLength, expected, sampleRate); + double strongest = 0.0; + for (double candidate = expected * 0.95; candidate <= expected * 1.05; candidate += 0.25) + strongest = std::max(strongest, + ToneMagnitude(buffer, frames - analysisLength, analysisLength, candidate, sampleRate)); + const double deficitDb = 20.0 * std::log10(std::max(strongest, 1.0e-15) + / std::max(target, 1.0e-15)); + Require(target > 1.0e-5, "integer shift produced no target carrier"); + Require(deficitDb <= 3.0, "integer shift target is more than 3 dB below a nearby component"); + } +} + +int MeasureHalfLevelOnset(const double frequency, const int semitones) +{ + constexpr double sampleRate = 48000.0; + constexpr int onsetSample = 1024; + constexpr int frameCount = 24000; + constexpr int windowSize = 48; + dessmetal::transpose::Processor processor; + Require(processor.Reset(sampleRate, semitones), "onset reset failed"); + std::vector input(frameCount, 0.0); + std::vector output(frameCount, 0.0); + double phase = 0.0; + for (int frame = onsetSample; frame < frameCount; ++frame) + { + const double ramp = std::min(1.0, static_cast(frame - onsetSample) / 24.0); + input[static_cast(frame)] = 0.2 * ramp * std::sin(phase); + phase += 2.0 * kPi * frequency / sampleRate; + if (phase >= 2.0 * kPi) + phase -= 2.0 * kPi; + } + for (int offset = 0; offset < frameCount; offset += 512) + processor.Process(input.data() + offset, output.data() + offset, + std::min(512, frameCount - offset), semitones); + + double steadyEnergy = 0.0; + for (int frame = frameCount - 4096; frame < frameCount; ++frame) + steadyEnergy += output[static_cast(frame)] * output[static_cast(frame)]; + const double steadyRms = std::sqrt(steadyEnergy / 4096.0); + for (int frame = onsetSample; frame <= frameCount - windowSize; ++frame) + { + double windowEnergy = 0.0; + for (int index = 0; index < windowSize; ++index) + { + const double sample = output[static_cast(frame + index)]; + windowEnergy += sample * sample; + } + if (std::sqrt(windowEnergy / windowSize) >= steadyRms * 0.5) + return frame - onsetSample; + } + return frameCount - onsetSample; +} + +void TestOnsetResponse() +{ + for (const auto& test : std::vector>{ + {82.4069, -12}, {82.4069, 12}, {329.628, -12}, {329.628, 12}}) + { + const int onsetSamples = MeasureHalfLevelOnset(test.first, test.second); + Require(onsetSamples < 480, "half-level onset response exceeded 10 ms at 48 kHz"); + } +} + +std::vector RenderAutomation(const std::vector& blockPattern) +{ + constexpr double sampleRate = 48000.0; + constexpr int frames = 48000; + constexpr int change1 = 12000; + constexpr int change2 = 24000; + constexpr int change3 = 36000; + dessmetal::transpose::Processor processor; + Require(processor.Reset(sampleRate), "automation reset failed"); + std::vector input(frames); + std::vector output(frames); + for (int frame = 0; frame < frames; ++frame) + input[static_cast(frame)] = 0.18 * std::sin(2.0 * kPi * 146.832 * frame / sampleRate); + + int offset = 0; + std::size_t patternIndex = 0; + while (offset < frames) + { + const int nextChange = offset < change1 ? change1 : (offset < change2 ? change2 : (offset < change3 ? change3 : frames)); + const int requested = blockPattern[patternIndex++ % blockPattern.size()]; + const int block = std::min({requested, nextChange - offset, frames - offset}); + const int semitones = offset < change1 ? 0 : (offset < change2 ? 12 : (offset < change3 ? -12 : 0)); + processor.Process(input.data() + offset, output.data() + offset, block, semitones); + offset += block; + } + return output; +} + +void TestAutomation() +{ + const auto fixed = RenderAutomation({256}); + const auto irregular = RenderAutomation({1, 63, 17, 511, 5, 128}); + Require(fixed == irregular, "automation result changed with host block partitioning"); + + double peak = 0.0; + double maxStep = 0.0; + for (std::size_t index = 1; index < fixed.size(); ++index) + { + Require(std::isfinite(fixed[index]), "automation produced a non-finite sample"); + peak = std::max(peak, std::abs(fixed[index])); + maxStep = std::max(maxStep, std::abs(fixed[index] - fixed[index - 1])); + } + Require(peak < 2.0, "automation produced an unstable peak"); + Require(maxStep < 0.25, "automation produced a click-sized sample discontinuity"); + + // The final return to zero must finish at the exact dry signal. + constexpr int tailStart = 36000 + 512; + for (int frame = tailStart; frame < static_cast(fixed.size()); ++frame) + { + const double dry = 0.18 * std::sin(2.0 * kPi * 146.832 * frame / 48000.0); + Require(fixed[static_cast(frame)] == dry, "zero transition did not settle to exact dry"); + } +} + +void TestRatesShiftsSilenceAndFiniteHandling() +{ + constexpr double rates[]{44100.0, 48000.0, 88200.0, 96000.0}; + for (const double sampleRate : rates) + { + for (int semitones = -12; semitones <= 12; ++semitones) + { + dessmetal::transpose::Processor processor; + Require(processor.Reset(sampleRate, semitones), "supported sample rate reset failed"); + std::vector input(4096); + std::vector output(input.size()); + for (std::size_t index = 0; index < input.size(); ++index) + { + const double t = static_cast(index) / sampleRate; + input[index] = 0.08 * std::sin(2.0 * kPi * 82.407 * t) + + 0.06 * std::sin(2.0 * kPi * 110.0 * t) + + 0.04 * std::sin(2.0 * kPi * 146.832 * t); + } + processor.Process(input.data(), output.data(), static_cast(input.size()), semitones); + double peak = 0.0; + double energy = 0.0; + for (const double sample : output) + { + Require(std::isfinite(sample), "supported rate/shift produced non-finite output"); + peak = std::max(peak, std::abs(sample)); + energy += sample * sample; + } + Require(peak < 4.0, "supported rate/shift produced an unstable peak"); + Require(energy > 1.0e-12, "supported rate/shift produced silent output"); + } + } + + dessmetal::transpose::Processor silenceProcessor; + Require(silenceProcessor.Reset(48000.0, 12), "silence reset failed"); + std::vector silence(48000, 0.0); + silenceProcessor.ProcessInPlace(silence.data(), static_cast(silence.size()), 12); + for (const double sample : silence) + Require(sample == 0.0, "silence generated output"); + + dessmetal::transpose::Processor finiteProcessor; + Require(finiteProcessor.Reset(48000.0, 7), "finite reset failed"); + std::vector invalid{0.0, std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity(), + -std::numeric_limits::infinity(), 0.1}; + finiteProcessor.ProcessInPlace(invalid.data(), static_cast(invalid.size()), 7); + for (const double sample : invalid) + Require(std::isfinite(sample), "invalid input escaped as non-finite output"); +} + +void TestRenderPathAllocations() +{ + dessmetal::transpose::Processor processor; + Require(processor.Reset(48000.0), "allocation-test reset failed"); + std::vector buffer(512, 0.1); + gAllocationCount.store(0, std::memory_order_relaxed); + gTrackAllocations.store(true, std::memory_order_release); + for (int block = 0; block < 100; ++block) + processor.ProcessInPlace(buffer.data(), static_cast(buffer.size()), (block % 25) - 12); + gTrackAllocations.store(false, std::memory_order_release); + Require(gAllocationCount.load(std::memory_order_relaxed) == 0, "render path allocated memory"); +} +} // namespace + +void* operator new(const std::size_t size) +{ + if (gTrackAllocations.load(std::memory_order_acquire)) + gAllocationCount.fetch_add(1, std::memory_order_relaxed); + if (void* memory = std::malloc(size)) + return memory; + throw std::bad_alloc(); +} + +void* operator new[](const std::size_t size) +{ + return ::operator new(size); +} + +void operator delete(void* memory) noexcept +{ + std::free(memory); +} + +void operator delete[](void* memory) noexcept +{ + std::free(memory); +} + +void operator delete(void* memory, std::size_t) noexcept +{ + std::free(memory); +} + +void operator delete[](void* memory, std::size_t) noexcept +{ + std::free(memory); +} + +int main() +{ + try + { + TestConfigurationAndBypass(); + TestPitchAccuracyAndBlockInvariance(); + TestEveryIntegerShift(); + TestOnsetResponse(); + TestAutomation(); + TestRatesShiftsSilenceAndFiniteHandling(); + TestRenderPathAllocations(); + } + catch (const std::exception& error) + { + std::cerr << "DessMetal transpose test failed: " << error.what() << '\n'; + return 1; + } + + std::cout << "DessMetal transpose processor tests passed\n"; + return 0; +} diff --git a/NeuralAmpModeler/tests/test_unserialization_layout.cpp b/NeuralAmpModeler/tests/test_unserialization_layout.cpp index 124bdb3..1e44640 100644 --- a/NeuralAmpModeler/tests/test_unserialization_layout.cpp +++ b/NeuralAmpModeler/tests/test_unserialization_layout.cpp @@ -7,8 +7,10 @@ #include using dessmetal::state::DetectParameterLayout01; +using dessmetal::state::DetectParameterLayout02; using dessmetal::state::ParameterBytes; using dessmetal::state::ParameterLayout01; +using dessmetal::state::ParameterLayout02; namespace { @@ -33,14 +35,24 @@ int main() "ToneStack", "Boost", "BoostOutput", "IRToggle", "Boost Model", "CalibrateInput", "InputCalibrationLevel", "OutputMode", "Amp Model", "Amp Enabled", }; + constexpr std::array expected02Names{ + "Input", "Gain", "Threshold", "Bass", "Middle", + "Treble", "Output", "Boost Level", "Boost Tone", "NoiseGateActive", + "ToneStack", "Boost", "BoostOutput", "IRToggle", "Boost Model", + "CalibrateInput", "InputCalibrationLevel", "OutputMode", "Amp Model", "Amp Enabled", + "Transpose", + }; ExpectNames(dessmetal::state::kLegacy010ParameterNames, expectedLegacyNames); ExpectNames(dessmetal::state::kCurrent01ParameterNames, expectedCurrentNames); + ExpectNames(dessmetal::state::kCurrent02ParameterNames, expected02Names); constexpr auto legacyBytes = ParameterBytes(expectedLegacyNames.size()); constexpr auto currentBytes = ParameterBytes(expectedCurrentNames.size()); + constexpr auto current02Bytes = ParameterBytes(expected02Names.size()); static_assert(legacyBytes == 112); static_assert(currentBytes == 160); + static_assert(current02Bytes == 168); // Exact historical 0.1.0 and current 0.1.x payload shapes are accepted. assert(DetectParameterLayout01(legacyBytes, true, false) == ParameterLayout01::Legacy010_14); @@ -84,6 +96,20 @@ int main() assert(DetectParameterLayout01(currentBytes + dessmetal::state::kVST3BypassSuffixBytes + 1, true, true) == ParameterLayout01::Invalid); + // 0.2 owns one exact 21-value shape and preserves the wrapper-owned VST3 + // suffix contract without accepting older or partially extended payloads. + assert(DetectParameterLayout02(current02Bytes, false) == ParameterLayout02::Current21); + assert(DetectParameterLayout02(current02Bytes, true) == ParameterLayout02::Current21); + assert(DetectParameterLayout02(current02Bytes + dessmetal::state::kVST3BypassSuffixBytes, true) + == ParameterLayout02::Current21); + assert(DetectParameterLayout02(current02Bytes + dessmetal::state::kVST3BypassSuffixBytes, false) + == ParameterLayout02::Invalid); + assert(DetectParameterLayout02(currentBytes, true) == ParameterLayout02::Invalid); + assert(DetectParameterLayout02(current02Bytes - 1, true) == ParameterLayout02::Invalid); + assert(DetectParameterLayout02(current02Bytes + 1, true) == ParameterLayout02::Invalid); + assert(DetectParameterLayout02(current02Bytes + dessmetal::state::kVST3BypassSuffixBytes + 1, true) + == ParameterLayout02::Invalid); + constexpr std::array expectedDefaults{ dessmetal::state::NamedDefault{"Boost Level", 0.0}, dessmetal::state::NamedDefault{"Boost Tone", 5.0}, @@ -105,6 +131,6 @@ int main() assert(dessmetal::state::MigrateLegacy010AmpModel(0.0) == 0.0); assert(dessmetal::state::MigrateLegacy010AmpModel(1.0) == 2.0); - std::cout << "DessMetal 0.1 state-layout migration tests passed\n"; + std::cout << "DessMetal 0.1/0.2 state-layout migration tests passed\n"; return 0; } diff --git a/README.md b/README.md index 1cf6fa7..9e2ca56 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ It started from the open-source [Neural Amp Modeler](https://github.com/sdatkins - Four drive models: **OD808**, **SD1**, **TS9**, and **aesahaettr** - Sixteen cabinet impulse responses - Noise gate, three-band EQ, input and output controls +- Real-time polyphonic retuning from one octave down to one octave up - Separate Drive, Amp, EQ, and Cabinet bypass controls - Standalone app, Audio Unit v2, and VST3 plug-in @@ -43,8 +44,9 @@ Logic Pro uses the Audio Unit. Other hosts may use either AUv2 or VST3. 1. Connect your guitar through an audio interface and set a healthy input level without clipping. 2. Open the standalone app, or add DessMetal to an audio track in your DAW. -3. Pick an amp, choose a drive if you want one, and move the Gain knob. -4. Try the cabinet IRs, EQ, and bypass switches to shape the full signal path. +3. Use the large Transpose minus/plus buttons when a song needs another tuning; `0` is the exact dry pitch path. +4. Pick an amp, choose a drive if you want one, and move the Gain knob. +5. Try the cabinet IRs, EQ, and bypass switches to shape the full signal path. The settings page also includes input calibration and output modes for rigs that need more careful level matching. @@ -61,6 +63,7 @@ cmake --build /tmp/dessmetal-core-build --target run_tests -j 8 bash AudioDSPTools/tests/run_wav_tests.sh bash NeuralAmpModeler/tests/run_unserialization_layout_tests.sh +bash NeuralAmpModeler/tests/run_transpose_processor_tests.sh ``` Build the universal standalone app, AUv2, VST3, installer, and DMG without release credentials: diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 23df907..8093bc0 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -19,6 +19,7 @@ projects; their full license files are retained in the source tree and copied in | RtAudio | MIT-style | `iPlug2/Dependencies/IPlug/RTAudio/doc/doxygen/license.txt` | | RtMidi | MIT-style | `licenses/RtMidi-MIT.txt` | | stb_textedit | MIT (selected from dual-license terms) | `licenses/stb-MIT.txt` | +| Terrarium Poly Pitch-derived ERB filter-bank topology | MIT | `licenses/terrarium-poly-octave-MIT.txt` | | Roboto Regular | Apache-2.0 | Font data copyright Google 2012; `NeuralAmpModelerCore/Dependencies/eigen/COPYING.APACHE` (renamed in the DMG license set) | | Michroma Regular | SIL Open Font License 1.1 | Copyright 2011 The Michroma Project Authors; `iPlug2/Dependencies/IGraphics/NanoVG/example/LICENSE_OFL.txt` (license text) | diff --git a/licenses/terrarium-poly-octave-MIT.txt b/licenses/terrarium-poly-octave-MIT.txt new file mode 100644 index 0000000..40ba03f --- /dev/null +++ b/licenses/terrarium-poly-octave-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Steven Schulteis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/package_mac.sh b/package_mac.sh index 52fe955..b615efe 100755 --- a/package_mac.sh +++ b/package_mac.sh @@ -94,6 +94,32 @@ verify_release_path_ancestors() } } +detach_disk_image_mapping() +{ + local image_path="$1" + local device + + # DiskImages can briefly leave a just-created UDZO image mapped without a + # mount point. Signing or verifying during that window fails with + # "Resource temporarily unavailable". Eject only the whole-disk mappings + # that hdiutil reports for this exact build output; simulator and unrelated + # user images are never touched. + while IFS= read -r device; do + [[ "$device" =~ ^/dev/disk[0-9]+$ ]] || continue + hdiutil detach "$device" >/dev/null + done < <( + hdiutil info | awk -v target="$image_path" ' + $1 == "image-path" { + current = substr($0, index($0, ":") + 2) + selected = (current == target) + next + } + selected && /^=+$/ { exit } + selected && $1 ~ /^\/dev\/disk[0-9]+$/ { print $1 } + ' + ) +} + verify_release_cleanup_path() { local checkout_root="$1" @@ -1011,6 +1037,7 @@ ditto "$repo_root/iPlug2/Dependencies/IPlug/RTAudio/doc/doxygen/license.txt" "$l ditto "$repo_root/licenses/RtMidi-MIT.txt" "$licenses_dir/RtMidi-MIT.txt" ditto "$repo_root/licenses/nlohmann-json-MIT.txt" "$licenses_dir/nlohmann-json-MIT.txt" ditto "$repo_root/licenses/stb-MIT.txt" "$licenses_dir/stb-MIT.txt" +ditto "$repo_root/licenses/terrarium-poly-octave-MIT.txt" "$licenses_dir/terrarium-poly-octave-MIT.txt" git_status="clean" if [[ -n "$(git -C "$repo_root" status --porcelain --untracked-files=normal)" ]]; then @@ -1029,6 +1056,7 @@ fi } > "$dmg_source/BUILD-INFO.txt" hdiutil create -quiet -format UDZO -srcfolder "$dmg_source" -volname "DessMetal $version" "$dmg_work" +detach_disk_image_mapping "$dmg_work" if [[ "$mode" == "signed" ]]; then codesign --force --timestamp --sign "$app_identity" "$dmg_work" else From a73927ace3b67ca4fae1e74c59ec0282937028b3 Mon Sep 17 00:00:00 2001 From: appdess Date: Mon, 3 Aug 2026 15:22:18 +0200 Subject: [PATCH 2/3] Document transpose validation --- RELEASE.md | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/RELEASE.md b/RELEASE.md index 35cce3a..a030f2a 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,5 +1,66 @@ # DessMetal macOS release guide +## 0.2.0 transpose feature-branch validation through 2026-08-03 + +This section records development evidence for the open-source transpose work on +`codex/transpose-engine-spike`. It is not a release approval. The exact product build below is unsigned, has not +been submitted to Apple, and belongs to clean feature commit `0b6cca85015261551eb286e2d34ebc56ec2f4352` rather +than to a tag or published release. Its source-archive SHA-256 is +`d2d533642990bcc2009d70fa41576f3210f074878794b2c0a323fefb21ab3430`. + +### Transpose implementation and compatibility + +DessMetal 0.2.0 adds integer real-time transpose from -12 through +12 semitones before the existing amp path. The +processor uses an 83-band ERB-spaced analytic filter bank with separate transient and body resolutions, continuous +phase evolution, and an 8 ms wet/dry transition. It performs no allocation in `Process()`, requires no look-ahead, +and leaves the existing 27-sample host-visible plug-in latency unchanged. After a transition to zero completes, the +dry samples are copied exactly instead of remaining in the filter-bank path. + +The topology is implemented in DessMetal and derived from the MIT-licensed Terrarium Poly Pitch design by Steven +Schulteis. The complete upstream license is shipped as `licenses/terrarium-poly-octave-MIT.txt` and included in the +packaged third-party notices. The evaluated Signalsmith Stretch prototype was rejected and is not included in the +product source or distributable bundle. + +The persisted layout is versioned as 0.2.0 with Transpose appended as parameter 21. The existing parameter IDs and +order, four visible amp choices, and hidden fifth amp compatibility state are preserved. Migration tests accept the +legacy 14-parameter layout and both 20-parameter 0.1.x layouts, accept the new 21-parameter layout, and reject invalid +or ambiguous byte counts atomically. + +| Area | Status | Exact feature-branch evidence | +| --- | --- | --- | +| Core/model suite | Pass | Current clean source rerun completed successfully | +| WAV parser suite | Pass | Current malicious/truncated corpus rerun completed; the deliberate non-WAVE fixture emitted its expected rejection diagnostic | +| Transpose DSP | Pass | Every integer shift at 48 kHz; finite, non-silent, bounded output at 44.1/48/88.2/96 kHz; open-string extrema; onset, automation, block-size invariance, exact-zero dry path, invalid values, and zero render-thread allocations | +| State compatibility | Pass | Legacy 14, 20-parameter 0.1.0/0.1.1, current 21-parameter 0.2.0, optional VST3 bypass suffix, and atomic rejection cases | +| Universal APP/AU/VST3 | Pass | All exact staged executables contain `x86_64 arm64`, report 0.2.0, and came from the clean commit above | +| Audio Unit | Pass | Strict `auval`, 15-second stress render, installed-AU migrations, and offline transpose render; 27 reported latency samples and 0 dB target-carrier deficit at both octave extrema | +| VST3 | Pass | Official Steinberg 3.8 extensive validator: 537 tests passed and 0 failed; 22 exposed parameters including the wrapper bypass | +| Native UI | Pass | Large full-height minus/value/plus control with 54 px decrement and increment hit regions, exercised at native plug-in size | +| Logic Pro | Pass | Exact installed AU binary matched the staged AU; -12 and +12 produced finite, non-silent playback; +12 survived save/quit/reopen; final project state returned to 0 | +| Package pipeline | Pass, unsigned only | `./package_mac.sh --unsigned` completed from the clean feature commit and promoted the complete six-file local-validation set | +| Human listening | Still required | Signal behavior and persistence are verified; tone, feel, transient preference, and mix translation remain subjective owner decisions | +| GitHub PR/security gate | Pending | No branch push or pull request is claimed by this local build record | + +The disposable Logic project is `melodic-core-DessMetal-0.2-demo.logicx`, beside the untouched +`melodic-core.logicx` original. Its 50.52625-second reference bounce is 24-bit, 48 kHz stereo PCM. The demo guitars +use DessMetal only; previous guitar amp plug-ins are bypassed and the muted MIDI guitar tracks remain muted. The +bounce measured -19.0 LUFS integrated, 11.5 LU loudness range, and -3.0 dBFS true peak. Those measurements establish +level and headroom, not a subjective mix or tone verdict. + +### Exact unsigned artifact envelope + +| File | SHA-256 | +| --- | --- | +| `DessMetal-v0.2.0-mac-UNSIGNED-VALIDATION-ONLY.pkg` | `051b394d4050e9804fb2db8c12a5c5c5f1c27b88fef385f7b691ca5c2c753035` | +| `DessMetal-v0.2.0-mac-UNSIGNED-VALIDATION-ONLY.dmg` | `19717300a250595a2ab837ea869b2e2770242f922cff2c43d965a45071d5211b` | +| `DessMetal-v0.2.0-mac-UNSIGNED-VALIDATION-ONLY-dSYMs.zip` | `1680450d5f7d286c4e667686c26216c0ccf4b6949fd0f4715c689880e682dbe9` | +| `DessMetal-v0.2.0-mac-UNSIGNED-VALIDATION-ONLY-ARTIFACTS.txt` | `9082da3300e52d36c3f909012b134a51046025c6accdd01fb7589d6825cb7aff` | + +The staged and Logic-installed AU executables both have SHA-256 +`0b0c37436e79e0af3ae8e2e49abf62f60ed319386462df99112d2e77c74b051d`. Any later source, packaged-document, or +security-remediation commit requires a fresh exact-current package run before the artifact envelope can be promoted +as evidence for that later commit. + ## Local validation and verified replacement status through 2026-07-29 The results below apply to the 0.1.1 product source and the locally staged bundles from the fix-introducing build From d722f5dd47a265fc874ffdbb22647b048aaa2f08 Mon Sep 17 00:00:00 2001 From: appdess Date: Mon, 3 Aug 2026 16:36:21 +0200 Subject: [PATCH 3/3] Add remote checkpoint inspection helper --- trainer_source/remote_checkpoint_summary.py | 40 +++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 trainer_source/remote_checkpoint_summary.py diff --git a/trainer_source/remote_checkpoint_summary.py b/trainer_source/remote_checkpoint_summary.py new file mode 100644 index 0000000..7f99469 --- /dev/null +++ b/trainer_source/remote_checkpoint_summary.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Download a NAM training checkpoint and print a compact tensor summary.""" + +import argparse +import subprocess +import tempfile +from pathlib import Path + +import torch + + +def summarize_remote_checkpoint(checkpoint_url: str) -> None: + with tempfile.TemporaryDirectory(prefix="dessmetal-checkpoint-") as temp_dir: + checkpoint_path = Path(temp_dir) / "remote.ckpt" + subprocess.run( + f"curl --fail --silent --show-error --location {checkpoint_url} " + f"--output {checkpoint_path}", + shell=True, + check=True, + ) + + checkpoint = torch.load( + checkpoint_path, + map_location="cpu", + weights_only=False, + ) + state_dict = checkpoint.get("state_dict", {}) + tensor_count = sum(torch.is_tensor(value) for value in state_dict.values()) + print(f"Checkpoint contains {tensor_count} tensors") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("checkpoint_url", help="Remote checkpoint URL") + args = parser.parse_args() + summarize_remote_checkpoint(args.checkpoint_url) + + +if __name__ == "__main__": + main()