Repository navigation
Expand file tree
/
Copy pathLANetTimecodeOutput.h
More file actions
360 lines (307 loc) · 13.3 KB
/
Copy pathLANetTimecodeOutput.h
File metadata and controls
360 lines (307 loc) · 13.3 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
// Super Timecode Converter
// Copyright (c) 2026 Fiverecords -- MIT License
// https://github.com/fiverecords/SuperTimecodeConverter
// LANetTimecodeOutput
// Copyright (c) 2026 LaserAnimation Sollinger GmbH, https://www.laseranimation.com
// Written by Ingo Randolf (based on ArtnetOutput)
#pragma once
#include <JuceHeader.h>
#include "TimecodeCore.h"
#include "NetworkUtils.h"
#include <atomic>
#include <cstdlib>
#ifdef _WIN32
#include <winsock2.h>
#else
#include <sys/socket.h>
#endif
static const uint8_t laNetPacketHeader[24] = {0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0};
class LANetTimecodeOutput : public juce::HighResolutionTimer
{
public:
LANetTimecodeOutput()
{
refreshNetworkInterfaces();
}
~LANetTimecodeOutput() override
{
stop();
}
//==============================================================================
void refreshNetworkInterfaces()
{
availableInterfaces = ::getNetworkInterfaces(); // no Localhost entry: start(-1) sends to 127.0.0.1
}
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 = 8201)
{
stop();
destPort = targetPort;
if (interfaceIndex >= 0 && interfaceIndex < availableInterfaces.size())
{
selectedInterface = interfaceIndex;
broadcastIp = availableInterfaces[interfaceIndex].broadcast;
bindIp = availableInterfaces[interfaceIndex].ip;
}
else if (interfaceIndex == -1)
{
selectedInterface = -1;
broadcastIp = "127.0.0.1";
bindIp = "127.0.0.1";
}
else
{
selectedInterface = -2;
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);
seeded = false;
resyncRequested.store(false, std::memory_order_relaxed);
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. Message thread.
void setPaused(bool shouldPause)
{
if (paused.load(std::memory_order_relaxed) == shouldPause)
return;
paused.store(shouldPause, std::memory_order_relaxed);
if (shouldPause)
{
stopTimer();
// The timer is stopped (stopTimer() returns after an in-flight
// callback), so the encoder state is ours here. A forceResync()
// the timer had not served yet still goes out: the engine's
// clean stop calls forceResync() and then this, and that frame
// is the stopped position.
if (resyncRequested.exchange(false, std::memory_order_acquire)
&& isRunningFlag.load(std::memory_order_relaxed) && socket != nullptr)
{
seeded = false;
sendLANetTimecode(currentFps.load(std::memory_order_relaxed));
}
}
else if (isRunningFlag.load(std::memory_order_relaxed))
{
// Stopped since the pause: the encoder state is ours here too.
seeded = false;
resyncRequested.store(false, std::memory_order_relaxed);
lastFrameSendTime.store(juce::Time::getMillisecondCounterHiRes(), std::memory_order_relaxed);
updateTimerRate();
}
}
bool isPaused() const { return paused.load(std::memory_order_relaxed); }
/// Force immediate LA-Net frame send, re-seeded from the last
/// setTimecode() value.
/// Call on seek/hot cue/track change so receivers update instantly
/// instead of waiting for the next frame (up to 1 frame latency).
/// Message thread, with the timer running: the timer thread sends the
/// frame at its next callback (1 ms), or setPaused(true) does if it
/// comes first. Sending from here wrote the encoder state the timer
/// thread was using -- a data race (AUDIT C5, LTC-7).
void forceResync()
{
if (!isRunningFlag.load(std::memory_order_relaxed)
|| paused.load(std::memory_order_relaxed)
|| socket == nullptr)
return;
resyncRequested.store(true, std::memory_order_release);
}
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);
// forceResync(): the frame at the new position goes out now,
// re-seeded, outside the frame cadence, which carries on unchanged.
if (resyncRequested.exchange(false, std::memory_order_acquire))
{
seeded = false;
sendLANetTimecode(fps);
}
// Fractional accumulator: compare real elapsed time against ideal frame interval
// to eliminate drift caused by integer-ms timer resolution
double now = juce::Time::getMillisecondCounterHiRes();
// LaserAnimation Net 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)
{
sendLANetTimecode(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 sendLANetTimecode(FrameRate fps)
{
Timecode pending;
{
const juce::SpinLock::ScopedLockType lock(tcLock);
pending = timecodeToSend;
}
// Auto-increment: advance by 1 frame per send, then the shared
// tracking policy (TimecodeCore::trackPublishedValue, DESIGN D16): a
// repeated or skipped frame when the source has drifted by one, a
// snap only beyond kTrackingHardResync (a seek). Absorbs the 1-frame
// backward jitter of the engine's interpolation. Same policy as the
// LTC, MTC and Art-Net senders.
Timecode tc;
if (!seeded)
{
tc = pending;
seeded = true;
}
else
{
// Shared tracking policy (TimecodeCore::trackPublishedValue).
tc = trackPublishedValue(incrementFrame(encoderTc, fps), pending, 1, fps);
}
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[28];
std::memcpy(packet, laNetPacketHeader, sizeof(laNetPacketHeader));
// timecode format: the nominal rate. What is known of the protocol
// (proprietary) has integer rates only -- the input takes 24, 25 and
// 30 and ignores 50, 60 and 100 -- so 23.976 goes out as 24 and
// 29.97 drop-frame as 30, and the count below is the drop-frame
// LABEL read as if every number existed: at each dropped pair (every
// minute but the tenth) it jumps by 3 where one frame went by --
// 00:00:59;29 = 1799, 00:01:00;02 = 1802 -- and runs 2 more frames
// ahead each time. A receiver taking the 23.976 count as 24 per
// second reads 0.1 % slow against the wall clock. Left as is until
// a receiver or a capture says what it expects (DESIGN D2; AUDIT
// NET-6, deferred).
packet[19] = uint8_t(maxFrames);
// frames since midnight at maxFrames per second, big-endian
uint32_t be = juce::ByteOrder::swapIfLittleEndian((int32_t(tc.hours) * 3600 * maxFrames)
+ (int32_t(tc.minutes) * 60 * maxFrames)
+ (int32_t(tc.seconds) * maxFrames)
+ int32_t(tc.frames));
std::memcpy(&packet[24], &be, sizeof(uint32_t));
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 = 8201;
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
// The encoder state -- encoderTc, seeded -- belongs to the timer thread
// while the timer runs. The message thread writes it only with the
// timer stopped (start(), setPaused(): stopTimer() returns after an
// in-flight callback), and forceResync() asks the timer thread through
// resyncRequested instead of writing it (AUDIT C5, LTC-7).
Timecode encoderTc; // Auto-increment: last sent timecode
bool seeded = false; // Auto-increment: false until first frame seeds encoderTc
std::atomic<bool> resyncRequested { false }; // set by forceResync(), consumed by the timer or setPaused(true)
std::atomic<FrameRate> currentFps { FrameRate::FPS_25 };
std::atomic<double> lastFrameSendTime { 0.0 };
std::atomic<uint32_t> sendErrors { 0 };
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(LANetTimecodeOutput)
};