-
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathLANetTimecodeInput.h
More file actions
304 lines (239 loc) · 9.22 KB
/
Copy pathLANetTimecodeInput.h
File metadata and controls
304 lines (239 loc) · 9.22 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
// Super Timecode Converter
// Copyright (c) 2026 Fiverecords -- MIT License
// https://github.com/fiverecords/SuperTimecodeConverter
// LANetTimecodeInput
// Copyright (c) 2026 LaserAnimation Sollinger GmbH, https://www.laseranimation.com
// Written by Ingo Randolf (based on ArtnetInput)
#pragma once
#include <JuceHeader.h>
#include "TimecodeCore.h"
#include "NetworkUtils.h"
#include <atomic>
class LANetTimecodeInput : public juce::Thread
{
public:
LANetTimecodeInput()
: Thread("LA-Net Input")
{
}
~LANetTimecodeInput() override
{
stop();
}
//==============================================================================
void refreshNetworkInterfaces()
{
availableInterfaces = ::getNetworkInterfaces(true); // software protocol: localhost too (#20)
}
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 = 8201)
{
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);
// Enable SO_REUSEADDR before binding
auto rawSock = socket->getRawSocketHandle();
if (rawSock >= 0)
{
const int flag = 1;
#ifdef _WIN32
setsockopt(rawSock, SOL_SOCKET, SO_REUSEADDR,
(const char*)&flag, sizeof(flag));
#else
setsockopt(rawSock, SOL_SOCKET, SO_REUSEADDR,
&flag, sizeof(flag));
#endif
}
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
/// Arrival instant of the last valid timecode packet (hi-res ms), which
/// the sender emits at its frame boundary -- so it is the start of the
/// frame carried in the packet. 0.0 when nothing has arrived.
double getLastFrameArrivalMs() const
{
return lastPacketTime.load(std::memory_order_relaxed);
}
/// Freewheel (D10): how long after the last frame/packet the source still
/// counts as present. The senders count on their own through it, so a
/// short dropout -- a USB stall, a display wake -- never reaches the
/// wire; the price is that a real stop takes this long to reach the
/// outputs. The operator sets it (engine setting), default
/// kSourceTimeoutMs.
void setTimeoutMs(double ms) { timeoutMs.store(juce::jmax(50.0, ms), std::memory_order_relaxed); }
double getTimeoutMs() const { return timeoutMs.load(std::memory_order_relaxed); }
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 < timeoutMs.load(std::memory_order_relaxed);
}
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 == 28)
parseLANetTimecodePacket(buffer, bytesRead);
}
}
void parseLANetTimecodePacket(const uint8_t* data, int size)
{
if (size != 28)
{
// invalid data
return;
}
const uint32_t* networkData = reinterpret_cast<const uint32_t*>(data);
// message type
uint32_t message_type = juce::ByteOrder::swapIfLittleEndian(networkData[0]);
if (message_type != 1)
{
return;
}
// version parsing
uint32_t version = juce::ByteOrder::swapIfLittleEndian(networkData[1]);
if (version != 1)
{
return;
}
uint32_t len = juce::ByteOrder::swapIfLittleEndian(networkData[3]);
if (len != 12)
{
return;
}
uint32_t fps = juce::ByteOrder::swapIfLittleEndian(networkData[4]);
if (fps == 0)
{
fps = 25;
}
uint32_t timestamp = juce::ByteOrder::swapIfLittleEndian(networkData[6]);
if (timestamp == 0xffffffff)
{
return;
}
// check valid fps
// ignore not supported fps: 50, 60, 100
if (fps != 24 && fps != 25 && fps != 30)
{
// unsupported fps could be converted
return;
}
int frames = timestamp % fps;
timestamp -= frames;
int seconds = (timestamp / fps) % 60;
timestamp -= seconds * fps;
int minutes = (timestamp / (60 * fps)) % 60;
timestamp -= minutes * fps * 60;
int hours = (timestamp / (60 * 60 * fps));
// 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 (fps)
{
case 24: detectedFps.store(FrameRate::FPS_24, std::memory_order_relaxed); break;
case 25: detectedFps.store(FrameRate::FPS_25, std::memory_order_relaxed); break;
case 30: detectedFps.store(FrameRate::FPS_30, std::memory_order_relaxed); break;
default: break;
}
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 = 8201;
int selectedInterface = 0;
std::atomic<bool> isRunningFlag { false };
std::atomic<double> timeoutMs { kSourceTimeoutMs }; // freewheel window (D10)
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(LANetTimecodeInput)
};