File size: 8,142 Bytes
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
#include "PluginBridgeProcessor.h"
#include "PluginBridgeEditor.h"
#include "../Shared/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(PluginBridgeConstants::kDefaultMcpPort, helper)
{
    // Set up crash callback
    helper.onHelperCrashed = [this]()
    {
        pluginLoaded = false;
        pluginName.clear();
        pluginParamCount = 0;
        DBG("PluginBridgeProcessor: Helper crashed — plugin unloaded");
    };

    mcpServer.start();
}

PluginBridgeProcessor::~PluginBridgeProcessor()
{
    mcpServer.stop();
    helper.killHelper();
}

void PluginBridgeProcessor::prepareToPlay(double sampleRate, int samplesPerBlock)
{
    currentSampleRate = sampleRate;
    currentBlockSize = samplesPerBlock;

    // If helper is connected, configure it
    if (helper.isHelperRunning())
    {
        json cmd = {{"cmd", "configure"},
                    {"sampleRate", sampleRate},
                    {"blockSize", samplesPerBlock},
                    {"channels", 2}};
        helper.sendCommand(cmd.dump());

        // Update shared memory header
        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 no plugin loaded or helper not running, pass through
    if (!pluginLoaded || !helper.isHelperRunning())
        return;

    auto& shm = helper.getSharedAudio();
    if (!shm.isValid()) return;

    int numChannels = buffer.getNumChannels();
    int numSamples = buffer.getNumSamples();

    // Write input to shared memory
    const float* inputPtrs[2] = {
        buffer.getReadPointer(0),
        numChannels > 1 ? buffer.getReadPointer(1) : buffer.getReadPointer(0)
    };
    shm.writeInput(inputPtrs, numChannels, numSamples);

    // Update header
    auto* header = shm.getHeader();
    header->blockSize.store((uint32_t)numSamples);
    header->numChannels.store((uint32_t)numChannels);
    header->state.store(kStateInputReady);

    // Signal helper: input is ready
    helper.getInputSem().signal();

    // Wait for helper to finish processing (with timeout)
    if (helper.getOutputSem().wait(IPC::kProcessBlockTimeoutMs))
    {
        // Read output from shared memory
        float* outputPtrs[2] = {
            buffer.getWritePointer(0),
            numChannels > 1 ? buffer.getWritePointer(1) : buffer.getWritePointer(0)
        };
        shm.readOutput(outputPtrs, numChannels, numSamples);
        header->state.store(kStateIdle);
    }
    else
    {
        // Timeout — helper might be stuck or crashed. Pass through silence.
        // (Don't pass through input — if plugin was supposed to process, silence is safer)
    }
}

juce::AudioProcessorEditor* PluginBridgeProcessor::createEditor()
{
    return new PluginBridgeEditor(*this);
}

void PluginBridgeProcessor::getStateInformation(juce::MemoryBlock& destData)
{
    juce::ValueTree state("PluginBridgeState");
    state.setProperty("pluginPath", pluginPath, nullptr);

    // Get plugin state from helper
    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);

            // Restore plugin state after loading
            auto pluginState = state.getProperty("pluginState").toString();
            if (pluginState.isNotEmpty() && helper.isHelperRunning())
            {
                json cmd = {{"cmd", "set_state"}, {"state", pluginState.toStdString()}};
                helper.sendCommand(cmd.dump());
            }
        }
    }
}

bool PluginBridgeProcessor::isMcpServerRunning() const
{
    return mcpServer.isRunning();
}

int PluginBridgeProcessor::getMcpServerPort() const
{
    return mcpServer.getPort();
}

void PluginBridgeProcessor::loadPlugin(const juce::String& path)
{
    // Spawn helper if not running
    if (!helper.isHelperRunning())
    {
        if (!helper.spawnHelper())
        {
            DBG("PluginBridgeProcessor: Failed to spawn helper");
            return;
        }

        // Configure helper with current audio settings
        json configCmd = {{"cmd", "configure"},
                          {"sampleRate", currentSampleRate},
                          {"blockSize", currentBlockSize},
                          {"channels", 2}};
        helper.sendCommand(configCmd.dump());
    }

    // Send load command
    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 + " (" + juce::String(pluginParamCount) + " params)");
        }
        else
        {
            pluginLoaded = false;
            DBG("PluginBridgeProcessor: Failed to load: " + juce::String(j.value("error", "unknown")));
        }
    }
    catch (...)
    {
        pluginLoaded = false;
    }
}

void PluginBridgeProcessor::unloadPlugin()
{
    if (helper.isHelperRunning())
        helper.sendCommand("{\"cmd\":\"unload\"}");

    pluginLoaded = false;
    pluginName.clear();
    pluginPath.clear();
    pluginParamCount = 0;
}

void PluginBridgeProcessor::showPluginGui()
{
    if (helper.isHelperRunning())
        helper.sendCommand("{\"cmd\":\"show_gui\"}");
}

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

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