File size: 8,801 Bytes
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
#include "HelperConnection.h"
#include "../Shared/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();
}

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

bool HelperConnection::spawnHelper()
{
    killHelper(); // Clean up any previous instance

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

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

    // 3. Create Unix domain socket (server side)
    auto socketPath = IPC::getSocketPath(myPid);
    unlink(socketPath.c_str()); // Remove stale socket

    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 socket");
        close(serverSocketFd);
        serverSocketFd = -1;
        return false;
    }

    // 4. Find helper binary (bundled inside .vst3/Contents/Resources/)
    auto helperPath = juce::File::getSpecialLocation(juce::File::currentExecutableFile)
                          .getParentDirectory()  // MacOS/
                          .getParentDirectory()  // Contents/
                          .getChildFile("Resources")
                          .getChildFile(PluginBridgeConstants::kHelperBinaryName);

    if (!helperPath.exists())
    {
        // Fallback: look next to the plugin binary (for development)
        helperPath = juce::File::getSpecialLocation(juce::File::currentExecutableFile)
                         .getParentDirectory()
                         .getChildFile(PluginBridgeConstants::kHelperBinaryName);
    }

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

    // 5. Spawn helper process
    state.store(State::Starting);

    auto pidStr = juce::String(myPid).toStdString();
    auto helperPathStr = helperPath.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 helper: " + juce::String(strerror(spawnResult)));
        state.store(State::Disconnected);
        return false;
    }

    helperPid = pid;
    helperRunning.store(true);

    // 6. Accept connection from helper (with timeout)
    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 helper connection");
        killHelper();
        return false;
    }

    // 7. Start IPC listen thread
    ipcRunning.store(true);
    ipcThread = std::thread([this]() { ipcListenLoop(); });

    // 8. Start crash detection timer
    startTimerHz(4);

    // Wait for "ready" notification (up to 5s)
    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();

    // Stop IPC
    ipcRunning.store(false);
    if (clientSocketFd >= 0) { close(clientSocketFd); clientSocketFd = -1; }
    if (serverSocketFd >= 0) { close(serverSocketFd); serverSocketFd = -1; }
    if (ipcThread.joinable()) ipcThread.join();

    // Kill helper process
    if (helperPid > 0 && helperRunning.load())
    {
        kill(helperPid, SIGTERM);
        int status;
        waitpid(helperPid, &status, WNOHANG);
        usleep(100000); // 100ms grace
        kill(helperPid, SIGKILL); // Force if still alive
        waitpid(helperPid, &status, 0);
    }
    helperPid = 0;
    helperRunning.store(false);

    // Clean up shared resources
    sharedAudio.destroy();
    inputSem.destroy();
    outputSem.destroy();

    // Remove socket file
    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\"}";

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

    // Wait for response (up to 5s)
    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;

    // Check if helper is still alive
    int status;
    pid_t result = waitpid(helperPid, &status, WNOHANG);

    if (result == helperPid)
    {
        // Helper has exited
        helperRunning.store(false);
        state.store(State::Crashed);
        stopTimer();

        DBG("HelperConnection: Helper process 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;

            // Check if it's a notification or a command response
            try
            {
                auto j = json::parse(msg);
                if (j.contains("notify"))
                {
                    handleNotification(msg);
                }
                else
                {
                    // It's a response to our command
                    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 == "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 (...) {}
}