-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathArtnetOutput.h
More file actions
379 lines (321 loc) · 13 KB
/
ArtnetOutput.h
File metadata and controls
379 lines (321 loc) · 13 KB
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
// Super Timecode Converter
// Copyright (c) 2026 Fiverecords -- MIT License
// https://github.com/fiverecords/SuperTimecodeConverter
#pragma once
#include <JuceHeader.h>
#include "TimecodeCore.h"
#include "NetworkUtils.h"
#include <atomic>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#endif
class ArtnetOutput : public juce::HighResolutionTimer
{
public:
ArtnetOutput()
{
refreshNetworkInterfaces();
}
~ArtnetOutput() override
{
stop();
}
//==============================================================================
void refreshNetworkInterfaces()
{
availableInterfaces = ::getNetworkInterfaces();
}
juce::StringArray getInterfaceNames() const
{
juce::StringArray names;
for (auto& ni : availableInterfaces)
names.add(ni.name + " (" + ni.ip + ")");
return names;
}
int getInterfaceCount() const { return availableInterfaces.size(); }
juce::String getInterfaceInfo(int index) const
{
if (index >= 0 && index < availableInterfaces.size())
return availableInterfaces[index].ip + " -> " + availableInterfaces[index].broadcast;
return "";
}
//==============================================================================
bool start(int interfaceIndex = -1, int targetPort = 6454)
{
stop();
destPort = targetPort;
if (interfaceIndex >= 0 && interfaceIndex < availableInterfaces.size())
{
selectedInterface = interfaceIndex;
broadcastIp = availableInterfaces[interfaceIndex].broadcast;
bindIp = availableInterfaces[interfaceIndex].ip;
}
else
{
selectedInterface = -1;
broadcastIp = "255.255.255.255";
bindIp = "0.0.0.0";
}
socket = std::make_unique<juce::DatagramSocket>(false);
if (!socket->bindToPort(0, bindIp))
{
if (!socket->bindToPort(0))
{
socket = nullptr;
return false;
}
}
// Enable SO_BROADCAST so the OS allows sending to broadcast addresses.
// Some systems (especially Linux) reject broadcast sends without this.
auto rawSock = socket->getRawSocketHandle();
if (rawSock >= 0)
{
int broadcastFlag = 1;
#ifdef _WIN32
setsockopt(rawSock, SOL_SOCKET, SO_BROADCAST,
(const char*)&broadcastFlag, sizeof(broadcastFlag));
#else
setsockopt(rawSock, SOL_SOCKET, SO_BROADCAST,
&broadcastFlag, sizeof(broadcastFlag));
#endif
}
isRunningFlag.store(true, std::memory_order_relaxed);
paused.store(false, std::memory_order_relaxed);
sendErrors.store(0, std::memory_order_relaxed);
artnetSeeded = false;
updateTimerRate();
return true;
}
void stop()
{
stopTimer();
isRunningFlag.store(false, std::memory_order_relaxed);
paused.store(false, std::memory_order_relaxed);
if (socket != nullptr)
{
socket->shutdown();
socket = nullptr;
}
}
bool getIsRunning() const { return isRunningFlag.load(std::memory_order_relaxed); }
juce::String getBroadcastIp() const { return broadcastIp; }
int getSelectedInterface() const { return selectedInterface; }
uint32_t getSendErrors() const { return sendErrors.load(std::memory_order_relaxed); }
//==============================================================================
void setTimecode(const Timecode& tc)
{
const juce::SpinLock::ScopedLockType lock(tcLock);
timecodeToSend = tc;
}
// Called from UI thread. startTimer() is internally serialised in JUCE's
// HighResolutionTimer, so calling it from the message thread is safe.
void setFrameRate(FrameRate fps)
{
auto prev = currentFps.load(std::memory_order_relaxed);
if (prev != fps)
{
currentFps.store(fps, std::memory_order_relaxed);
if (isRunningFlag.load(std::memory_order_relaxed) && !paused.load(std::memory_order_relaxed))
updateTimerRate();
}
}
// Pause/resume transmission
void setPaused(bool shouldPause)
{
if (paused.load(std::memory_order_relaxed) == shouldPause)
return;
paused.store(shouldPause, std::memory_order_relaxed);
if (shouldPause)
{
stopTimer();
}
else if (isRunningFlag.load(std::memory_order_relaxed))
{
artnetSeeded = false;
lastFrameSendTime.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
updateTimerRate();
}
}
bool isPaused() const { return paused.load(std::memory_order_relaxed); }
/// Force immediate ArtTimeCode frame send.
/// Call on seek/hot cue/track change so receivers update instantly
/// instead of waiting for the next timer tick (up to 1 frame latency).
void forceResync()
{
if (!isRunningFlag.load(std::memory_order_relaxed)
|| paused.load(std::memory_order_relaxed)
|| socket == nullptr)
return;
artnetSeeded = false;
FrameRate fps = currentFps.load(std::memory_order_relaxed);
sendArtTimeCode(fps);
}
//==============================================================================
// Art-Net DMX output (OpDmx 0x5000)
//
// Sends a DMX512 frame using the same socket/interface as timecode output.
// Can be called independently of timecode pause state -- mixer data flows
// regardless of whether timecode is active.
//
// dmxData: up to 512 bytes of DMX channel values (channel 1 at index 0)
// numChannels: how many channels to send (1-512, will be rounded up to even)
// universe: Art-Net universe (0-32767, default 0)
//==============================================================================
void sendDmxFrame(const uint8_t* dmxData, int numChannels, int universe = 0)
{
if (!isRunningFlag.load(std::memory_order_relaxed) || socket == nullptr)
return;
numChannels = juce::jlimit(2, 512, numChannels);
if (numChannels % 2 != 0) numChannels++; // Art-Net requires even length
uint8_t packet[530] = {}; // 18 header + 512 max data
// Art-Net header
packet[0] = 'A'; packet[1] = 'r'; packet[2] = 't'; packet[3] = '-';
packet[4] = 'N'; packet[5] = 'e'; packet[6] = 't'; packet[7] = 0;
// OpDmx = 0x5000 (little-endian)
packet[8] = 0x00;
packet[9] = 0x50;
// Protocol version 14 (big-endian)
packet[10] = 0x00;
packet[11] = 0x0E;
// Sequence (incrementing, 1-255, 0 = disable sequencing)
dmxSequence = (dmxSequence % 255) + 1;
packet[12] = dmxSequence;
// Physical port
packet[13] = 0;
// Universe (little-endian, 15-bit)
packet[14] = uint8_t(universe & 0xFF);
packet[15] = uint8_t((universe >> 8) & 0x7F);
// Length (big-endian)
packet[16] = uint8_t((numChannels >> 8) & 0xFF);
packet[17] = uint8_t(numChannels & 0xFF);
// DMX data
std::memcpy(packet + 18, dmxData, (size_t)numChannels);
int written = socket->write(broadcastIp, destPort, packet, 18 + numChannels);
if (written < 0)
sendErrors.fetch_add(1, std::memory_order_relaxed);
}
private:
void hiResTimerCallback() override
{
if (!isRunningFlag.load(std::memory_order_relaxed)
|| paused.load(std::memory_order_relaxed)
|| socket == nullptr)
{
stopTimer(); // Don't spin at 1000Hz when there's nothing to send
return;
}
// Single atomic read -- guarantees frame interval and packet rate code are consistent
FrameRate fps = currentFps.load(std::memory_order_relaxed);
// Fractional accumulator: compare real elapsed time against ideal frame interval
// to eliminate drift caused by integer-ms timer resolution
double now = juce::Time::getMillisecondCounterHiRes();
// ArtNet TimeCode is a digital protocol -- always send at nominal frame rate.
// The timecode VALUES advance slower at low pitch (PLL handles that),
// producing repeated frames, which is correct. Scaling the interval
// caused receivers to lose sync or stop at low pitch.
double frameInterval = 1000.0 / frameRateToDouble(fps);
// Allow up to 2 catch-up sends per callback to handle jitter
int sent = 0;
double lastSend = lastFrameSendTime.load(std::memory_order_relaxed);
while ((now - lastSend) >= frameInterval && sent < 2)
{
sendArtTimeCode(fps);
// Advance by ideal interval (not by 'now') to prevent cumulative drift
lastSend += frameInterval;
sent++;
}
lastFrameSendTime.store(lastSend, std::memory_order_relaxed);
// If we fell too far behind (>100ms), reset to avoid a burst
if ((now - lastSend) > 100.0)
lastFrameSendTime.store(now, std::memory_order_relaxed);
}
void sendArtTimeCode(FrameRate fps)
{
Timecode pending;
{
const juce::SpinLock::ScopedLockType lock(tcLock);
pending = timecodeToSend;
}
// Auto-increment: advance by 1 frame per send. Compare with
// pendingTimecode and only resync on diff > 1 (seek/jump).
// Prevents 1-frame backward jitter from interpolation overshoot.
// Same architectural pattern as the LTC and MTC encoders.
Timecode tc;
if (!artnetSeeded)
{
tc = pending;
artnetSeeded = true;
}
else
{
tc = incrementFrame(encoderTc, fps);
int maxFrames = frameRateToInt(fps);
auto toTotal = [maxFrames](const Timecode& t) -> int64_t {
return (int64_t)t.hours * 3600 * maxFrames
+ (int64_t)t.minutes * 60 * maxFrames
+ (int64_t)t.seconds * maxFrames
+ (int64_t)t.frames;
};
int64_t dayFrames = (int64_t)24 * 3600 * maxFrames;
int64_t rawDiff = toTotal(pending) - toTotal(tc);
int64_t diff = ((rawDiff % dayFrames) + dayFrames) % dayFrames;
if (diff > dayFrames / 2) diff = dayFrames - diff;
if (diff > 1)
tc = pending;
}
encoderTc = tc;
// Validate ranges -- don't send corrupt data to the network
int maxFrames = frameRateToInt(fps);
if (tc.hours > 23 || tc.minutes > 59 || tc.seconds > 59 || tc.frames >= maxFrames)
return;
uint8_t packet[19] = {};
packet[0] = 'A';
packet[1] = 'r';
packet[2] = 't';
packet[3] = '-';
packet[4] = 'N';
packet[5] = 'e';
packet[6] = 't';
packet[7] = 0;
packet[8] = 0x00;
packet[9] = 0x97;
packet[10] = 0x00; // ProtVer Hi (big-endian)
packet[11] = 0x0E; // ProtVer Lo = 14 (Art-Net 4 standard)
packet[12] = 0; // Filler1 -- reserved, must be 0 (Art-Net 4 spec Sec.12)
packet[13] = 0; // Filler2 -- reserved, must be 0 (Art-Net 4 spec Sec.12)
packet[14] = (uint8_t)tc.frames;
packet[15] = (uint8_t)tc.seconds;
packet[16] = (uint8_t)tc.minutes;
packet[17] = (uint8_t)tc.hours;
packet[18] = (uint8_t)fpsToRateCode(fps);
int written = socket->write(broadcastIp, destPort, packet, sizeof(packet));
if (written < 0)
sendErrors.fetch_add(1, std::memory_order_relaxed);
}
void updateTimerRate()
{
// Run timer at 1ms fixed rate -- the fractional accumulator in
// hiResTimerCallback handles exact frame timing to avoid drift
lastFrameSendTime.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
startTimer(1);
}
std::unique_ptr<juce::DatagramSocket> socket;
juce::String broadcastIp = "255.255.255.255";
juce::String bindIp = "0.0.0.0";
int destPort = 6454;
int selectedInterface = -1;
std::atomic<bool> isRunningFlag { false };
std::atomic<bool> paused { false };
juce::Array<NetworkInterface> availableInterfaces;
juce::SpinLock tcLock;
Timecode timecodeToSend; // Written by UI thread under tcLock, read by timer thread under tcLock
Timecode encoderTc; // Auto-increment: last sent timecode (timer thread only)
bool artnetSeeded = false; // Auto-increment: false until first frame seeds encoderTc
std::atomic<FrameRate> currentFps { FrameRate::FPS_25 };
std::atomic<double> lastFrameSendTime { 0.0 };
std::atomic<uint32_t> sendErrors { 0 };
uint8_t dmxSequence = 0; // incrementing 1-255 for OpDmx sequencing (message-thread-only currently, but atomic-safe for future use)
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ArtnetOutput)
};