-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathArtnetInput.h
More file actions
233 lines (191 loc) · 7.83 KB
/
ArtnetInput.h
File metadata and controls
233 lines (191 loc) · 7.83 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
// 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>
class ArtnetInput : public juce::Thread
{
public:
ArtnetInput()
: Thread("ArtNet Input")
{
}
~ArtnetInput() override
{
stop();
}
//==============================================================================
void refreshNetworkInterfaces()
{
availableInterfaces = ::getNetworkInterfaces();
}
juce::StringArray getInterfaceNames() const
{
juce::StringArray names;
names.add("ALL INTERFACES (0.0.0.0)");
for (auto& ni : availableInterfaces)
names.add(ni.name + " (" + ni.ip + ")");
return names;
}
int getInterfaceCount() const { return availableInterfaces.size() + 1; }
juce::String getBindInfo() const { return bindIp + ":" + juce::String(listenPort); }
bool didFallBackToAllInterfaces() const { return bindFellBack.load(std::memory_order_relaxed); }
int getSelectedInterface() const { return selectedInterface; }
//==============================================================================
bool start(int interfaceIndex = 0, int port = 6454)
{
stop();
listenPort = port;
if (interfaceIndex > 0 && (interfaceIndex - 1) < availableInterfaces.size())
{
selectedInterface = interfaceIndex;
bindIp = availableInterfaces[interfaceIndex - 1].ip;
}
else
{
selectedInterface = 0;
bindIp = "0.0.0.0";
}
socket = std::make_unique<juce::DatagramSocket>(false);
bool bound = false;
bool fellBack = false;
if (bindIp != "0.0.0.0")
bound = socket->bindToPort(listenPort, bindIp);
if (!bound)
{
bound = socket->bindToPort(listenPort);
if (bound)
{
fellBack = (bindIp != "0.0.0.0"); // only a fallback if we tried a specific IP
bindIp = "0.0.0.0"; // reflect actual bind address
}
}
bindFellBack.store(fellBack, std::memory_order_relaxed);
if (bound)
{
isRunningFlag.store(true, std::memory_order_relaxed);
startThread();
return true;
}
socket = nullptr;
return false;
}
void stop()
{
isRunningFlag.store(false, std::memory_order_relaxed);
bindFellBack.store(false, std::memory_order_relaxed);
if (socket != nullptr)
socket->shutdown();
if (isThreadRunning())
stopThread(1000);
socket = nullptr;
}
bool getIsRunning() const { return isRunningFlag.load(std::memory_order_relaxed); }
int getListenPort() const { return listenPort; }
//==============================================================================
// True if Art-Net TC packets are actively arriving
bool isReceiving() const
{
double lpt = lastPacketTime.load(std::memory_order_relaxed);
if (lpt == 0.0)
return false;
double now = juce::Time::getMillisecondCounterHiRes();
double elapsed = now - lpt;
// At 24fps a packet arrives every ~41ms, at 30fps ~33ms
return elapsed < kSourceTimeoutMs;
}
Timecode getCurrentTimecode() const
{
return unpackTimecode(packedTimecode.load(std::memory_order_relaxed));
}
FrameRate getDetectedFrameRate() const { return detectedFps.load(std::memory_order_relaxed); }
private:
void run() override
{
uint8_t buffer[1024];
while (!threadShouldExit() && isRunningFlag.load(std::memory_order_relaxed))
{
// Capture local pointer: stop() may nullify `socket` from another thread
// after calling socket->shutdown(). The shutdown unblocks waitUntilReady,
// and then the while-condition will fail on the next iteration. The local
// pointer ensures we don't dereference a null between the check and use.
auto* sock = socket.get();
if (sock == nullptr)
break;
// Wait up to 100ms for data -- allows periodic threadShouldExit() checks
// so the thread can shut down cleanly even if no packets are arriving
if (!sock->waitUntilReady(true, 100))
continue;
int bytesRead = sock->read(buffer, sizeof(buffer), false);
if (bytesRead >= 19)
parseArtNetPacket(buffer, bytesRead);
}
}
void parseArtNetPacket(const uint8_t* data, int size)
{
if (size < 19)
return;
if (data[0] != 'A' || data[1] != 'r' || data[2] != 't' ||
data[3] != '-' || data[4] != 'N' || data[5] != 'e' ||
data[6] != 't' || data[7] != 0)
return;
uint16_t opcode = (uint16_t)((uint16_t)data[8] | ((uint16_t)data[9] << 8));
if (opcode != 0x9700)
return;
// ProtVer is big-endian (Hi byte at offset 10, Lo at 11)
// Art-Net 4 requires ProtVer >= 14; accept anything >= 14 for compatibility
uint16_t protVer = (uint16_t)(((uint16_t)data[10] << 8) | (uint16_t)data[11]);
if (protVer < 14)
return;
int frames = data[14];
int seconds = data[15];
int minutes = data[16];
int hours = data[17];
int rateCode = data[18] & 0x03;
// Art-Net 4 spec: bits 2-7 of the Type field are reserved and must be 0.
// Log a warning if they are non-zero (malformed sender), but still
// process the packet -- the frame-rate bits 0-1 remain valid.
if ((data[18] & 0xFC) != 0)
{
DBG("ArtTimeCode: reserved bits in Type field are non-zero (0x"
+ juce::String::toHexString(data[18]) + "). Packet may be malformed.");
}
// Validate ranges -- discard malformed packets
// (lastPacketTime is updated AFTER validation so isReceiving()
// only returns true when we actually accepted valid data)
if (hours > 23 || minutes > 59 || seconds > 59 || frames > 29)
return;
lastPacketTime.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
switch (rateCode)
{
case 0:
// Art-Net rate code 0 means "24fps". Like MTC, Art-Net has
// no dedicated code for 23.976, so if the user has already
// selected FPS_2398 we preserve it rather than silently
// overwriting with FPS_24.
if (detectedFps.load(std::memory_order_relaxed) != FrameRate::FPS_2398)
detectedFps.store(FrameRate::FPS_24, std::memory_order_relaxed);
break;
case 1: detectedFps.store(FrameRate::FPS_25, std::memory_order_relaxed); break;
case 2: detectedFps.store(FrameRate::FPS_2997, std::memory_order_relaxed); break;
case 3: detectedFps.store(FrameRate::FPS_30, std::memory_order_relaxed); break;
default: break; // mask guarantees 0-3, but be explicit
}
packedTimecode.store(packTimecode(hours, minutes, seconds, frames),
std::memory_order_relaxed);
}
std::unique_ptr<juce::DatagramSocket> socket;
juce::String bindIp = "0.0.0.0";
int listenPort = 6454;
int selectedInterface = 0;
std::atomic<bool> isRunningFlag { false };
std::atomic<bool> bindFellBack { false };
juce::Array<NetworkInterface> availableInterfaces;
std::atomic<double> lastPacketTime { 0.0 };
std::atomic<uint64_t> packedTimecode { 0 };
std::atomic<FrameRate> detectedFps { FrameRate::FPS_25 };
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ArtnetInput)
};