File size: 9,305 Bytes
f36ed0a
 
3e55272
767fa15
f36ed0a
 
 
 
 
 
3e55272
 
f36ed0a
3e55272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06d413f
f36ed0a
 
 
 
06d413f
3e55272
f36ed0a
 
 
 
 
 
 
3e55272
f36ed0a
3e55272
 
 
 
 
 
 
 
 
 
 
 
 
f36ed0a
 
 
3e55272
f36ed0a
3e55272
f36ed0a
 
 
 
 
 
 
 
3e55272
 
767fa15
3e55272
 
767fa15
3e55272
 
767fa15
3e55272
 
 
767fa15
3e55272
767fa15
3e55272
 
 
 
767fa15
3e55272
767fa15
3e55272
767fa15
3e55272
 
 
 
 
 
767fa15
3e55272
767fa15
3e55272
 
 
767fa15
 
9e02f23
06d413f
 
 
 
 
 
767fa15
f36ed0a
06d413f
f36ed0a
3e55272
06d413f
3e55272
 
 
 
 
 
 
f36ed0a
3e55272
 
 
 
 
767fa15
 
3e55272
 
 
 
f36ed0a
3e55272
f36ed0a
3e55272
f36ed0a
3e55272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f36ed0a
3e55272
06d413f
3e55272
06d413f
 
3e55272
f36ed0a
 
 
06d413f
f36ed0a
3e55272
 
f36ed0a
3e55272
 
 
 
 
 
 
f36ed0a
3e55272
 
f36ed0a
 
3e55272
f36ed0a
3e55272
 
f36ed0a
 
3e55272
1dd0405
3e55272
 
1dd0405
 
06d413f
 
f36ed0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06d413f
 
 
 
 
 
 
 
 
 
 
 
3e55272
06d413f
3e55272
 
 
 
 
 
06d413f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e55272
 
06d413f
3e55272
 
06d413f
 
 
 
 
3e55272
 
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
#include "PluginBridgeProcessor.h"
#include "PluginBridgeEditor.h"
#include "IPCProtocol.h"

#include "json.hpp"
using json = nlohmann::json;

PluginBridgeProcessor::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 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();
    helper.killHelper();
}

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

    auto totalNumInputChannels = getTotalNumInputChannels();
    auto totalNumOutputChannels = getTotalNumOutputChannels();
    for (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)
            onLoadFailed("Not compatible (crashed previously)");
        return;
    }

    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 it
            blocklist.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 ---

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);

    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);
    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 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();
}

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

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