Upload Source/Plugin/PluginBridgeProcessor.cpp
Browse files123456789101112131 unmodified line15161718192021222324252627282930313233343536371 unmodified line394041424344454647484950515253545556575859602 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751 unmodified line17717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736838 unmodified lines40740840941041141241341441541641741810 unmodified lines429430431432433434435436437438439440441442443444445446447448449#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 "json.hpp"using json = nlohmann::json;1 unmodified linePluginBridgeProcessor::PluginBridgeProcessor(): AudioProcessor(BusesProperties().withInput("Input", juce::AudioChannelSet::stereo(), true).withOutput("Output", juce::AudioChannelSet::stereo(), true)){#if JUCE_PLUGINHOST_VST3formatManager.addFormat(new juce::VST3PluginFormat());#endif#if JUCE_PLUGINHOST_AUformatManager.addFormat(new juce::AudioUnitPluginFormat());#endifmcpServer = std::make_unique<McpServer>(PluginBridgeConstants::kDefaultMcpPort, *this);mcpServer->start();}PluginBridgeProcessor::~PluginBridgeProcessor(){mcpServer->stop();unloadPlugin();}void PluginBridgeProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)1 unmodified linecurrentSampleRate = sampleRate;currentBlockSize = samplesPerBlock;juce::ScopedLock sl(pluginLock);if (hostedPlugin){hostedPlugin->setRateAndBufferSizeDetails(sampleRate, samplesPerBlock);hostedPlugin->prepareToPlay(sampleRate, samplesPerBlock);}}void PluginBridgeProcessor::releaseResources(){juce::ScopedLock sl(pluginLock);if (hostedPlugin)hostedPlugin->releaseResources();}void PluginBridgeProcessor::processBlock(juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midi){juce::ScopedNoDenormals noDenormals;2 unmodified linesfor (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 ---static juce::File findHelperBinary(){// Helper .app is bundled at: PluginBridge.vst3/Contents/Resources/PluginBridgeHelper.app// The actual executable is at: PluginBridgeHelper.app/Contents/MacOS/PluginBridgeHelperauto 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 {};}PluginBridgeProcessor::TestResult PluginBridgeProcessor::testPluginSafety(const juce::String& path){if (blocklist.isBlocked(path))return TestResult::Unsafe;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};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); // 50mswaitedMs += 50;}if (waitedMs >= timeoutMs){kill(pid, SIGKILL);waitpid(pid, &status, 0);DBG("testPluginSafety: Timed out for " + path);return TestResult::Unsafe;}if (WIFEXITED(status) && WEXITSTATUS(status) == 0){DBG("testPluginSafety: SAFE — " + path);return TestResult::Safe;}DBG("testPluginSafety: UNSAFE — " + path + " (exit: " + juce::String(WEXITSTATUS(status)) + ")");return TestResult::Unsafe;}// --- Plugin Loading ---void PluginBridgeProcessor::loadPlugin(const juce::String& path){unloadPlugin();if (blocklist.isBlocked(path)){if (onLoadFailed)1 unmodified linereturn;}juce::File pluginFile(path);if (!pluginFile.exists()){if (onLoadFailed)onLoadFailed("Plugin file not found");return;}// Test safety firstauto testResult = testPluginSafety(path);if (testResult == TestResult::Unsafe){blocklist.addBlocked(path);if (onLoadFailed)onLoadFailed("Not compatible with PluginBridge");return;}// Safe — load in-processjuce::OwnedArray<juce::PluginDescription> typesFound;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;}if (typesFound.isEmpty()){if (onLoadFailed)onLoadFailed("Plugin format not recognized");return;}juce::String errorMessage;auto instance = formatManager.createPluginInstance(*typesFound[0], currentSampleRate, currentBlockSize, errorMessage);if (instance == nullptr){DBG("PluginBridgeProcessor: Failed to load: " + errorMessage);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);}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();elseinfo.id = juce::String(i);results.push_back(info);if (results.size() >= PluginBridgeConstants::kMaxParamResults)break;}}return results;}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;auto& params = hostedPlugin->getParameters();for (int idx : ids){if (idx >= 0 && idx < params.size())results.push_back({idx, params[idx]->getValue()});}return results;}bool PluginBridgeProcessor::setParams(const std::map<int, float>& values){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;}// --- Hosted Plugin Editor ---juce::AudioProcessorEditor* PluginBridgeProcessor::createHostedPluginEditor(){juce::ScopedLock sl(pluginLock);if (hostedPlugin && hostedPlugin->hasEditor())return hostedPlugin->createEditor();return nullptr;}// --- Plugin List ---38 unmodified linesjuce::ValueTree state("PluginBridgeState");state.setProperty("pluginPath", pluginPath, nullptr);juce::ScopedLock sl(pluginLock);if (hostedPlugin){juce::MemoryBlock pluginState;hostedPlugin->getStateInformation(pluginState);state.setProperty("pluginState", pluginState.toBase64Encoding(), nullptr);}juce::MemoryOutputStream stream(destData, false);10 unmodified lines{loadPlugin(path);auto pluginStateB64 = state.getProperty("pluginState").toString();if (pluginStateB64.isNotEmpty()){juce::MemoryBlock pluginState;if (pluginState.fromBase64Encoding(pluginStateB64)){juce::ScopedLock sl(pluginLock);if (hostedPlugin)hostedPlugin->setStateInformation(pluginState.getData(), (int)pluginState.getSize());}}}}}bool PluginBridgeProcessor::isMcpServerRunning() const{return mcpServer && mcpServer->isRunning();1234561 unmodified line89101112131415161718192021222324252627282930313233343536373839404142434445464748495051521 unmodified line5455565758596061626364656667686970717273747576777879802 unmodified lines83848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301 unmodified line13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022138 unmodified lines26026126226326426526626726826927027127227310 unmodified lines284285286287288289290291292293294295296297298299300301#include "PluginBridgeProcessor.h"#include "PluginBridgeEditor.h"#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)),mcpServer(std::make_unique<McpServer>(PluginBridgeConstants::kDefaultMcpPort, helper)){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 infohelper.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();helper.killHelper();}void PluginBridgeProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)1 unmodified linecurrentSampleRate = sampleRate;currentBlockSize = samplesPerBlock;if (helper.isHelperRunning()){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() {}void PluginBridgeProcessor::processBlock(juce::AudioBuffer<float>& buffer, juce::MidiBuffer&){juce::ScopedNoDenormals noDenormals;2 unmodified linesfor (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i)buffer.clear(i, 0, buffer.getNumSamples());if (!pluginLoaded || !helper.isHelperRunning())return;auto& shm = helper.getSharedAudio();if (!shm.isValid()) return;int numChannels = buffer.getNumChannels();int numSamples = buffer.getNumSamples();const float* inputPtrs[2] = {buffer.getReadPointer(0),numChannels > 1 ? buffer.getReadPointer(1) : buffer.getReadPointer(0)};shm.writeInput(inputPtrs, numChannels, numSamples);auto* header = shm.getHeader();header->blockSize.store((uint32_t)numSamples);header->numChannels.store((uint32_t)numChannels);header->state.store(kStateInputReady);helper.getInputSem().signal();if (helper.getOutputSem().wait(IPC::kProcessBlockTimeoutMs)){float* outputPtrs[2] = {buffer.getWritePointer(0),numChannels > 1 ? buffer.getWritePointer(1) : buffer.getWritePointer(0)};shm.readOutput(outputPtrs, numChannels, numSamples);header->state.store(kStateIdle);}}juce::AudioProcessorEditor* PluginBridgeProcessor::createEditor(){return new PluginBridgeEditor(*this);}// --- Plugin Loading ---void PluginBridgeProcessor::loadPlugin(const juce::String& path){if (blocklist.isBlocked(path)){if (onLoadFailed)1 unmodified linereturn;}if (!helper.isHelperRunning()){if (!helper.spawnHelper()){DBG("PluginBridgeProcessor: Failed to spawn helper");if (onLoadFailed)onLoadFailed("Failed to start helper process");return;}json configCmd = {{"cmd", "configure"},{"sampleRate", currentSampleRate},{"blockSize", currentBlockSize},{"channels", 2}};helper.sendCommand(configCmd.dump());}json loadCmd = {{"cmd", "load"},{"path", path.toStdString()},{"sampleRate", currentSampleRate},{"blockSize", currentBlockSize}};auto response = helper.sendCommand(loadCmd.dump());try{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 itblocklist.addBlocked(path);if (onLoadFailed)onLoadFailed("Not compatible: " + error);}}catch (...){pluginLoaded = false;blocklist.addBlocked(path);if (onLoadFailed)onLoadFailed("Helper communication error");}}void PluginBridgeProcessor::unloadPlugin(){if (helper.isHelperRunning())helper.sendCommand("{\"cmd\":\"unload\"}");pluginLoaded = false;pluginName.clear();pluginPath.clear();pluginParamCount = 0;remoteLayerPortName.clear();remoteGuiWidth = 0;remoteGuiHeight = 0;if (onPluginUnloaded)juce::MessageManager::callAsync([this]() { if (onPluginUnloaded) onPluginUnloaded(); });}void PluginBridgeProcessor::showPluginGui(){if (helper.isHelperRunning())helper.sendCommand("{\"cmd\":\"show_gui\"}");}void PluginBridgeProcessor::hidePluginGui(){if (helper.isHelperRunning())helper.sendCommand("{\"cmd\":\"hide_gui\"}");}// --- Plugin List ---38 unmodified linesjuce::ValueTree state("PluginBridgeState");state.setProperty("pluginPath", pluginPath, nullptr);if (pluginLoaded && helper.isHelperRunning()){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 pluginState = state.getProperty("pluginState").toString();if (pluginState.isNotEmpty() && helper.isHelperRunning()){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