Repository navigation
Expand file tree
/
Copy pathudp_server.cpp
More file actions
356 lines (323 loc) · 11.5 KB
/
Copy pathudp_server.cpp
File metadata and controls
356 lines (323 loc) · 11.5 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
#include "udp_server.h"
#include "api_config.h"
#include "socket_utils.h"
#include "stream_info_impl.h"
#include "util/strfuns.hpp"
#include <algorithm>
#include <asio/io_context.hpp>
#include <asio/ip/address.hpp>
#include <asio/ip/address_v4.hpp>
#include <asio/ip/multicast.hpp>
#include <asio/ip/udp.hpp>
#include <cstdio>
#include <cstring>
#include <exception>
#include <loguru.hpp>
#include <sstream>
#include <utility>
namespace ip = asio::ip;
namespace lsl {
udp_server::udp_server(stream_info_impl_p info, asio::io_context &io, udp protocol)
: info_(std::move(info)), io_(io), socket_(std::make_shared<udp_socket_p::element_type>(io)),
time_services_enabled_(true) {
// open the socket for the specified protocol
socket_->open(protocol);
// bind to a free port
uint16_t port = bind_port_in_range(*socket_, protocol);
ts_caps_ = enable_socket_timestamps(*socket_);
// assign the service port field
if (protocol == udp::v4())
info_->v4service_port(port);
else
info_->v6service_port(port);
LOG_F(2, "%s: Started unicast udp server at port %d (addr %p)", info_->name().c_str(), port,
(void *)this);
}
udp_server::udp_server(stream_info_impl_p info, asio::io_context &io, ip::address addr,
uint16_t port, int ttl, const std::string &listen_address)
: info_(std::move(info)), io_(io), socket_(std::make_shared<udp_socket>(io)),
time_services_enabled_(false) {
bool is_broadcast = addr == ip::address_v4::broadcast();
// set up the endpoint where we listen (note: this is not yet the multicast address)
udp::endpoint listen_endpoint;
if (listen_address.empty()) {
// pick the default endpoint
if (addr.is_v4())
listen_endpoint = udp::endpoint(udp::v4(), port);
else
listen_endpoint = udp::endpoint(udp::v6(), port);
} else {
// choose an endpoint explicitly
ip::address listen_addr = ip::make_address(listen_address);
listen_endpoint = udp::endpoint(listen_addr, (uint16_t)port);
}
// open the socket and make sure that we can reuse the address, and bind it
socket_->open(listen_endpoint.protocol());
socket_->set_option(udp::socket::reuse_address(true));
// set the multicast TTL
if (addr.is_multicast() && !is_broadcast) socket_->set_option(ip::multicast::hops(ttl));
// bind to the listen endpoint
socket_->bind(listen_endpoint);
// join the multicast groups
if (addr.is_multicast() && !is_broadcast) {
bool joined_anywhere = false;
asio::error_code err;
for (auto &if_ : api_config::get_instance()->multicast_interfaces) {
DLOG_F(
INFO, "Joining %s to %s", if_.addr.to_string().c_str(), addr.to_string().c_str());
if (addr.is_v4() && if_.addr.is_v4())
socket_->set_option(ip::multicast::join_group(addr.to_v4(), if_.addr.to_v4()), err);
else if (addr.is_v6() && if_.addr.is_v6())
socket_->set_option(
ip::multicast::join_group(addr.to_v6(), if_.addr.to_v6().scope_id()), err);
if (err)
LOG_F(1, "Could not bind multicast responder for %s to interface %s (%s)",
addr.to_string().c_str(), if_.addr.to_string().c_str(), err.message().c_str());
else
joined_anywhere = true;
}
if (!joined_anywhere) throw std::runtime_error("Could not join any multicast group");
}
LOG_F(2, "%s: Started multicast udp server at %s port %d (addr %p)",
this->info_->name().c_str(), addr.to_string().c_str(), port, (void *)this);
}
// === externally issued asynchronous commands ===
void udp_server::begin_serving() {
// pre-calculate the shortinfo message (now that everyone should have initialized their part).
shortinfo_msg_ = info_->to_shortinfo_message();
// start asking for a packet
request_next_packet();
}
void udp_server::end_serving() {
// gracefully close the socket; this will eventually lead to the cancellation of the IO
// operation(s) tied to its socket
auto sock(socket_); // socket shared ptr to be kept alive
const char *fn = __func__;
post(io_, [sock, fn]() {
try {
if (sock->is_open()) sock->close();
} catch (std::exception &e) { LOG_F(ERROR, "Error during %s: %s", fn, e.what()); }
});
}
// === receive / reply loop ===
void udp_server::request_next_packet() {
DLOG_F(5, "udp_server::request_next_packet");
if (time_services_enabled_ && ts_caps_.rx_kernel)
async_receive_with_rx_timestamp(*socket_, buffer_, sizeof(buffer_), remote_endpoint_,
rx_ts_, [shared_this = shared_from_this()](err_t err, std::size_t len) {
shared_this->handle_receive_outcome(err, len);
});
else
socket_->async_receive_from(asio::buffer(buffer_), remote_endpoint_,
[shared_this = shared_from_this()](err_t err, std::size_t len) {
shared_this->rx_ts_ = rx_timestamps{};
if (!err) shared_this->rx_ts_.user = lsl_clock();
shared_this->handle_receive_outcome(err, len);
});
}
void udp_server::process_shortinfo_request(std::istream& request_stream)
{
std::string query;
getline(request_stream, query);
query = trim(query);
// parse return address, port, and query ID
uint16_t return_port;
request_stream >> return_port;
std::string query_id;
request_stream >> query_id;
DLOG_F(2, "%p shortinfo req from %s for %s", (void *)this,
remote_endpoint_.address().to_string().c_str(), query.c_str());
// check query
if (info_->matches_query(query)) {
LOG_F(3, "%p query matches, replying to port %d", (void *)this, return_port);
// query matches: send back reply
udp::endpoint return_endpoint(remote_endpoint_.address(), return_port);
string_p replymsg(
std::make_shared<std::string>((query_id += "\r\n") += shortinfo_msg_));
socket_->async_send_to(asio::buffer(*replymsg), return_endpoint,
[shared_this = shared_from_this(), replymsg](err_t err_, std::size_t /*unused*/) {
if (err_ != asio::error::operation_aborted && err_ != asio::error::shut_down)
shared_this->request_next_packet();
});
} else {
DLOG_F(2, "%p query didn't match", (void *)this);
request_next_packet();
}
}
void udp_server::drain_outlet_tx_timestamps() {
if (!ts_caps_.tx_kernel) return;
drained_tx_.clear();
drain_tx_timestamps(*socket_, drained_tx_);
for (const auto &entry : drained_tx_) {
for (auto &pr : peer_replies_) {
if (pr.has_tx_ts_id && !pr.tx_resolved && pr.tx_ts_id == entry.first) {
const double lag = entry.second - pr.t2_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) {
pr.t2_tx = entry.second;
pr.tx_resolved = true;
tx_lag_history_.push_back(lag);
if (tx_lag_history_.size() > 64) tx_lag_history_.pop_front();
}
break;
}
}
}
}
double udp_server::median_tx_lag() const {
if (tx_lag_history_.empty()) return 0.0;
std::vector<double> tmp(tx_lag_history_.begin(), tx_lag_history_.end());
const auto mid = tmp.begin() + static_cast<std::ptrdiff_t>(tmp.size() / 2);
std::nth_element(tmp.begin(), mid, tmp.end());
if (tmp.size() % 2) return *mid;
return (*mid + *std::max_element(tmp.begin(), mid)) / 2.0;
}
void udp_server::process_timedata_request(
const char *body, const char *end, const rx_timestamps &rx) {
int wave_id = 0;
double t0 = 0.0;
const char *p = body;
if (!parse_c_int(p, end, wave_id) || !parse_c_double(p, end, t0)) return;
// Resolve any pending kernel TX timestamps from earlier replies before piggybacking.
drain_outlet_tx_timestamps();
const peer_reply_state *prev = nullptr;
for (const auto &pr : peer_replies_) {
if (pr.endpoint == remote_endpoint_) {
prev = ≺
break;
}
}
char reply[384];
std::size_t pos = 0;
auto append_char = [&](char c) {
if (pos + 1 < sizeof(reply)) reply[pos++] = c;
};
auto append_str = [&](const char *s, std::size_t n) {
if (pos + n < sizeof(reply)) {
std::memcpy(reply + pos, s, n);
pos += n;
}
};
auto append_int = [&](int v) {
if (pos + 1 < sizeof(reply)) {
int n = std::snprintf(reply + pos, sizeof(reply) - pos, "%d", v);
if (n > 0) pos += std::min(static_cast<std::size_t>(n), sizeof(reply) - pos - 1);
}
};
auto append_dbl = [&](double v) {
if (pos + 1 < sizeof(reply)) {
int n = format_c_double(reply + pos, sizeof(reply) - pos, v);
if (n > 0) pos += static_cast<std::size_t>(n);
}
};
// Standard 4-field prefix (user-space t1 & t2_before for full backwards compatibility).
append_char(' ');
append_int(wave_id);
append_char(' ');
append_dbl(t0);
append_char(' ');
append_dbl(rx.user);
append_char(' ');
const double tx_lag = median_tx_lag();
const double t2_before = lsl_clock();
append_dbl(t2_before);
// Optional clock identity token, ignored by older inlets.
if (api_config::get_instance()->time_same_clock_detection() && !lsl_clock_id().empty()) {
append_char(' ');
const auto &cid = lsl_clock_id();
append_str(cid.data(), cid.size());
}
// Optional trailing tx= extension for newer inlets:
// tx=<t1_rx>,<t2_est>[,<prev_wave>,<prev_t0>,<prev_t2_tx>]
// Older inlets stop parsing after t2 (or clock_id) and ignore this token.
append_str(" tx=", 4);
append_dbl(rx.best());
append_char(',');
append_dbl(t2_before + tx_lag);
if (prev && prev->tx_resolved) {
append_char(',');
append_int(prev->wave_id);
append_char(',');
append_dbl(prev->t0);
append_char(',');
append_dbl(prev->t2_tx);
}
tx_timestamps tx{};
asio::error_code send_ec;
send_with_tx_timestamp(*socket_, reply, pos, remote_endpoint_, ts_caps_.tx_kernel,
tx_ts_counter_, tx, send_ec);
if (send_ec) return;
peer_reply_state state{};
state.endpoint = remote_endpoint_;
state.wave_id = wave_id;
state.t0 = t0;
state.t2_before = t2_before;
state.t2_tx = tx.midpoint();
state.tx_ts_id = tx.ts_id;
state.has_tx_ts_id = tx.has_ts_id;
state.tx_resolved = !tx.has_ts_id;
bool updated = false;
for (auto &pr : peer_replies_) {
if (pr.endpoint == remote_endpoint_) {
pr = state;
updated = true;
break;
}
}
if (!updated) {
if (peer_replies_.size() >= 64) peer_replies_.pop_front();
peer_replies_.push_back(state);
}
if (!tx.has_ts_id) {
const double lag = state.t2_tx - t2_before;
if (lag >= 0.0 && lag < 0.01) {
tx_lag_history_.push_back(lag);
if (tx_lag_history_.size() > 64) tx_lag_history_.pop_front();
}
} else {
drain_outlet_tx_timestamps();
}
}
void udp_server::handle_receive_outcome(err_t err, std::size_t len) {
DLOG_F(6, "udp_server::handle_receive_outcome (%lub)", len);
if (err) {
// non-critical error? Wait for the next packet if the socket is still open
if (err != asio::error::operation_aborted && err != asio::error::shut_down
&& socket_ && socket_->is_open())
request_next_packet();
return;
}
try {
const char *const end = buffer_ + len;
// Fast path for LSL:timedata: avoid std::string / std::istringstream allocations.
if (time_services_enabled_) {
const char *nl = static_cast<const char *>(std::memchr(buffer_, '\n', len));
const char *line_end = nl ? nl : end;
const char *m_begin = buffer_;
const char *m_end = line_end;
trim(m_begin, m_end);
if (static_cast<std::size_t>(m_end - m_begin) == 12 &&
std::memcmp(m_begin, "LSL:timedata", 12) == 0) {
if (nl) process_timedata_request(nl + 1, end, rx_ts_);
request_next_packet();
return;
}
}
// wrap received packet into a request stream and parse the method from it
std::istringstream request_stream(std::string(buffer_, len));
std::string method;
getline(request_stream, method);
method = trim(method);
if (method == "LSL:shortinfo") {
// shortinfo request: parse content query string
process_shortinfo_request(request_stream);
return;
}
DLOG_F(INFO, "%p Unknown method '%s' received by udp-server", (void *)this, method.c_str());
} catch (std::exception &e) {
LOG_F(
WARNING, "%p udp_server: hiccup during request processing: %s", (void *)this, e.what());
}
request_next_packet();
}
} // namespace lsl