File size: 1,844 Bytes
8957da4
 
 
122bd54
8957da4
 
 
 
 
 
2be9229
 
8957da4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24a3c7f
 
8957da4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2be9229
8957da4
 
 
 
 
 
 
 
 
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
#pragma once

#include <juce_core/juce_core.h>
#include <juce_events/juce_events.h>
#include <string>
#include <thread>
#include <atomic>
#include <functional>
#include <mutex>

#include "SharedAudioBuffer.h"
#include "IPCProtocol.h"

class HelperConnection : private juce::Timer
{
public:
    HelperConnection();
    ~HelperConnection();

    // Lifecycle
    bool spawnHelper();
    void killHelper();
    bool isHelperRunning() const { return helperRunning.load(); }

    // Audio bridge
    SharedAudioBuffer& getSharedAudio() { return sharedAudio; }
    SharedSemaphore& getInputSem() { return inputSem; }
    SharedSemaphore& getOutputSem() { return outputSem; }

    // Send commands (blocking — waits for response)
    std::string sendCommand(const std::string& json);

    // State
    enum class State { Disconnected, Starting, Connected, Crashed };
    State getState() const { return state.load(); }

    // Callbacks
    std::function<void()> onHelperReady;
    std::function<void()> onHelperCrashed;
    std::function<void(int, float)> onParamChanged;
    std::function<void(const juce::String&, int, int)> onGuiReady;   // portName, width, height
    std::function<void(int, int)> onGuiResized;                       // width, height

private:
    void timerCallback() override;
    void ipcListenLoop();
    void handleNotification(const std::string& json);

    pid_t helperPid = 0;
    std::atomic<bool> helperRunning{false};
    std::atomic<State> state{State::Disconnected};

    SharedAudioBuffer sharedAudio;
    SharedSemaphore inputSem;
    SharedSemaphore outputSem;

    int serverSocketFd = -1;
    int clientSocketFd = -1;
    std::thread ipcThread;
    std::atomic<bool> ipcRunning{false};

    std::mutex commandMutex;
    std::string lastResponse;
    std::atomic<bool> responseReady{false};

    int myPid;
};