File size: 9,045 Bytes
2871daa
7ba3088
2871daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ba3088
2871daa
 
 
 
 
 
 
 
 
7ba3088
2871daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ba3088
2871daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8335f9f
2871daa
 
 
 
 
8335f9f
 
 
 
 
 
 
 
 
2871daa
8335f9f
2871daa
8335f9f
 
 
 
 
 
2871daa
 
8335f9f
2871daa
8335f9f
2871daa
 
 
 
 
 
8335f9f
2871daa
 
 
 
 
 
 
 
 
 
 
 
8335f9f
2871daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8335f9f
2871daa
 
 
 
7ba3088
 
 
2871daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8335f9f
2871daa
 
 
 
 
 
 
 
 
7ba3088
 
2871daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ba3088
2871daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8335f9f
2871daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8335f9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2871daa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#include "HelperConnection.h"
#include "Constants.h"

#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <poll.h>
#include <spawn.h>

extern char** environ;

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

HelperConnection::HelperConnection()
{
    myPid = getpid();
    signal(SIGPIPE, SIG_IGN);
}

HelperConnection::~HelperConnection()
{
    killHelper();
}

bool HelperConnection::spawnHelper()
{
    killHelper();

    auto shmName = IPC::getShmName(myPid);
    if (!sharedAudio.create(shmName))
    {
        DBG("HelperConnection: Failed to create shared memory");
        return false;
    }

    if (!inputSem.create(IPC::getInputSemName(myPid)) ||
        !outputSem.create(IPC::getOutputSemName(myPid)))
    {
        DBG("HelperConnection: Failed to create semaphores");
        return false;
    }

    auto socketPath = IPC::getSocketPath(myPid);
    unlink(socketPath.c_str());

    serverSocketFd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (serverSocketFd < 0)
    {
        DBG("HelperConnection: Failed to create socket");
        return false;
    }

    struct sockaddr_un addr;
    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, socketPath.c_str(), sizeof(addr.sun_path) - 1);

    if (bind(serverSocketFd, (struct sockaddr*)&addr, sizeof(addr)) < 0 ||
        listen(serverSocketFd, 1) < 0)
    {
        DBG("HelperConnection: Failed to bind/listen");
        close(serverSocketFd);
        serverSocketFd = -1;
        return false;
    }

    // Find helper .app bundle inside .vst3/Contents/Resources/
    auto helperApp = juce::File::getSpecialLocation(juce::File::currentExecutableFile)
                         .getParentDirectory()   // MacOS/
                         .getParentDirectory()   // Contents/
                         .getChildFile("Resources")
                         .getChildFile("PluginBridgeHelper.app")
                         .getChildFile("Contents")
                         .getChildFile("MacOS")
                         .getChildFile(PluginBridgeConstants::kHelperBinaryName);

    if (!helperApp.exists())
    {
        // Fallback: bare binary
        helperApp = juce::File::getSpecialLocation(juce::File::currentExecutableFile)
                        .getParentDirectory()
                        .getParentDirectory()
                        .getChildFile("Resources")
                        .getChildFile(PluginBridgeConstants::kHelperBinaryName);
    }

    if (!helperApp.exists())
    {
        DBG("HelperConnection: Helper not found at: " + helperApp.getFullPathName());
        return false;
    }

    state.store(State::Starting);

    auto pidStr = juce::String(myPid).toStdString();
    auto helperPathStr = helperApp.getFullPathName().toStdString();

    pid_t pid;
    char* argv[] = {
        (char*)helperPathStr.c_str(),
        (char*)"--pid",
        (char*)pidStr.c_str(),
        nullptr
    };

    int spawnResult = posix_spawn(&pid, helperPathStr.c_str(), nullptr, nullptr, argv, environ);
    if (spawnResult != 0)
    {
        DBG("HelperConnection: Failed to spawn: " + juce::String(strerror(spawnResult)));
        state.store(State::Disconnected);
        return false;
    }

    helperPid = pid;
    helperRunning.store(true);

    struct pollfd pfd;
    pfd.fd = serverSocketFd;
    pfd.events = POLLIN;

    if (poll(&pfd, 1, IPC::kHelperTimeoutMs) <= 0)
    {
        DBG("HelperConnection: Helper didn't connect in time");
        killHelper();
        return false;
    }

    clientSocketFd = accept(serverSocketFd, nullptr, nullptr);
    if (clientSocketFd < 0)
    {
        DBG("HelperConnection: Failed to accept connection");
        killHelper();
        return false;
    }

    int nosigpipe = 1;
    setsockopt(clientSocketFd, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));

    ipcRunning.store(true);
    ipcThread = std::thread([this]() { ipcListenLoop(); });

    startTimerHz(4);

    int waitMs = 0;
    while (state.load() == State::Starting && waitMs < IPC::kHelperTimeoutMs)
    {
        juce::Thread::sleep(50);
        waitMs += 50;
    }

    return state.load() == State::Connected;
}

void HelperConnection::killHelper()
{
    stopTimer();
    ipcRunning.store(false);

    if (clientSocketFd >= 0) { close(clientSocketFd); clientSocketFd = -1; }
    if (serverSocketFd >= 0) { close(serverSocketFd); serverSocketFd = -1; }
    if (ipcThread.joinable()) ipcThread.join();

    if (helperPid > 0 && helperRunning.load())
    {
        kill(helperPid, SIGTERM);
        int status;
        waitpid(helperPid, &status, WNOHANG);
        usleep(100000);
        kill(helperPid, SIGKILL);
        waitpid(helperPid, &status, 0);
    }
    helperPid = 0;
    helperRunning.store(false);

    sharedAudio.destroy();
    inputSem.destroy();
    outputSem.destroy();

    unlink(IPC::getSocketPath(myPid).c_str());
    state.store(State::Disconnected);
}

std::string HelperConnection::sendCommand(const std::string& jsonCmd)
{
    std::lock_guard<std::mutex> lock(commandMutex);

    if (clientSocketFd < 0 || !helperRunning.load())
        return "{\"ok\":false,\"error\":\"not connected\"}";

    auto data = jsonCmd + "\n";
    if (::send(clientSocketFd, data.c_str(), data.size(), 0) < 0)
        return "{\"ok\":false,\"error\":\"send failed\"}";

    responseReady.store(false);
    int waitMs = 0;
    while (!responseReady.load() && waitMs < 5000)
    {
        juce::Thread::sleep(10);
        waitMs += 10;
    }

    if (!responseReady.load())
        return "{\"ok\":false,\"error\":\"timeout\"}";

    return lastResponse;
}

void HelperConnection::timerCallback()
{
    if (helperPid <= 0) return;

    int status;
    pid_t result = waitpid(helperPid, &status, WNOHANG);

    if (result == helperPid)
    {
        helperRunning.store(false);
        state.store(State::Crashed);
        stopTimer();
        DBG("HelperConnection: Helper died");
        if (onHelperCrashed)
            onHelperCrashed();
    }
}

void HelperConnection::ipcListenLoop()
{
    std::string buffer;
    char chunk[4096];

    while (ipcRunning.load())
    {
        struct pollfd pfd;
        pfd.fd = clientSocketFd;
        pfd.events = POLLIN;

        int ret = poll(&pfd, 1, 200);
        if (ret <= 0) continue;

        ssize_t n = recv(clientSocketFd, chunk, sizeof(chunk) - 1, 0);
        if (n <= 0)
        {
            if (ipcRunning.load())
            {
                helperRunning.store(false);
                state.store(State::Crashed);
                if (onHelperCrashed)
                    juce::MessageManager::callAsync([this]() { if (onHelperCrashed) onHelperCrashed(); });
            }
            return;
        }

        chunk[n] = '\0';
        buffer += chunk;

        size_t pos;
        while ((pos = buffer.find('\n')) != std::string::npos)
        {
            auto msg = buffer.substr(0, pos);
            buffer.erase(0, pos + 1);

            if (msg.empty()) continue;

            try
            {
                auto j = json::parse(msg);
                if (j.contains("notify"))
                    handleNotification(msg);
                else
                {
                    lastResponse = msg;
                    responseReady.store(true);
                }
            }
            catch (...) {}
        }
    }
}

void HelperConnection::handleNotification(const std::string& jsonStr)
{
    try
    {
        auto j = json::parse(jsonStr);
        auto notify = j.value("notify", "");

        if (notify == "ready")
        {
            state.store(State::Connected);
            if (onHelperReady)
                juce::MessageManager::callAsync([this]() { if (onHelperReady) onHelperReady(); });
        }
        else if (notify == "gui_ready")
        {
            auto portName = juce::String(j.value("layerPortName", ""));
            int width = j.value("width", 0);
            int height = j.value("height", 0);
            if (onGuiReady)
                juce::MessageManager::callAsync([this, portName, width, height]()
                    { if (onGuiReady) onGuiReady(portName, width, height); });
        }
        else if (notify == "resized")
        {
            int width = j.value("width", 0);
            int height = j.value("height", 0);
            if (onGuiResized)
                juce::MessageManager::callAsync([this, width, height]()
                    { if (onGuiResized) onGuiResized(width, height); });
        }
        else if (notify == "param_changed")
        {
            int index = j.value("index", -1);
            float value = j.value("value", 0.0f);
            if (onParamChanged)
                onParamChanged(index, value);
        }
        else if (notify == "crashed")
        {
            state.store(State::Crashed);
            if (onHelperCrashed)
                juce::MessageManager::callAsync([this]() { if (onHelperCrashed) onHelperCrashed(); });
        }
    }
    catch (...) {}
}