Repository navigation
Expand file tree
/
Copy pathtime_receiver.cpp
More file actions
505 lines (466 loc) · 17.7 KB
/
Copy pathtime_receiver.cpp
File metadata and controls
505 lines (466 loc) · 17.7 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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
#include "time_receiver.h"
#include "api_config.h"
#include "inlet_connection.h"
#include "netinterfaces.h"
#include "socket_utils.h"
#include <algorithm>
#include <asio/io_context.hpp>
#include <asio/post.hpp>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <exception>
#include <limits>
#include <loguru.hpp>
#include <memory>
#include <random>
#include <string>
/// internally used constant to represent an unassigned time offset
const double NOT_ASSIGNED = std::numeric_limits<double>::max();
using namespace lsl;
namespace {
inline bool approx_same_t0(double a, double b) {
return std::abs(a - b) <= 1e-12 * std::max(1.0, std::abs(b));
}
inline int initial_wave_id() {
try {
std::random_device rd;
int v = static_cast<int>(rd() & 0x3fffffffU);
return v > 0 ? v : 1;
} catch (...) { return 1; }
}
/// Whether addr is loopback or one of this machine's interface addresses
bool is_local_address(const asio::ip::address &addr) {
if (addr.is_loopback()) return true;
// ponytail: get_local_interfaces() lists only up, multicast-capable interfaces (and on Windows
// one address per family per adapter); a missed local address just disables the fallback
for (const auto &netif : get_local_interfaces())
if (netif.addr.is_v6() && addr.is_v6()
? netif.addr.to_v6().to_bytes() == addr.to_v6().to_bytes() // ignore scope id
: netif.addr == addr)
return true;
return false;
}
/// same-clock fallback for tokenless outlets, only for outlets on this machine
same_clock_fallback make_fallback(const api_config *cfg, const udp::endpoint &outlet) {
const int rounds = cfg->time_same_clock_fallback_rounds();
return same_clock_fallback(cfg->time_same_clock_detection() && rounds > 0 &&
is_local_address(outlet.address())
? rounds
: 0);
}
} // namespace
time_receiver::time_receiver(inlet_connection &conn)
: conn_(conn), was_reset_(false), timeoffset_(std::numeric_limits<double>::max()),
remote_time_(std::numeric_limits<double>::max()),
uncertainty_(std::numeric_limits<double>::max()),
drift_(api_config::get_instance()->time_drift_window()), cfg_(api_config::get_instance()),
time_sock_(time_io_), outlet_addr_(conn_.get_udp_endpoint()), next_estimate_(time_io_),
aggregate_results_(time_io_), next_packet_(time_io_), current_wave_id_(initial_wave_id()) {
conn_.register_onlost(this, &timeoffset_upd_);
conn_.register_onrecover(this, [this]() {
reset_timeoffset_on_recovery();
const auto new_addr = conn_.get_udp_endpoint();
// Perform socket close/reopen and state updates exclusively on time_io_ so the time
// thread never races with recovery on time_sock_, ts_caps_, or tx_ts_counter_.
asio::post(time_io_, [this, new_addr]() {
outlet_addr_ = new_addr;
fallback_ = make_fallback(cfg_, outlet_addr_);
DLOG_F(INFO, "Set new time service address: %s",
outlet_addr_.address().to_string().c_str());
++sock_gen_;
receiving_ = false;
asio::error_code ec;
time_sock_.close(ec);
time_sock_.open(outlet_addr_.protocol(), ec);
if (!ec) {
ts_caps_ = enable_socket_timestamps(time_sock_);
tx_ts_counter_ = 0;
}
start_time_estimation();
});
});
time_sock_.open(outlet_addr_.protocol());
ts_caps_ = enable_socket_timestamps(time_sock_);
fallback_ = make_fallback(cfg_, outlet_addr_);
}
time_receiver::~time_receiver() {
try {
conn_.unregister_onrecover(this);
conn_.unregister_onlost(this);
time_io_.stop();
if (time_thread_.joinable()) time_thread_.join();
} catch (std::exception &e) {
LOG_F(ERROR, "Unexpected error during destruction of a time_receiver: %s", e.what());
} catch (...) { LOG_F(ERROR, "Severe error during time receiver shutdown."); }
}
// === external data acccess ===
void time_receiver::wait_for_initial_estimate(std::unique_lock<std::mutex> &lock, double timeout) {
auto timeoffset_available = [this]() {
return (timeoffset_ != std::numeric_limits<double>::max()) || conn_.lost();
};
if (!timeoffset_available()) {
// start thread if not yet running
if (!time_thread_.joinable()) time_thread_ = std::thread(&time_receiver::time_thread, this);
// wait until the timeoffset becomes available (or we time out)
if (timeout >= FOREVER)
timeoffset_upd_.wait(lock, timeoffset_available);
else if (!timeoffset_upd_.wait_for(
lock, std::chrono::duration<double>(timeout), timeoffset_available))
throw timeout_error("The time_correction() operation timed out.");
}
if (conn_.lost())
throw lost_error("The stream read by this inlet has been lost. To recover, you need to "
"re-resolve the source and re-create the inlet.");
}
double time_receiver::time_correction(double timeout) {
double remote_time, uncertainty;
return time_correction(&remote_time, &uncertainty, timeout);
}
double time_receiver::time_correction(double *remote_time, double *uncertainty, double timeout) {
std::unique_lock<std::mutex> lock(timeoffset_mut_);
wait_for_initial_estimate(lock, timeout);
*uncertainty = uncertainty_;
if (drift_.fitted()) {
const double now = lsl_clock();
const double corr = drift_.predict(now);
*remote_time = now - corr;
return corr;
}
*remote_time = remote_time_;
return timeoffset_;
}
drift_estimator::linear_model time_receiver::time_correction_model(double timeout) {
std::unique_lock<std::mutex> lock(timeoffset_mut_);
wait_for_initial_estimate(lock, timeout);
if (drift_.fitted()) return drift_.model();
return drift_estimator::linear_model{
timeoffset_, 0.0, 0.0, drift_estimator::kMaxExtrap, drift_estimator::kMaxExtrap, false};
}
bool time_receiver::was_reset() {
std::unique_lock<std::mutex> lock(timeoffset_mut_);
bool result = was_reset_;
was_reset_ = false;
return result;
}
// === internal processing ===
void time_receiver::time_thread() {
conn_.acquire_watchdog();
loguru::set_thread_name((std::string("T_") += conn_.type_info().name()).c_str());
DLOG_F(2, "Started time receiver thread");
try {
// start an async time estimation
start_time_estimation();
// start the IO object (will keep running until cancelled)
while (true) {
try {
time_io_.run();
break;
} catch (std::exception &e) {
LOG_F(WARNING, "Hiccup during time_thread io_context processing: %s", e.what());
}
}
} catch (std::exception &e) {
LOG_F(WARNING, "time_thread failed unexpectedly with message: %s", e.what());
}
conn_.release_watchdog();
}
void time_receiver::start_time_estimation() {
// clear the wave buffers
sent_probes_.clear();
wave_probes_.clear();
wave_aggregated_ = false;
fallback_.start_round();
// advance wave id monotonically so late replies from earlier waves are ignored
current_wave_id_ = (current_wave_id_ + 1) & 0x3fffffff;
if (current_wave_id_ == 0) current_wave_id_ = 1;
// start the packet exchange chains
send_next_packet(1);
// the receive chain re-arms itself; only (re)start it if it ended (first wave, socket reopened)
if (!receiving_) receive_next_packet();
// use tighter probe spacing on the initial blocking wave for faster cold-start convergence
const double probe_interval =
has_estimate_ ? cfg_->time_probe_interval() : std::min(cfg_->time_probe_interval(), 0.025);
// schedule the aggregation fallback (early aggregation fires as soon as all replies arrive)
const double aggregation_delay =
cfg_->time_probe_max_rtt() + probe_interval * cfg_->time_probe_count();
aggregate_results_.expires_after(timeout_sec(aggregation_delay));
aggregate_results_.async_wait([this](err_t err) { result_aggregation_scheduled(err); });
// schedule the next estimation step, not before this one is aggregated (re-arming
// aggregate_results_ earlier would cancel it, so no estimate would ever be produced); the
// margin keeps the two timers from expiring together, which would run them in either order
next_estimate_.expires_after(timeout_sec(
std::max(cfg_->time_update_interval(), aggregation_delay + probe_interval)));
next_estimate_.async_wait([this](err_t err) {
if (err != asio::error::operation_aborted) start_time_estimation();
});
}
void time_receiver::send_next_packet(int packet_num) {
try {
// form the request into a stack buffer (locale-independent, zero allocations)
const double t0_wire = lsl_clock();
char req[128];
int n = std::snprintf(req, sizeof(req), "LSL:timedata\r\n%d ", current_wave_id_);
if (n > 0 && static_cast<std::size_t>(n) + 40 < sizeof(req)) {
std::size_t pos = static_cast<std::size_t>(n);
pos += static_cast<std::size_t>(format_c_double(req + pos, sizeof(req) - pos, t0_wire));
if (pos + 2 < sizeof(req)) {
req[pos++] = '\r';
req[pos++] = '\n';
}
tx_timestamps tx{};
asio::error_code ec;
send_with_tx_timestamp(time_sock_, req, pos, outlet_addr_, ts_caps_.tx_kernel,
tx_ts_counter_, tx, ec);
if (!ec) {
sent_probes_.push_back(
{t0_wire, tx.before, tx.midpoint(), tx.ts_id, tx.has_ts_id, !tx.has_ts_id});
if (tx.has_ts_id) drain_inlet_tx_timestamps();
}
}
} catch (std::exception &e) {
LOG_F(WARNING, "Error trying to send a time packet: %s", e.what());
}
// schedule next packet
if (packet_num < cfg_->time_probe_count()) {
const double probe_interval = has_estimate_ ? cfg_->time_probe_interval()
: std::min(cfg_->time_probe_interval(), 0.025);
next_packet_.expires_after(timeout_sec(probe_interval));
next_packet_.async_wait([this, packet_num](err_t err) {
if (!err) send_next_packet(packet_num + 1);
});
}
}
void time_receiver::receive_next_packet() {
const uint64_t gen = sock_gen_;
if (ts_caps_.rx_kernel)
async_receive_with_rx_timestamp(time_sock_, recv_buffer_, sizeof(recv_buffer_),
remote_endpoint_, rx_ts_,
[this, gen](err_t err, std::size_t len) { handle_receive_outcome(gen, err, len); });
else
time_sock_.async_receive_from(asio::buffer(recv_buffer_), remote_endpoint_,
[this, gen](err_t err, std::size_t len) {
if (gen == sock_gen_) {
rx_ts_ = rx_timestamps{};
if (!err) rx_ts_.user = lsl_clock();
}
handle_receive_outcome(gen, err, len);
});
// set only once the receive is armed (asio never runs the handler inside the call)
receiving_ = true;
}
void time_receiver::drain_inlet_tx_timestamps() {
if (!ts_caps_.tx_kernel) return;
drained_tx_.clear();
drain_tx_timestamps(time_sock_, drained_tx_);
for (const auto &entry : drained_tx_) {
for (auto &sp : sent_probes_) {
if (sp.has_tx_ts_id && !sp.tx_resolved && sp.tx_ts_id == entry.first) {
const double lag = entry.second - sp.t0_before;
// Reject out-of-range TX stamps (e.g. if OPT_ID ever drifted after a send error).
if (lag >= 0.0 && lag < 0.01) {
sp.t0_tx = entry.second;
sp.tx_resolved = true;
for (auto &wp : wave_probes_) {
if (wp.has_tx_ext && !wp.same_clock &&
approx_same_t0(wp.t0_wire, sp.t0_wire)) {
const double new_rtt =
(wp.t3_rx - entry.second) - (wp.t2_tx - wp.t1_rx);
if (new_rtt >= 0.0) {
wp.t0_tx = entry.second;
wp.recompute();
}
}
}
}
break;
}
}
}
}
void time_receiver::handle_receive_outcome(uint64_t sock_gen, err_t err, std::size_t len) {
if (sock_gen != sock_gen_) return;
try {
if (!err) {
// Resolve any kernel TX timestamps for sent probes before computing offset/RTT.
drain_inlet_tx_timestamps();
const char *p = recv_buffer_;
const char *const end = recv_buffer_ + len;
int wave_id = 0;
double t0_wire = 0.0, t1_user = 0.0, t2_before = 0.0;
// a truncated or garbled reply is dropped rather than used half-parsed
if (parse_c_int(p, end, wave_id) && wave_id == current_wave_id_ &&
parse_c_double(p, end, t0_wire) && parse_c_double(p, end, t1_user) &&
parse_c_double(p, end, t2_before)) {
// Optional trailing tokens: [<clock_id>] [tx=<t1_rx>,<t2_est>[,<prev_wave>,<prev_t0>,<prev_t2_tx>]]
std::string clock_id;
bool has_tx_ext = false;
double t1_rx = t1_user, t2_est = t2_before;
bool has_prev_tx = false;
int prev_wave = 0;
double prev_t0 = 0.0, prev_t2_tx = 0.0;
auto next_token = [&](const char *&tok_b, const char *&tok_e) -> bool {
while (p < end && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')) ++p;
if (p >= end) return false;
tok_b = p;
while (p < end && !(*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')) ++p;
tok_e = p;
return true;
};
auto parse_tx_ext = [&](const char *tb, const char *te) {
const char *q = tb + 3; // skip "tx="
if (!parse_c_double(q, te, t1_rx) || q >= te || *q != ',') return;
++q;
if (!parse_c_double(q, te, t2_est)) return;
has_tx_ext = true;
if (q < te && *q == ',') {
++q;
if (parse_c_int(q, te, prev_wave) && q < te && *q == ',') {
++q;
if (parse_c_double(q, te, prev_t0) && q < te && *q == ',') {
++q;
if (parse_c_double(q, te, prev_t2_tx)) has_prev_tx = true;
}
}
}
};
const char *tb = nullptr, *te = nullptr;
while (next_token(tb, te)) {
if (static_cast<std::size_t>(te - tb) > 3 && std::memcmp(tb, "tx=", 3) == 0)
parse_tx_ext(tb, te);
else if (clock_id.empty())
clock_id.assign(tb, te);
}
// Match local sent_probe for exact t0_before and post-send t0_tx.
double t0_before = t0_wire;
double t0_tx = t0_wire;
for (const auto &sp : sent_probes_) {
if (approx_same_t0(sp.t0_wire, t0_wire)) {
t0_before = sp.t0_before;
t0_tx = sp.t0_tx;
break;
}
}
const double t3_user = rx_ts_.user;
// Same clock (same OS instance and boot): offset is exactly 0. Check causality on
// user-space stamps so loopback conversion-bracket jitter never causes a false miss.
const bool is_same_clock = cfg_->time_same_clock_detection() &&
!clock_id.empty() && clock_id == lsl_clock_id() &&
t0_before <= t1_user && t2_before <= t3_user;
fallback_.add_probe(!clock_id.empty(), t0_before, t1_user, t2_before, t3_user);
// Upgrade the previous probe in this wave with its exact post-send t2_tx if valid.
if (has_tx_ext && has_prev_tx && prev_wave == current_wave_id_) {
for (auto &wp : wave_probes_) {
if (wp.has_tx_ext && !wp.same_clock &&
approx_same_t0(wp.t0_wire, prev_t0)) {
const double new_rtt =
(wp.t3_rx - wp.t0_tx) - (prev_t2_tx - wp.t1_rx);
if (prev_t2_tx >= wp.t1_rx && new_rtt >= 0.0) {
wp.t2_tx = prev_t2_tx;
wp.recompute();
}
break;
}
}
}
// Build this probe: pair TX+RX symmetrically when talking to a new outlet, or
// symmetric user-space stamps when talking to an older outlet without tx=.
wave_probe wp{};
wp.t0_wire = t0_wire;
wp.has_tx_ext = has_tx_ext;
wp.same_clock = is_same_clock;
if (has_tx_ext) {
wp.t0_tx = t0_tx;
wp.t1_rx = t1_rx;
wp.t2_tx = t2_est;
wp.t3_rx = rx_ts_.best();
} else {
wp.t0_tx = t0_before;
wp.t1_rx = t1_user;
wp.t2_tx = t2_before;
wp.t3_rx = t3_user;
}
wp.recompute();
// Drop any probe with a negative RTT (e.g. from a corrupted/mismatched stamp).
if (wp.rtt >= 0.0) wave_probes_.push_back(wp);
// Early aggregation: once all probes of this wave have returned, don't wait out
// the remaining TimeProbeMaxRTT tail.
if (!wave_aggregated_ &&
static_cast<int>(wave_probes_.size()) >= cfg_->time_probe_count()) {
aggregate_results_.cancel();
aggregate_wave();
}
}
}
} catch (std::exception &e) {
LOG_F(WARNING, "Error while processing a time estimation return packet: %s", e.what());
}
if (err != asio::error::operation_aborted)
receive_next_packet();
else
receiving_ = false;
}
void time_receiver::result_aggregation_scheduled(err_t err) {
if (err) return;
aggregate_wave();
}
void time_receiver::aggregate_wave() {
if (wave_aggregated_) return;
wave_aggregated_ = true;
drain_inlet_tx_timestamps();
const bool same_clock_fb = fallback_.end_round();
if (static_cast<int>(wave_probes_.size()) >= cfg_->time_update_minprobes()) {
// Pick the lowest-RTT probe for uncertainty and single-wave fallback.
double best_offset = 0.0, best_rtt = FOREVER;
double best_remote_time = 0.0;
bool all_same_clock = true;
int valid_probes = 0;
for (const auto &wp : wave_probes_) {
if (wp.rtt < 0.0) continue;
++valid_probes;
if (!wp.same_clock) all_same_clock = false;
if (wp.rtt < best_rtt) {
best_rtt = wp.rtt;
best_offset = wp.offset;
best_remote_time = wp.remote_time;
}
}
if (valid_probes < cfg_->time_update_minprobes()) return;
// tokenless outlet on this machine consistent with offset 0 for several rounds: report 0.
// The uncertainty stays best_rtt, the width of the interval the true offset is known to
// lie in, which is also how far off 0 could be if the clocks were not the same after all
if (same_clock_fb) best_offset = 0.0;
const bool exact_same_clock = same_clock_fb || all_same_clock;
std::vector<drift_estimator::round> wave;
if (!exact_same_clock && cfg_->time_drift_window() > 0) {
wave.reserve(wave_probes_.size());
for (const auto &wp : wave_probes_)
if (wp.rtt >= 0.0) wave.push_back({wp.local_time, 0.0 - wp.offset, wp.rtt});
}
// and notify that the result is available
{
std::lock_guard<std::mutex> lock(timeoffset_mut_);
uncertainty_ = best_rtt;
timeoffset_ = 0.0 - best_offset; // not -best_offset, which turns 0.0 into -0.0
remote_time_ = best_remote_time;
// a same-clock 0 must stay exactly 0, not be blended with earlier measured rounds
if (exact_same_clock)
drift_.clear();
else if (!wave.empty())
drift_.add_wave(wave);
}
has_estimate_ = true;
timeoffset_upd_.notify_all();
}
}
void time_receiver::reset_timeoffset_on_recovery() {
std::lock_guard<std::mutex> lock(timeoffset_mut_);
if (timeoffset_ != NOT_ASSIGNED)
// this will only be set to true if the reset may have caused a possible interruption in the
// obtained time offsets
was_reset_ = true;
timeoffset_ = NOT_ASSIGNED;
has_estimate_ = false;
drift_.clear();
}