File size: 13,358 Bytes
f36ed0a
 
06d413f
f36ed0a
767fa15
 
 
 
 
 
 
f36ed0a
 
 
 
 
 
06d413f
f36ed0a
06d413f
 
 
 
 
 
 
 
 
f36ed0a
 
 
 
06d413f
 
f36ed0a
 
 
 
 
 
 
06d413f
 
f36ed0a
06d413f
 
f36ed0a
 
 
 
 
06d413f
 
 
f36ed0a
 
06d413f
f36ed0a
 
 
 
 
 
 
 
06d413f
 
 
 
 
 
 
 
 
 
767fa15
 
 
 
9e02f23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
767fa15
 
 
 
 
 
 
 
 
 
9e02f23
 
767fa15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e02f23
 
767fa15
 
 
 
 
 
 
 
 
9e02f23
767fa15
 
 
 
 
 
 
 
 
 
 
 
 
9e02f23
767fa15
 
 
 
 
9e02f23
767fa15
 
 
9e02f23
767fa15
 
 
9e02f23
06d413f
 
 
 
 
 
 
 
767fa15
f36ed0a
06d413f
f36ed0a
06d413f
 
 
 
 
 
 
f36ed0a
9e02f23
767fa15
 
 
 
 
 
 
 
 
9e02f23
06d413f
f36ed0a
06d413f
 
 
 
 
f36ed0a
06d413f
 
f36ed0a
06d413f
 
 
 
f36ed0a
06d413f
f36ed0a
06d413f
 
 
f36ed0a
 
06d413f
 
 
f36ed0a
06d413f
 
 
 
 
 
 
 
 
 
f36ed0a
06d413f
 
 
 
 
 
 
 
 
 
f36ed0a
06d413f
 
f36ed0a
 
06d413f
 
 
 
 
 
f36ed0a
 
06d413f
f36ed0a
 
06d413f
 
f36ed0a
06d413f
 
f36ed0a
 
06d413f
 
 
f36ed0a
 
06d413f
f36ed0a
06d413f
 
f36ed0a
 
06d413f
f36ed0a
06d413f
 
f36ed0a
 
06d413f
 
 
f36ed0a
06d413f
 
 
 
 
 
 
 
f36ed0a
06d413f
 
 
 
f36ed0a
06d413f
 
 
 
 
 
 
 
 
 
 
 
 
 
f36ed0a
 
06d413f
 
f36ed0a
06d413f
 
 
 
 
f36ed0a
06d413f
 
f36ed0a
06d413f
 
f36ed0a
06d413f
f36ed0a
 
06d413f
f36ed0a
06d413f
 
f36ed0a
06d413f
 
 
 
 
 
 
 
 
 
 
 
f36ed0a
 
06d413f
f36ed0a
06d413f
1dd0405
06d413f
 
 
 
1dd0405
 
06d413f
 
f36ed0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06d413f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f36ed0a
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
#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;

PluginBridgeProcessor::PluginBridgeProcessor()
    : AudioProcessor(BusesProperties()
                         .withInput("Input", juce::AudioChannelSet::stereo(), true)
                         .withOutput("Output", juce::AudioChannelSet::stereo(), true))
{
    #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);
    mcpServer->start();
}

PluginBridgeProcessor::~PluginBridgeProcessor()
{
    mcpServer->stop();
    unloadPlugin();
}

void PluginBridgeProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)
{
    currentSampleRate = 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;

    auto totalNumInputChannels = getTotalNumInputChannels();
    auto totalNumOutputChannels = getTotalNumOutputChannels();
    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 ---

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 {};
}

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); // 50ms
        waitedMs += 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)
            onLoadFailed("Not compatible (crashed previously)");
        return;
    }

    juce::File pluginFile(path);
    if (!pluginFile.exists())
    {
        if (onLoadFailed)
            onLoadFailed("Plugin file not found");
        return;
    }

    // Test safety first
    auto testResult = testPluginSafety(path);
    if (testResult == TestResult::Unsafe)
    {
        blocklist.addBlocked(path);
        if (onLoadFailed)
            onLoadFailed("Not compatible with PluginBridge");
        return;
    }

    // Safe — load in-process
    juce::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();
            else
                info.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 ---

juce::Array<juce::File> PluginBridgeProcessor::getInstalledPluginFiles() const
{
    juce::Array<juce::File> results;

    juce::Array<juce::File> dirs = {
        juce::File("/Library/Audio/Plug-Ins/VST3"),
        juce::File::getSpecialLocation(juce::File::userHomeDirectory)
            .getChildFile("Library/Audio/Plug-Ins/VST3"),
        juce::File("/Library/Audio/Plug-Ins/Components"),
        juce::File::getSpecialLocation(juce::File::userHomeDirectory)
            .getChildFile("Library/Audio/Plug-Ins/Components")
    };

    for (auto& dir : dirs)
    {
        if (dir.isDirectory())
        {
            auto vst3s = dir.findChildFiles(juce::File::findDirectories, false, "*.vst3");
            auto aus = dir.findChildFiles(juce::File::findDirectories, false, "*.component");
            results.addArray(vst3s);
            results.addArray(aus);
        }
    }

    results.sort();
    return results;
}

bool PluginBridgeProcessor::isBlocked(const juce::String& path) const
{
    return blocklist.isBlocked(path);
}

// --- State ---

void PluginBridgeProcessor::getStateInformation(juce::MemoryBlock& destData)
{
    juce::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);
    state.writeToStream(stream);
}

void PluginBridgeProcessor::setStateInformation(const void* data, int sizeInBytes)
{
    auto state = juce::ValueTree::readFromData(data, (size_t)sizeInBytes);
    if (state.isValid())
    {
        auto path = state.getProperty("pluginPath").toString();
        if (path.isNotEmpty())
        {
            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();
}

int PluginBridgeProcessor::getMcpServerPort() const
{
    return mcpServer ? mcpServer->getPort() : 0;
}

juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
    return new PluginBridgeProcessor();
}