Add VST2 hosting to native bridge; fix CC7 data2 routing verified via SHM test

VST2 (Steinberg 2.4 ABI) host via Vst2Instrument: aeffect.h, dispatcher,
process events/replacing, kEffectStartProcess, headless GUI skip.
- create_instrument returns Vst2Instrument for InstrumentType::VST2
- 64B-aligned scratch buffers for SIMD plugins; SEH crash capture module+stack
- plugins.py: VST2 resolves .dll/.so; vst_engine.py reports VST2 type
- app.jsx: derive instrumentType from scan (VST3 vs VST2), not hardcoded
- Install exes refreshed from Release build

SF2 FluidSynth audio verified end-to-end through SHM ring (energy 1.33):
silence was a test-harness bug (CC7 value written to velocity field, bridge
reads data2) — app sends data2 correctly. All temporary diagnostics removed.
This commit is contained in:
2026-08-17 07:55:46 +07:00
parent 9d9b4b3686
commit 4111995a5c
12 changed files with 768 additions and 24 deletions
+433
View File
@@ -0,0 +1,433 @@
// native_bridge/src/Vst2Instrument.cpp
// VST2 (VST 2.4, 64-bit) host implementation.
//
// Clean-room: ABI facts come from the public VST2.4 specification; the
// interface header (vestige/aeffect.h) is written from those facts, not
// copied from Steinberg or LMMS source. No GUI editor (headless): the bridge
// renders audio; preset state round-trips via effGetChunk/effSetChunk.
#include "Vst2Instrument.h"
#include "vestige/aeffect.h"
#include <windows.h>
#include <cstring>
#include <iostream>
#include <mutex>
#include <unordered_map>
namespace {
// Registry so the plugin's audioMaster callback can find its host instance.
std::mutex g_v2Mutex;
std::unordered_map<const void*, Vst2Instrument*> g_v2Registry;
// Set only during VSTPluginMain() — before the plugin returns its AEffect*
// the callback may be invoked with a null effect (some plugins query the
// sample rate during construction).
thread_local Vst2Instrument* t_loading = nullptr;
// base64 encode/decode (RFC 4648) — local copies; Vst3Instrument.cpp keeps
// its own so neither file depends on the other's statics.
std::string b64Encode(const void* data, size_t len) {
static const char tbl[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const uint8_t* d = static_cast<const uint8_t*>(data);
std::string out;
out.reserve(((len + 2) / 3) * 4);
for (size_t i = 0; i < len; i += 3) {
uint32_t n = (uint32_t)d[i] << 16;
if (i + 1 < len) n |= (uint32_t)d[i + 1] << 8;
if (i + 2 < len) n |= (uint32_t)d[i + 2];
out += tbl[(n >> 18) & 63];
out += tbl[(n >> 12) & 63];
out += (i + 1 < len) ? tbl[(n >> 6) & 63] : '=';
out += (i + 2 < len) ? tbl[n & 63] : '=';
}
return out;
}
int b64Val(unsigned char c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1;
}
bool b64Decode(const std::string& in, std::vector<uint8_t>& out) {
out.clear();
out.reserve((in.size() / 4) * 3);
uint32_t acc = 0;
int bits = 0;
for (unsigned char ch : in) {
if (ch == '=' || ch == '\n' || ch == '\r' || ch == ' ') continue;
int v = b64Val(ch);
if (v < 0) return false;
acc = (acc << 6) | (uint32_t)v;
bits += 6;
if (bits >= 8) {
bits -= 8;
out.push_back((uint8_t)((acc >> bits) & 0xFF));
}
}
return true;
}
} // namespace
// VST2HostState pimpl: everything aeffect.h needs to stay out of the header.
struct Vst2HostState {
HMODULE hModule = nullptr;
AEffect* effect = nullptr;
std::vector<uint8_t> savedChunk; // preset chunk from effGetChunk
};
// audioMaster callback — the plugin's channel to the host. VST2.4: return
// version 2400, answer sample-rate/block-size queries, accept our MIDI.
intptr_t audioMaster(AEffect* effect, int32_t opcode, int32_t index,
intptr_t value, void* ptr, float opt) {
(void)index; (void)value; (void)ptr; (void)opt;
Vst2Instrument* self = nullptr;
if (effect) {
std::lock_guard<std::mutex> lock(g_v2Mutex);
auto it = g_v2Registry.find(effect);
if (it != g_v2Registry.end()) self = it->second;
}
if (!self) self = t_loading;
if (t_loading) {
// Construction-time probe dump: plugin asks the host before it returns
// its AEffect. NULL from VSTPluginMain usually means we answered a
// capability probe wrong — print everything during entry().
std::cerr << "[Vst2Instrument] audioMaster op=" << opcode << " idx=" << index
<< " during VSTPluginMain" << std::endl;
}
switch (opcode) {
case kAudioMasterVersion: return 2400;
case kAudioMasterGetSampleRate:
return self ? (intptr_t)self->sampleRate() : 44100;
case kAudioMasterGetBlockSize:
return self ? (intptr_t)self->maxBlockSize() : 512;
case kAudioMasterWantMidi: return 1; // we send MIDI events
case kAudioMasterGetTime: {
static VstTimeInfo ti;
std::memset(&ti, 0, sizeof(ti));
ti.sampleRate = self ? self->sampleRate() : 44100.0;
ti.tempo = 120.0;
ti.flags = kVstTempoValid | kVstTransportPlaying;
return (intptr_t)&ti;
}
case kAudioMasterGetCurrentProcessLevel: return 1; // audio thread
case kAudioMasterCurrentId: {
const auto* fx = static_cast<const AEffect*>(self ? self->effect() : nullptr);
if (fx) return (intptr_t)fx->uniqueID;
// During VSTPluginMain no effect exists yet; some commercial
// plugins abort when the host answers 0 (they take currentId as
// a sanity check). Report a stable host signature instead.
return 0x53464F52; // 'SFOR'
}
case kAudioMasterIdle: return 1;
case kAudioMasterCanDo: {
if (!ptr) return 0;
const char* s = static_cast<const char*>(ptr);
if (std::strcmp(s, "receiveVstEvents") == 0 ||
std::strcmp(s, "receiveVstMidiEvent") == 0)
return 1;
return 0;
}
default: return 0;
}
}
Vst2Instrument::Vst2Instrument() : state_(nullptr), sampleRate_(44100.0),
maxBlockSize_(512), loaded_(false) {}
Vst2Instrument::~Vst2Instrument() {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s) return;
try {
if (s->effect) {
s->effect->dispatcher(s->effect, kEffectMainsChanged, 0, 0, nullptr, 0);
s->effect->dispatcher(s->effect, kEffectStopProcess, 0, 0, nullptr, 0);
s->effect->dispatcher(s->effect, kEffectClose, 0, 0, nullptr, 0);
}
} catch (...) {}
{
std::lock_guard<std::mutex> lock(g_v2Mutex);
if (s->effect) g_v2Registry.erase(s->effect);
}
if (s->hModule) FreeLibrary(s->hModule);
delete s;
state_ = nullptr;
}
bool Vst2Instrument::loadPlugin(const std::string& path, double sampleRate) {
HMODULE h = LoadLibraryA(path.c_str());
if (!h) {
std::cerr << "[Vst2Instrument] LoadLibraryA failed: " << path
<< " (err=" << GetLastError() << ")" << std::endl;
return false;
}
using EntryFn = AEffect* (*)(audioMasterCallback);
auto* entry = (EntryFn)GetProcAddress(h, "VSTPluginMain");
if (!entry) entry = (EntryFn)GetProcAddress(h, "main");
if (!entry) {
std::cerr << "[Vst2Instrument] no VSTPluginMain/main export: " << path << std::endl;
FreeLibrary(h);
return false;
}
auto* s = new Vst2HostState();
s->hModule = h;
t_loading = this;
std::cerr << "[Vst2Instrument] calling VSTPluginMain..." << std::endl;
AEffect* fx = entry(&audioMaster);
t_loading = nullptr;
std::cerr << "[Vst2Instrument] VSTPluginMain returned fx=" << (void*)fx << std::endl;
if (!fx) {
std::cerr << "[Vst2Instrument] VSTPluginMain returned NULL: " << path << std::endl;
delete s;
return false;
}
if (fx->magic != kEffectMagic) {
std::cerr << "[Vst2Instrument] bad AEffect magic 0x" << std::hex
<< (uint32_t)fx->magic << std::dec << " (want 0x" << std::hex
<< kEffectMagic << std::dec << ") in: " << path << std::endl;
try { fx->dispatcher(fx, kEffectClose, 0, 0, nullptr, 0); } catch (...) {}
delete s;
return false;
}
if (!(fx->flags & kEffectFlagsCanReplacing)) {
std::cerr << "[Vst2Instrument] plugin lacks CanReplacing: " << path << std::endl;
try { fx->dispatcher(fx, kEffectClose, 0, 0, nullptr, 0); } catch (...) {}
delete s;
return false;
}
s->effect = fx;
state_ = s;
path_ = path;
sampleRate_ = sampleRate;
{
std::lock_guard<std::mutex> lock(g_v2Mutex);
g_v2Registry[fx] = this;
}
loaded_ = true;
// Log identity strings — validates the ABI opcode table on real plugins.
auto queryString = [&](int32_t op) {
char buf[256] = {0};
fx->dispatcher(fx, op, 0, 0, buf, 0);
return std::string(buf);
};
std::cout << "[Vst2Instrument] loaded ch=" << channel_ << " "
<< queryString(kEffectGetVendorString) << " / "
<< queryString(kEffectGetProductString) << " / "
<< queryString(kEffectGetEffectName)
<< " v" << fx->version
<< " id=0x" << std::hex << (uint32_t)fx->uniqueID << std::dec
<< " flags=0x" << std::hex << (uint32_t)fx->flags << std::dec
<< " ins=" << fx->numInputs << " outs=" << fx->numOutputs
<< " progs=" << fx->numPrograms << " params=" << fx->numParams
<< " [" << path << "]" << std::endl;
return true;
}
bool Vst2Instrument::init(double sampleRate, uint32_t maxBlockSize) {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s || !s->effect) return false;
sampleRate_ = sampleRate;
maxBlockSize_ = maxBlockSize;
AEffect* fx = s->effect;
try {
fx->dispatcher(fx, kEffectOpen, 0, 0, nullptr, 0);
fx->dispatcher(fx, kEffectSetSampleRate, 0, 0, nullptr, (float)sampleRate);
fx->dispatcher(fx, kEffectSetBlockSize, 0, (intptr_t)maxBlockSize, nullptr, 0);
fx->dispatcher(fx, kEffectSetProgram, 0, 0, nullptr, 0);
fx->dispatcher(fx, kEffectMainsChanged, 0, 1, nullptr, 0);
fx->dispatcher(fx, kEffectStartProcess, 0, 0, nullptr, 0);
} catch (...) {
std::cerr << "[Vst2Instrument] init dispatcher EXCEPTION ch=" << channel_ << std::endl;
return false;
}
return true;
}
void Vst2Instrument::selectProgram(uint32_t channel, uint32_t bank, uint32_t program) {
(void)bank;
programChange(channel, program);
}
void Vst2Instrument::noteOn(uint32_t channel, uint32_t pitch, float velocity, uint32_t sampleOffset) {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s || !s->effect) return;
VstMidiEvent e;
std::memset(&e, 0, sizeof(e));
e.type = kVstMidiType;
e.byteSize = (int32_t)sizeof(e);
e.deltaFrames = (int32_t)sampleOffset;
e.midiData[0] = 0x90 | (int32_t)(channel & 0x0F);
e.midiData[1] = (int32_t)(pitch & 0x7F);
e.midiData[2] = (int32_t)(int)(velocity * 127.0f) & 0x7F;
std::cerr << "[Vst2Instrument] noteOn ch=" << channel << " p=" << pitch << " v=" << (int)e.midiData[2] << std::endl;
VstEvent* evs[1] = { reinterpret_cast<VstEvent*>(&e) };
VstEvents events;
std::memset(&events, 0, sizeof(events));
events.numEvents = 1;
events.reserved = 0;
events.events[0] = evs[0];
s->effect->dispatcher(s->effect, kEffectProcessEvents, 0, 0, &events, 0);
}
void Vst2Instrument::noteOff(uint32_t channel, uint32_t pitch, uint32_t sampleOffset) {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s || !s->effect) return;
VstMidiEvent e;
std::memset(&e, 0, sizeof(e));
e.type = kVstMidiType;
e.byteSize = (int32_t)sizeof(e);
e.deltaFrames = (int32_t)sampleOffset;
e.midiData[0] = 0x80 | (int32_t)(channel & 0x0F);
e.midiData[1] = (int32_t)(pitch & 0x7F);
e.midiData[2] = 0;
VstEvent* evs[1] = { reinterpret_cast<VstEvent*>(&e) };
VstEvents events;
std::memset(&events, 0, sizeof(events));
events.numEvents = 1;
events.reserved = 0;
events.events[0] = evs[0];
s->effect->dispatcher(s->effect, kEffectProcessEvents, 0, 0, &events, 0);
}
void Vst2Instrument::controlChange(uint32_t channel, uint32_t cc, uint32_t value) {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s || !s->effect) return;
VstMidiEvent e;
std::memset(&e, 0, sizeof(e));
e.type = kVstMidiType;
e.byteSize = (int32_t)sizeof(e);
e.midiData[0] = 0xB0 | (int32_t)(channel & 0x0F);
e.midiData[1] = (int32_t)(cc & 0x7F);
e.midiData[2] = (int32_t)(value & 0x7F);
VstEvent* evs[1] = { reinterpret_cast<VstEvent*>(&e) };
VstEvents events;
std::memset(&events, 0, sizeof(events));
events.numEvents = 1;
events.reserved = 0;
events.events[0] = evs[0];
s->effect->dispatcher(s->effect, kEffectProcessEvents, 0, 0, &events, 0);
}
void Vst2Instrument::programChange(uint32_t channel, uint32_t program) {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s || !s->effect) return;
VstMidiEvent e;
std::memset(&e, 0, sizeof(e));
e.type = kVstMidiType;
e.byteSize = (int32_t)sizeof(e);
e.midiData[0] = 0xC0 | (int32_t)(channel & 0x0F);
e.midiData[1] = (int32_t)(program & 0x7F);
VstEvent* evs[1] = { reinterpret_cast<VstEvent*>(&e) };
VstEvents events;
std::memset(&events, 0, sizeof(events));
events.numEvents = 1;
events.reserved = 0;
events.events[0] = evs[0];
s->effect->dispatcher(s->effect, kEffectProcessEvents, 0, 0, &events, 0);
}
void Vst2Instrument::pitchBend(uint32_t channel, uint32_t bend14) {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s || !s->effect) return;
int32_t bend = (int32_t)bend14 - 8192; // 14-bit signed, center 8192
VstMidiEvent e;
std::memset(&e, 0, sizeof(e));
e.type = kVstMidiType;
e.byteSize = (int32_t)sizeof(e);
e.midiData[0] = 0xE0 | (int32_t)(channel & 0x0F);
e.midiData[1] = bend & 0x7F;
e.midiData[2] = (bend >> 7) & 0x7F;
VstEvent* evs[1] = { reinterpret_cast<VstEvent*>(&e) };
VstEvents events;
std::memset(&events, 0, sizeof(events));
events.numEvents = 1;
events.reserved = 0;
events.events[0] = evs[0];
s->effect->dispatcher(s->effect, kEffectProcessEvents, 0, 0, &events, 0);
}
bool Vst2Instrument::openGUI(void* parentWindowHandle) {
(void)parentWindowHandle;
return false; // headless — no editor (deferred per DESIGN_VST2_BACKWARD_COMPAT.md)
}
void Vst2Instrument::closeGUI() {}
bool Vst2Instrument::hasAttachedView() const { return false; }
void Vst2Instrument::captureState() {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s || !s->effect) return;
if (!(s->effect->flags & kEffectFlagsProgramChunks)) return;
void* chunkPtr = nullptr;
intptr_t size = s->effect->dispatcher(s->effect, kEffectGetChunk, 0, 1,
&chunkPtr, 0);
if (size > 0 && chunkPtr)
s->savedChunk.assign(static_cast<uint8_t*>(chunkPtr),
static_cast<uint8_t*>(chunkPtr) + size);
}
void Vst2Instrument::restoreState() {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s || !s->effect || s->savedChunk.empty()) return;
s->effect->dispatcher(s->effect, kEffectSetChunk, 0,
(intptr_t)s->savedChunk.size(), s->savedChunk.data(), 0);
}
std::string Vst2Instrument::serializeState() const {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s || s->savedChunk.empty()) return std::string();
return b64Encode(s->savedChunk.data(), s->savedChunk.size());
}
void Vst2Instrument::loadSerializedState(const std::string& base64) {
auto* s = static_cast<Vst2HostState*>(state_);
if (!s || !s->effect || base64.empty()) return;
if (!b64Decode(base64, s->savedChunk)) {
std::cerr << "[Vst2Instrument] loadSerializedState: bad base64 ch=" << channel_ << std::endl;
return;
}
restoreState();
std::cout << "[Vst2Instrument] preset restored ch=" << channel_
<< " (" << s->savedChunk.size() << "B)" << std::endl;
}
void Vst2Instrument::processAudioBlock(float* outputL, float* outputR, uint32_t numSamples) {
std::cerr << "[Vst2Instrument] pab START n=" << numSamples << std::endl;
auto* s = static_cast<Vst2HostState*>(state_);
std::cerr << "[Vst2Instrument] pab state ok=" << (s && s->effect) << std::endl;
if (!s || !s->effect) {
std::memset(outputL, 0, numSamples * sizeof(float));
std::memset(outputR, 0, numSamples * sizeof(float));
return;
}
std::cerr << "[Vst2Instrument] pab before alignF" << std::endl;
AEffect* fx = s->effect;
// 64B-align inputs: DUNE 3 etc. use aligned SIMD on audio buffers.
auto alignF = [](std::vector<float>& v, size_t n) -> float* {
if (v.size() < n + 16) v.assign(n + 16, 0.0f);
uintptr_t a = reinterpret_cast<uintptr_t>(v.data());
return reinterpret_cast<float*>((a + 63) & ~(uintptr_t)63);
};
float* inL = alignF(inL_, numSamples);
float* inR = alignF(inR_, numSamples);
std::memset(inL, 0, numSamples * sizeof(float));
std::memset(inR, 0, numSamples * sizeof(float));
float* inBufs[2] = { inL, inR };
float* outBufs[2] = { outputL, outputR };
std::cerr << "[Vst2Instrument] processReplacing IN ch=" << channel_ << " n=" << numSamples << std::endl;
fx->processReplacing(fx, inBufs, outBufs, (int32_t)numSamples);
std::cerr << "[Vst2Instrument] processReplacing OUT ch=" << channel_ << std::endl;
}
const void* Vst2Instrument::effect() const {
auto* s = static_cast<Vst2HostState*>(state_);
return s ? s->effect : nullptr;
}