forked from VCVRack/Rack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbridge.cpp
439 lines (371 loc) · 8.94 KB
/
bridge.cpp
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#include "bridge.hpp"
#include "util/common.hpp"
#include "dsp/ringbuffer.hpp"
#include <unistd.h>
#if ARCH_WIN
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <fcntl.h>
#endif
#include <thread>
namespace rack {
struct BridgeClientConnection;
static BridgeClientConnection *connections[BRIDGE_NUM_PORTS] = {};
static AudioIO *audioListeners[BRIDGE_NUM_PORTS] = {};
static std::thread serverThread;
static bool serverRunning = false;
static BridgeMidiDriver *driver = NULL;
struct BridgeClientConnection {
int client;
bool ready = false;
int port = -1;
int sampleRate = 0;
~BridgeClientConnection() {
setPort(-1);
}
/** Returns true if successful */
bool send(const void *buffer, int length) {
if (length <= 0)
return false;
#if ARCH_LIN
int flags = MSG_NOSIGNAL;
#else
int flags = 0;
#endif
ssize_t remaining = 0;
while (remaining < length) {
ssize_t actual = ::send(client, (const char*) buffer, length, flags);
if (actual <= 0) {
ready = false;
return false;
}
remaining += actual;
}
return true;
}
template <typename T>
bool send(T x) {
return send(&x, sizeof(x));
}
/** Returns true if successful */
bool recv(void *buffer, int length) {
if (length <= 0)
return false;
#if ARCH_LIN
int flags = MSG_NOSIGNAL;
#else
int flags = 0;
#endif
ssize_t remaining = 0;
while (remaining < length) {
ssize_t actual = ::recv(client, (char*) buffer + remaining, length - remaining, flags);
if (actual <= 0) {
ready = false;
return false;
}
remaining += actual;
}
return true;
}
template <typename T>
bool recv(T *x) {
return recv(x, sizeof(*x));
}
void flush() {
// Turn off Nagle
int flag = 1;
setsockopt(client, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(int));
// Turn on Nagle
flag = 0;
setsockopt(client, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(int));
}
void run() {
info("Bridge client connected");
// Check hello key
uint32_t hello = -1;
recv<uint32_t>(&hello);
if (hello != BRIDGE_HELLO) {
info("Bridge client protocol mismatch %x %x", hello, BRIDGE_HELLO);
return;
}
// Process commands until no longer ready
ready = true;
while (ready) {
step();
}
info("Bridge client closed");
}
/** Accepts a command from the client */
void step() {
uint8_t command;
if (!recv<uint8_t>(&command)) {
return;
}
switch (command) {
default:
case NO_COMMAND: {
warn("Bridge client: bad command %d detected, closing", command);
ready = false;
} break;
case QUIT_COMMAND: {
ready = false;
} break;
case PORT_SET_COMMAND: {
uint8_t port = -1;
recv<uint8_t>(&port);
setPort(port);
} break;
case MIDI_MESSAGE_COMMAND: {
MidiMessage message;
if (!recv(&message, 3)) {
return;
}
processMidi(message);
} break;
case AUDIO_SAMPLE_RATE_SET_COMMAND: {
uint32_t sampleRate = 0;
recv<uint32_t>(&sampleRate);
setSampleRate(sampleRate);
} break;
case AUDIO_PROCESS_COMMAND: {
uint32_t frames = 0;
recv<uint32_t>(&frames);
if (frames == 0 || frames > (1<<16)) {
ready = false;
return;
}
float input[BRIDGE_INPUTS * frames];
if (!recv(&input, BRIDGE_INPUTS * frames * sizeof(float))) {
debug("Failed to receive");
return;
}
float output[BRIDGE_OUTPUTS * frames];
memset(&output, 0, sizeof(output));
processStream(input, output, frames);
if (!send(&output, BRIDGE_OUTPUTS * frames * sizeof(float))) {
debug("Failed to send");
return;
}
// flush();
} break;
}
}
void setPort(int port) {
// Unbind from existing port
if (0 <= this->port && connections[this->port] == this) {
connections[this->port] = NULL;
}
// Bind to new port
if ((0 <= port && port < BRIDGE_NUM_PORTS) && !connections[port]) {
this->port = port;
connections[this->port] = this;
refreshAudio();
}
else {
this->port = -1;
}
}
void processMidi(MidiMessage message) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (!driver)
return;
driver->devices[port].onMessage(message);
}
void setSampleRate(int sampleRate) {
this->sampleRate = sampleRate;
refreshAudio();
}
void processStream(const float *input, float *output, int frames) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (!audioListeners[port])
return;
audioListeners[port]->setBlockSize(frames);
audioListeners[port]->processStream(input, output, frames);
}
void refreshAudio() {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (connections[port] != this)
return;
if (!audioListeners[port])
return;
audioListeners[port]->setSampleRate(sampleRate);
}
};
static void clientRun(int client) {
defer({
#if ARCH_WIN
if (shutdown(client, SD_SEND)) {
warn("Bridge client shutdown() failed");
}
if (closesocket(client)) {
warn("Bridge client closesocket() failed");
}
#else
if (close(client)) {
warn("Bridge client close() failed");
}
#endif
});
#if ARCH_MAC
// Avoid SIGPIPE
int flag = 1;
if (setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(int))) {
warn("Bridge client setsockopt() failed");
return;
}
#endif
// Disable non-blocking
#if ARCH_WIN
unsigned long blockingMode = 0;
if (ioctlsocket(client, FIONBIO, &blockingMode)) {
warn("Bridge client ioctlsocket() failed");
return;
}
#else
if (fcntl(client, F_SETFL, fcntl(client, F_GETFL, 0) & ~O_NONBLOCK)) {
warn("Bridge client fcntl() failed");
return;
}
#endif
BridgeClientConnection connection;
connection.client = client;
connection.run();
}
static void serverConnect() {
// Initialize sockets
#if ARCH_WIN
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
warn("Bridge server WSAStartup() failed");
return;
}
defer({
WSACleanup();
});
#endif
// Get address
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(BRIDGE_PORT);
#if ARCH_WIN
addr.sin_addr.s_addr = inet_addr(BRIDGE_HOST);
#else
inet_pton(AF_INET, BRIDGE_HOST, &addr.sin_addr);
#endif
// Open socket
int server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server < 0) {
warn("Bridge server socket() failed");
return;
}
defer({
if (close(server)) {
warn("Bridge server close() failed");
return;
}
info("Bridge server closed");
});
#if ARCH_MAC || ARCH_LIN
int reuseAddrFlag = 1;
setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuseAddrFlag, sizeof(reuseAddrFlag));
#endif
// Bind socket to address
if (bind(server, (struct sockaddr*) &addr, sizeof(addr))) {
warn("Bridge server bind() failed");
return;
}
// Listen for clients
if (listen(server, 20)) {
warn("Bridge server listen() failed");
return;
}
info("Bridge server started");
// Enable non-blocking
#if ARCH_WIN
unsigned long blockingMode = 1;
if (ioctlsocket(server, FIONBIO, &blockingMode)) {
warn("Bridge server ioctlsocket() failed");
return;
}
#else
int flags = fcntl(server, F_GETFL, 0);
fcntl(server, F_SETFL, flags | O_NONBLOCK);
#endif
// Accept clients
while (serverRunning) {
int client = accept(server, NULL, NULL);
if (client < 0) {
// Wait a bit before attempting to accept another client
std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
continue;
}
// Launch client thread
std::thread clientThread(clientRun, client);
clientThread.detach();
}
}
static void serverRun() {
while (serverRunning) {
std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
serverConnect();
}
}
std::vector<int> BridgeMidiDriver::getInputDeviceIds() {
std::vector<int> deviceIds;
for (int i = 0; i < 16; i++) {
deviceIds.push_back(i);
}
return deviceIds;
}
std::string BridgeMidiDriver::getInputDeviceName(int deviceId) {
if (deviceId < 0)
return "";
return stringf("Port %d", deviceId + 1);
}
MidiInputDevice *BridgeMidiDriver::subscribeInputDevice(int deviceId, MidiInput *midiInput) {
if (!(0 <= deviceId && deviceId < 16))
return NULL;
devices[deviceId].subscribe(midiInput);
return &devices[deviceId];
}
void BridgeMidiDriver::unsubscribeInputDevice(int deviceId, MidiInput *midiInput) {
if (!(0 <= deviceId && deviceId < 16))
return;
devices[deviceId].unsubscribe(midiInput);
}
void bridgeInit() {
serverRunning = true;
serverThread = std::thread(serverRun);
driver = new BridgeMidiDriver();
midiDriverAdd(BRIDGE_DRIVER, driver);
}
void bridgeDestroy() {
serverRunning = false;
serverThread.join();
}
void bridgeAudioSubscribe(int port, AudioIO *audio) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
// Check if an Audio is already subscribed on the port
if (audioListeners[port])
return;
audioListeners[port] = audio;
if (connections[port])
connections[port]->refreshAudio();
}
void bridgeAudioUnsubscribe(int port, AudioIO *audio) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (audioListeners[port] != audio)
return;
audioListeners[port] = NULL;
}
} // namespace rack