Upload Source/Plugin/PluginBridgeProcessor.cpp
Browse files1234567891034561 unmodified line8910181112132021222324252627141516171819202122232425262728293031323334353637383940414243444546474834495051521 unmodified line54555642435758454659606162636465666768697071727374505152535455757657777879802 unmodified lines83848566676869707172737475768687887879808182838485868788899091929394959697989910089909110210310410592939410710810911011111211311411511611711811912012112295969798991001251261271281291301311321331341351361371381391401411421431441451461471011021031041051491501511521531541551061071571081091591601101111121131141151161171181631641191201211221231241251261271711721281291301 unmodified line13213313418018113513613713813918318418518614014114214314418818919019119219319419514514614714814915015119819915215315415515620120220320420520620720820921021121221315715821515916021721821916116216316416516616716816917017117217317417517617717817918018118222122222322422522618318422818518618723123223323423523623723823924024124224324424524624724824918818925125225325425525625719019119219326226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132219419519632432532632732819719819920020120220320433033133233333433533620520620720833920921034134234334434534634734834935035135235335435521121221321435835936021521636236336436521721821922022138 unmodified lines26026126241041126326441341441526526626726826927027127227310 unmodified lines284285286432433287288289435436437438439440441290291292293294295296297298299300301#include "PluginBridgeProcessor.h"#include "PluginBridgeEditor.h"#include "McpServer.h"
#include <spawn.h>#include <sys/wait.h>#include <unistd.h>#include <signal.h>
extern char** environ;#include "IPCProtocol.h"
#include "json.hpp"using json = nlohmann::json;1 unmodified linePluginBridgeProcessor::PluginBridgeProcessor() : AudioProcessor(BusesProperties() .withInput("Input", juce::AudioChannelSet::stereo(), true) .withOutput("Output", juce::AudioChannelSet::stereo(), true)) .withOutput("Output", juce::AudioChannelSet::stereo(), true)), mcpServer(std::make_unique<McpServer>(PluginBridgeConstants::kDefaultMcpPort, helper)){ #if JUCE_PLUGINHOST_VST3 formatManager.addFormat(new juce::VST3PluginFormat()); #endif #if JUCE_PLUGINHOST_AU formatManager.addFormat(new juce::AudioUnitPluginFormat()); #endif
mcpServer = std::make_unique<McpServer>(PluginBridgeConstants::kDefaultMcpPort, *this); helper.onHelperCrashed = [this]() { pluginLoaded = false; pluginName.clear(); pluginParamCount = 0; remoteLayerPortName.clear(); remoteGuiWidth = 0; remoteGuiHeight = 0; DBG("PluginBridgeProcessor: Helper crashed"); };
// When helper sends "ready" notification with layer port info helper.onGuiReady = [this](const juce::String& portName, int width, int height) { remoteLayerPortName = portName; remoteGuiWidth = width; remoteGuiHeight = height; if (onGuiReady) juce::MessageManager::callAsync([this]() { if (onGuiReady) onGuiReady(); }); };
helper.onGuiResized = [this](int width, int height) { remoteGuiWidth = width; remoteGuiHeight = height; if (onGuiResized) juce::MessageManager::callAsync([this, width, height]() { if (onGuiResized) onGuiResized(width, height); }); };
mcpServer->start();}
PluginBridgeProcessor::~PluginBridgeProcessor(){ mcpServer->stop(); unloadPlugin(); helper.killHelper();}
void PluginBridgeProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)1 unmodified line currentSampleRate = sampleRate; currentBlockSize = samplesPerBlock;
juce::ScopedLock sl(pluginLock); if (hostedPlugin) if (helper.isHelperRunning()) { hostedPlugin->setRateAndBufferSizeDetails(sampleRate, samplesPerBlock); hostedPlugin->prepareToPlay(sampleRate, samplesPerBlock); json cmd = {{"cmd", "configure"}, {"sampleRate", sampleRate}, {"blockSize", samplesPerBlock}, {"channels", 2}}; helper.sendCommand(cmd.dump());
auto* header = helper.getSharedAudio().getHeader(); if (header) { header->sampleRate.store((uint32_t)sampleRate); header->blockSize.store((uint32_t)samplesPerBlock); header->numChannels.store(2); } }}
void PluginBridgeProcessor::releaseResources(){ juce::ScopedLock sl(pluginLock); if (hostedPlugin) hostedPlugin->releaseResources();}void PluginBridgeProcessor::releaseResources() {}
void PluginBridgeProcessor::processBlock(juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midi)void PluginBridgeProcessor::processBlock(juce::AudioBuffer<float>& buffer, juce::MidiBuffer&){ juce::ScopedNoDenormals noDenormals;
2 unmodified lines for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i) buffer.clear(i, 0, buffer.getNumSamples());
juce::ScopedLock sl(pluginLock); if (hostedPlugin) hostedPlugin->processBlock(buffer, midi);}
juce::AudioProcessorEditor* PluginBridgeProcessor::createEditor(){ return new PluginBridgeEditor(*this);}
// --- Helper Test Load --- if (!pluginLoaded || !helper.isHelperRunning()) return;
static juce::File findHelperBinary(){ // Helper .app is bundled at: PluginBridge.vst3/Contents/Resources/PluginBridgeHelper.app // The actual executable is at: PluginBridgeHelper.app/Contents/MacOS/PluginBridgeHelper auto resourcesDir = juce::File::getSpecialLocation(juce::File::currentExecutableFile) .getParentDirectory() // MacOS/ .getParentDirectory() // Contents/ .getChildFile("Resources");
auto helperApp = resourcesDir.getChildFile("PluginBridgeHelper.app"); auto helperExe = helperApp.getChildFile("Contents").getChildFile("MacOS").getChildFile("PluginBridgeHelper");
if (helperExe.exists()) return helperExe;
// Fallback: bare binary (old layout) auto bareBinary = resourcesDir.getChildFile("PluginBridgeHelper"); if (bareBinary.exists()) return bareBinary;
DBG("findHelperBinary: NOT FOUND. Looked at: " + helperExe.getFullPathName()); return {};} auto& shm = helper.getSharedAudio(); if (!shm.isValid()) return;
PluginBridgeProcessor::TestResult PluginBridgeProcessor::testPluginSafety(const juce::String& path){ if (blocklist.isBlocked(path)) return TestResult::Unsafe; int numChannels = buffer.getNumChannels(); int numSamples = buffer.getNumSamples();
auto helperBinary = findHelperBinary(); if (!helperBinary.exists()) { DBG("testPluginSafety: Helper not found, skipping test (assuming safe)"); return TestResult::Safe; }
auto helperPathStr = helperBinary.getFullPathName().toStdString(); auto pluginPathStr = path.toStdString();
pid_t pid; char* argv[] = { (char*)helperPathStr.c_str(), (char*)"--test", (char*)pluginPathStr.c_str(), nullptr const float* inputPtrs[2] = { buffer.getReadPointer(0), numChannels > 1 ? buffer.getReadPointer(1) : buffer.getReadPointer(0) }; shm.writeInput(inputPtrs, numChannels, numSamples);
int spawnResult = posix_spawn(&pid, helperPathStr.c_str(), nullptr, nullptr, argv, environ); if (spawnResult != 0) { DBG("testPluginSafety: Failed to spawn helper: " + juce::String(strerror(spawnResult))); return TestResult::Safe; }
// Wait for helper to exit (max 10 seconds) int status = 0; int waitedMs = 0; const int timeoutMs = 10000;
while (waitedMs < timeoutMs) { int waitResult = waitpid(pid, &status, WNOHANG); if (waitResult == pid) break; if (waitResult < 0) break;
usleep(50000); // 50ms waitedMs += 50; } auto* header = shm.getHeader(); header->blockSize.store((uint32_t)numSamples); header->numChannels.store((uint32_t)numChannels); header->state.store(kStateInputReady);
if (waitedMs >= timeoutMs) { kill(pid, SIGKILL); waitpid(pid, &status, 0); DBG("testPluginSafety: Timed out for " + path); return TestResult::Unsafe; } helper.getInputSem().signal();
if (WIFEXITED(status) && WEXITSTATUS(status) == 0) if (helper.getOutputSem().wait(IPC::kProcessBlockTimeoutMs)) { DBG("testPluginSafety: SAFE — " + path); return TestResult::Safe; float* outputPtrs[2] = { buffer.getWritePointer(0), numChannels > 1 ? buffer.getWritePointer(1) : buffer.getWritePointer(0) }; shm.readOutput(outputPtrs, numChannels, numSamples); header->state.store(kStateIdle); }}
DBG("testPluginSafety: UNSAFE — " + path + " (exit: " + juce::String(WEXITSTATUS(status)) + ")"); return TestResult::Unsafe;juce::AudioProcessorEditor* PluginBridgeProcessor::createEditor(){ return new PluginBridgeEditor(*this);}
// --- Plugin Loading ---
void PluginBridgeProcessor::loadPlugin(const juce::String& path){ unloadPlugin();
if (blocklist.isBlocked(path)) { if (onLoadFailed)1 unmodified line return; }
juce::File pluginFile(path); if (!pluginFile.exists()) if (!helper.isHelperRunning()) { if (!helper.spawnHelper()) { DBG("PluginBridgeProcessor: Failed to spawn helper"); if (onLoadFailed) onLoadFailed("Plugin file not found"); return; } if (onLoadFailed) onLoadFailed("Failed to start helper process"); return; }
// Test safety first auto testResult = testPluginSafety(path); if (testResult == TestResult::Unsafe) { blocklist.addBlocked(path); if (onLoadFailed) onLoadFailed("Not compatible with PluginBridge"); return; json configCmd = {{"cmd", "configure"}, {"sampleRate", currentSampleRate}, {"blockSize", currentBlockSize}, {"channels", 2}}; helper.sendCommand(configCmd.dump()); }
// Safe — load in-process juce::OwnedArray<juce::PluginDescription> typesFound; json loadCmd = {{"cmd", "load"}, {"path", path.toStdString()}, {"sampleRate", currentSampleRate}, {"blockSize", currentBlockSize}};
for (int i = 0; i < formatManager.getNumFormats(); ++i) { auto* format = formatManager.getFormat(i); bool isVST3 = pluginFile.getFileExtension() == ".vst3"; bool isAU = pluginFile.getFileExtension() == ".component";
if (isVST3 && format->getName() != "VST3") continue; if (isAU && format->getName() != "AudioUnit") continue;
format->findAllTypesForFile(typesFound, pluginFile.getFullPathName()); if (typesFound.size() > 0) break; } auto response = helper.sendCommand(loadCmd.dump());
if (typesFound.isEmpty()) try { if (onLoadFailed) onLoadFailed("Plugin format not recognized"); return; auto j = json::parse(response); if (j.value("ok", false)) { pluginLoaded = true; pluginName = juce::String(j["name"].get<std::string>()); pluginParamCount = j.value("params", 0); pluginPath = path; DBG("PluginBridgeProcessor: Loaded " + pluginName);
if (onPluginLoaded) juce::MessageManager::callAsync([this]() { if (onPluginLoaded) onPluginLoaded(); }); } else { pluginLoaded = false; auto error = juce::String(j.value("error", "unknown")); // If plugin failed in helper, blocklist it blocklist.addBlocked(path); if (onLoadFailed) onLoadFailed("Not compatible: " + error); } }
juce::String errorMessage; auto instance = formatManager.createPluginInstance( *typesFound[0], currentSampleRate, currentBlockSize, errorMessage);
if (instance == nullptr) catch (...) { DBG("PluginBridgeProcessor: Failed to load: " + errorMessage); pluginLoaded = false; blocklist.addBlocked(path); if (onLoadFailed) onLoadFailed("Failed to load: " + errorMessage); return; }
instance->enableAllBuses();
auto layout = juce::AudioProcessor::BusesLayout(); layout.inputBuses.add(juce::AudioChannelSet::stereo()); layout.outputBuses.add(juce::AudioChannelSet::stereo());
if (instance->checkBusesLayoutSupported(layout)) instance->setBusesLayout(layout);
instance->setRateAndBufferSizeDetails(currentSampleRate, currentBlockSize); instance->prepareToPlay(currentSampleRate, currentBlockSize);
{ juce::ScopedLock sl(pluginLock); hostedPlugin = std::move(instance); onLoadFailed("Helper communication error"); }
pluginPath = path; DBG("PluginBridgeProcessor: Loaded " + getLoadedPluginName() + " (" + juce::String(getLoadedPluginParamCount()) + " params)");
if (onPluginLoaded) onPluginLoaded();}
void PluginBridgeProcessor::unloadPlugin(){ { juce::ScopedLock sl(pluginLock); if (hostedPlugin) { hostedPlugin->releaseResources(); hostedPlugin.reset(); } } pluginPath.clear(); if (onPluginUnloaded) onPluginUnloaded();}
juce::String PluginBridgeProcessor::getLoadedPluginName() const{ juce::ScopedLock sl(pluginLock); return hostedPlugin ? hostedPlugin->getName() : juce::String();}
int PluginBridgeProcessor::getLoadedPluginParamCount() const{ juce::ScopedLock sl(pluginLock); return hostedPlugin ? hostedPlugin->getParameters().size() : 0;}
// --- Parameters ---
std::vector<PluginBridgeProcessor::ParamInfo> PluginBridgeProcessor::searchParams(const juce::String& keyword) const{ std::vector<ParamInfo> results; juce::ScopedLock sl(pluginLock); if (!hostedPlugin) return results;
auto& params = hostedPlugin->getParameters(); auto keywordLower = keyword.toLowerCase();
for (int i = 0; i < params.size(); ++i) { auto* param = params[i]; auto name = param->getName(128);
if (keyword.isEmpty() || name.toLowerCase().contains(keywordLower)) { ParamInfo info; info.index = i; info.name = name; info.value = param->getValue(); info.displayText = param->getText(param->getValue(), 64);
if (auto* hosted = dynamic_cast<juce::AudioPluginInstance::HostedParameter*>(param)) info.id = hosted->getParameterID(); else info.id = juce::String(i);
results.push_back(info); if (results.size() >= PluginBridgeConstants::kMaxParamResults) break; } } return results;} if (helper.isHelperRunning()) helper.sendCommand("{\"cmd\":\"unload\"}");
std::vector<std::pair<int, float>> PluginBridgeProcessor::getParams(const std::vector<int>& ids) const{ std::vector<std::pair<int, float>> results; juce::ScopedLock sl(pluginLock); if (!hostedPlugin) return results; pluginLoaded = false; pluginName.clear(); pluginPath.clear(); pluginParamCount = 0; remoteLayerPortName.clear(); remoteGuiWidth = 0; remoteGuiHeight = 0;
auto& params = hostedPlugin->getParameters(); for (int idx : ids) { if (idx >= 0 && idx < params.size()) results.push_back({idx, params[idx]->getValue()}); } return results; if (onPluginUnloaded) juce::MessageManager::callAsync([this]() { if (onPluginUnloaded) onPluginUnloaded(); });}
bool PluginBridgeProcessor::setParams(const std::map<int, float>& values)void PluginBridgeProcessor::showPluginGui(){ juce::ScopedLock sl(pluginLock); if (!hostedPlugin) return false;
auto& params = hostedPlugin->getParameters(); for (auto& [idx, val] : values) { if (idx >= 0 && idx < params.size()) { auto* param = params[idx]; param->beginChangeGesture(); param->setValueNotifyingHost(juce::jlimit(0.0f, 1.0f, val)); param->endChangeGesture(); } } return true; if (helper.isHelperRunning()) helper.sendCommand("{\"cmd\":\"show_gui\"}");}
// --- Hosted Plugin Editor ---
juce::AudioProcessorEditor* PluginBridgeProcessor::createHostedPluginEditor()void PluginBridgeProcessor::hidePluginGui(){ juce::ScopedLock sl(pluginLock); if (hostedPlugin && hostedPlugin->hasEditor()) return hostedPlugin->createEditor(); return nullptr; if (helper.isHelperRunning()) helper.sendCommand("{\"cmd\":\"hide_gui\"}");}
// --- Plugin List ---38 unmodified lines juce::ValueTree state("PluginBridgeState"); state.setProperty("pluginPath", pluginPath, nullptr);
juce::ScopedLock sl(pluginLock); if (hostedPlugin) if (pluginLoaded && helper.isHelperRunning()) { juce::MemoryBlock pluginState; hostedPlugin->getStateInformation(pluginState); state.setProperty("pluginState", pluginState.toBase64Encoding(), nullptr); auto response = helper.sendCommand("{\"cmd\":\"get_state\"}"); try { auto j = json::parse(response); if (j.value("ok", false)) state.setProperty("pluginState", juce::String(j["state"].get<std::string>()), nullptr); } catch (...) {} }
juce::MemoryOutputStream stream(destData, false);10 unmodified lines { loadPlugin(path);
auto pluginStateB64 = state.getProperty("pluginState").toString(); if (pluginStateB64.isNotEmpty()) auto pluginState = state.getProperty("pluginState").toString(); if (pluginState.isNotEmpty() && helper.isHelperRunning()) { juce::MemoryBlock pluginState; if (pluginState.fromBase64Encoding(pluginStateB64)) { juce::ScopedLock sl(pluginLock); if (hostedPlugin) hostedPlugin->setStateInformation(pluginState.getData(), (int)pluginState.getSize()); } json cmd = {{"cmd", "set_state"}, {"state", pluginState.toStdString()}}; helper.sendCommand(cmd.dump()); } } }}
// --- MCP ---
bool PluginBridgeProcessor::isMcpServerRunning() const{ return mcpServer && mcpServer->isRunning();Source/Plugin/PluginBridgeProcessor.cpp+148-296