Debian Codegraph @

src/rist-common.c

raw symbols SCIP
1 /* librist. Copyright © 2019-2020 SipRadius LLC. All right reserved.
2 * Author: Daniele Lacamera <[email protected]>
3 * Author: Antonio Cardace <[email protected]>
4 * Author: Kuldeep Singh Dhaka <[email protected]>
5 * Author: Sergio Ammirata, Ph.D. <[email protected]>
6 *
7 * SPDX-License-Identifier: BSD-2-Clause
8 */
9
10 #include "proto/gre.h"
11 #include "rist-private.h"
12 #include <limits.h>
13 #include "log-private.h"
14 #include "crypto/psk.h"
15 #include <lz4.h>
16 #include "crypto/random.h"
17 #include "udp-private.h"
18 #include "transport-private.h"
19 #include "udpsocket.h"
20 #include "endian-shim.h"
21 #include "time-shim.h"
22 #include "proto/rist_time.h"
23 #include "network.h"
24 #include "librist/tun.h"
25 #include "librist/tunnel.h"
26 #include <sys/types.h>
27 #include "proto/protocol_gre.h"
28 #if HAVE_SRP_SUPPORT
29 #include "proto/eap.h"
30 #endif
31 #include "mpegts.h"
32 #include "rist_ref.h"
33 #include "config.h"
34 #include "rist-thread.h"
35 #include "rist-nack-select.h"
36 #include "peer.h"
37 #include <stdbool.h>
38 #include "stdio-shim.h"
39 #include <assert.h>
40 #include "proto/gre.h"
41
42 static void rist_peer_recv(struct evsocket_ctx *evctx, int fd, short revents, void *arg, bool *again);
43 static void rist_peer_recv_wrap(struct evsocket_ctx *evctx, int fd, short revents, void *arg);
44 static void rist_peer_sockerr(struct evsocket_ctx *evctx, int fd, short revents, void *arg);
45 static PTHREAD_START_FUNC(receiver_pthread_dataout,arg);
46 static void store_peer_settings(const struct rist_peer_config *settings, struct rist_peer *peer);
47 static struct rist_peer *peer_initialize(const char *url, struct rist_sender *sender_ctx,
48 struct rist_receiver *receiver_ctx);
49 void remove_peer_from_flow(struct rist_peer *peer);
50
51 int parse_url_udp_options(const char* url, struct rist_udp_config *output_udp_config)
52 {
53 uint32_t clean_url_len = 0;
54 const char* query = NULL;
55 uint32_t prefix_len = 0;
56 struct udpsocket_url_param url_params[32];
57 int num_params = 0;
58 int i = 0;
59 int ret = 0;
60
61 if (!url || !url[0] || !output_udp_config)
62 return -1;
63
64 char *tmp_url = strdup( url );
65 if (!tmp_url)
66 return -1;
67
68 query = strchr( tmp_url, '/' );
69 if (query != NULL) {
70 prefix_len = (uint32_t)(query - tmp_url);
71 /* clamp copy length and terminator to prefix[]; prefix_len may be 0 */
72 size_t prefix_copy = prefix_len > 0 ? (size_t)(prefix_len - 1) : 0;
73 if (prefix_copy > sizeof(output_udp_config->prefix) - 1)
74 prefix_copy = sizeof(output_udp_config->prefix) - 1;
75 memcpy((void *)output_udp_config->prefix, tmp_url, prefix_copy);
76 output_udp_config->prefix[prefix_copy] = '\0';
77 // Convert to lower
78 char *p =(char *)output_udp_config->prefix;
79 for(i = 0; i < 16; i++)
80 p[i] = p[i] > 0x40 && p[i] < 0x5b ? p[i] | 0x60 : p[i];
81 if (!strncmp(output_udp_config->prefix, "rtp", 3))
82 output_udp_config->rtp = true;
83 else
84 output_udp_config->rtp = false;
85 } else {
86 // default is udp
87 char src[] = "udp";
88 strcpy((void *)output_udp_config->prefix, src);
89 output_udp_config->rtp = false;
90 }
91
92 // Parse URL parameters
93 num_params = udpsocket_parse_url_parameters( tmp_url, url_params,
94 sizeof(url_params) / sizeof(struct udpsocket_url_param), &clean_url_len );
95 if (num_params > 0) {
96 for (i = 0; i < num_params; ++i) {
97 char* val = url_params[i].val;
98 if (!val)
99 continue;
100
101 if (strcmp( url_params[i].key, RIST_URL_PARAM_MIFACE ) == 0) {
102 strncpy((void *)output_udp_config->miface, val, RIST_MAX_STRING_SHORT - 1);
103 } else if (strcmp(url_params[i].key, RIST_URL_PARAM_MCAST_TTL) == 0) {
104 int temp = atoi(val);
105 if (temp > 0 && temp <= 255)
106 output_udp_config->multicast_ttl = (uint32_t)temp;
107 } else if (output_udp_config->version >= 2 &&
108 strcmp(url_params[i].key, RIST_URL_PARAM_CBR_OUTPUT) == 0) {
109 if (strcmp(val, "0") && strcmp(val, "1")) {
110 ret = -1;
111 } else {
112 output_udp_config->cbr_output = atoi(val);
113 output_udp_config->cbr_output_set = 1;
114 }
115 } else if (strcmp(url_params[i].key, RIST_URL_PARAM_MCAST_SOURCE) == 0) {
116 strncpy((void *)output_udp_config->multicast_source, val, RIST_MAX_STRING_LONG - 1);
117 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_STREAM_ID ) == 0) {
118 int temp = atoi( val );
119 if (temp > 0)
120 output_udp_config->stream_id = (uint16_t)temp;
121 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTP_TIMESTAMP ) == 0) {
122 int temp = atoi( val );
123 if (temp >= 0)
124 output_udp_config->rtp_timestamp = (uint16_t)temp;
125 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTP_SEQUENCE ) == 0) {
126 int temp = atoi( val );
127 if (temp >= 0)
128 output_udp_config->rtp_sequence = (uint16_t)temp;
129 } else if (output_udp_config->version >= 1 && strcmp( url_params[i].key, RIST_URL_PARAM_RTP_OUTPUT_PTYPE) == 0) {
130 int temp = atoi( val );
131 if (temp >= 0)
132 output_udp_config->rtp_ptype = (uint8_t)temp;
133 } else if (output_udp_config->version >= 1 && strcmp( url_params[i].key, RIST_URL_PARAM_MULTIPLEX_MODE) == 0) {
134 int temp = atoi( val );
135 if (temp >= 0)
136 output_udp_config->multiplex_mode = (uint8_t)temp;
137 /*UNUSED TODO} else if (output_udp_config->version >= 1 && strcmp( url_params[i].key, RIST_URL_PARAM_MULTIPLEX_FILTER) == 0) {
138 strncpy((void *)output_udp_config->multiplex_filter, val, RIST_MAX_STRING_SHORT -1); */
139 } else {
140 ret = -1;
141 fprintf(stderr, "Unknown or invalid parameter %s\n", url_params[i].key);
142 }
143 }
144 }
145 strncpy((void *)output_udp_config->address, url, clean_url_len >= RIST_MAX_STRING_LONG ? RIST_MAX_STRING_LONG-1 : clean_url_len - 1);
146
147 free( tmp_url );
148
149 if (ret != 0)
150 return num_params;
151 else
152 return 0;
153 }
154
155 int parse_url_options(const char* url, struct rist_peer_config *output_peer_config)
156 {
157 uint32_t clean_url_len = 0;
158 struct udpsocket_url_param url_params[32];
159 int num_params = 0;
160 int i = 0;
161 int ret = 0;
162
163 if (!url || !url[0] || !output_peer_config)
164 return -1;
165
166 // Parse URL parameters
167 char *tmp_url = strdup( url );
168 if (!tmp_url)
169 return -1;
170
171 num_params = udpsocket_parse_url_parameters( tmp_url, url_params,
172 sizeof(url_params) / sizeof(struct udpsocket_url_param), &clean_url_len );
173 if (num_params > 0) {
174 for (i = 0; i < num_params; ++i) {
175 char* val = url_params[i].val;
176 if (!val)
177 continue;
178
179 if (strcmp( url_params[i].key, RIST_URL_PARAM_BUFFER_SIZE ) == 0) {
180 int temp = atoi( val );
181 /* 0 is meaningless as a recovery buffer and divides by zero
182 * in init_peer_settings (SIGFPE at peer creation). */
183 if (temp > 0) {
184 output_peer_config->recovery_length_min = temp;
185 output_peer_config->recovery_length_max = temp;
186 }
187 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_BUFFER_SIZE_MIN ) == 0) {
188 int temp = atoi( val );
189 if (temp >= 0)
190 output_peer_config->recovery_length_min = temp;
191 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_BUFFER_SIZE_MAX ) == 0) {
192 int temp = atoi( val );
193 if (temp > 0)
194 output_peer_config->recovery_length_max = temp;
195 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_MIFACE ) == 0) {
196 strncpy((void *)output_peer_config->miface, val, 128-1);
197 } else if (output_peer_config->version >= 2 && strcmp(url_params[i].key, RIST_URL_PARAM_MCAST_TTL) == 0) {
198 int temp = atoi(val);
199 if (temp > 0 && temp <= 255)
200 output_peer_config->multicast_ttl = (uint32_t)temp;
201 } else if (output_peer_config->version >= 2 && strcmp(url_params[i].key, RIST_URL_PARAM_MCAST_SOURCE) == 0) {
202 strncpy((void *)output_peer_config->multicast_source, val, RIST_MAX_STRING_LONG - 1);
203 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_SECRET ) == 0) {
204 strncpy((void *)output_peer_config->secret, val, 128-1);
205 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_SRP_USERNAME) == 0) {
206 strncpy((void *)output_peer_config->srp_username, val, 256 -1);
207 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_SRP_PASSWORD) == 0) {
208 strncpy((void *)output_peer_config->srp_password, val, 256 -1);
209 } else if (output_peer_config->version >= 3 && strcmp( url_params[i].key, RIST_URL_PARAM_SRP_COMPAT) == 0) {
210 char *endp = NULL;
211 long temp = strtol(val, &endp, 10);
212 if (endp == val || *endp != '\0' || (temp != 0 && temp != 1)) {
213 ret = -1;
214 fprintf(stderr, "Invalid srp-compat '%s'; expected 0|1\n", val);
215 continue;
216 }
217 output_peer_config->srp_compat_legacy = (int)temp;
218 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_CNAME ) == 0) {
219 strncpy((void *)output_peer_config->cname, val, 128-1);
220 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_AES_TYPE ) == 0) {
221 int temp = atoi( val );
222 if (temp == 0 || temp == 128 || temp == 192 || temp == 256) {
223 output_peer_config->key_size = temp;
224 }
225 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_AES_KEY_ROTATION ) == 0) {
226 int temp = atoi( val );
227 if (temp > 0)
228 output_peer_config->key_rotation = temp;
229 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_BANDWIDTH ) == 0) {
230 int temp = atoi( val );
231 if (temp > 0)
232 output_peer_config->recovery_maxbitrate = temp;
233 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RET_BANDWIDTH ) == 0) {
234 int temp = atoi( val );
235 if (temp >= 0)
236 output_peer_config->recovery_maxbitrate_return = temp;
237 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTT ) == 0) {
238 int temp = atoi( val );
239 if (temp >= 0) {
240 output_peer_config->recovery_rtt_min = temp;
241 output_peer_config->recovery_rtt_max = temp;
242 }
243 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTT_MIN ) == 0) {
244 int temp = atoi( val );
245 if (temp >= 0)
246 output_peer_config->recovery_rtt_min = temp;
247 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTT_MAX ) == 0) {
248 int temp = atoi( val );
249 if (temp >= 0)
250 output_peer_config->recovery_rtt_max = temp;
251 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_REORDER_BUFFER ) == 0) {
252 int temp = atoi( val );
253 if (temp >= 0)
254 output_peer_config->recovery_reorder_buffer = temp;
255 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_COMPRESSION ) == 0) {
256 int temp = atoi( val );
257 if (temp >= 0)
258 output_peer_config->compression = temp;
259 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_VIRT_DST_PORT ) == 0) {
260 int temp = atoi( val );
261 if (temp > 0)
262 output_peer_config->virt_dst_port = (uint16_t)temp;
263 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_WEIGHT ) == 0) {
264 int temp = atoi( val );
265 if (temp >= 0)
266 output_peer_config->weight = temp;
267 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RECOVERY_PRIORITY ) == 0) {
268 int temp = atoi( val );
269 if (temp >= 0)
270 output_peer_config->recovery_priority = (uint32_t)temp;
271 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTT_DROP ) == 0) {
272 int temp = atoi( val );
273 if (temp >= 0)
274 output_peer_config->rtt_drop = (uint32_t)temp;
275 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTT_RESTORE ) == 0) {
276 int temp = atoi( val );
277 if (temp >= 0)
278 output_peer_config->rtt_restore = (uint32_t)temp;
279 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTT_DROP_SETTLE ) == 0) {
280 int temp = atoi( val );
281 if (temp >= 0)
282 output_peer_config->rtt_drop_settle = (uint32_t)temp;
283 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_RTT_DROP_TRICKLE ) == 0) {
284 int temp = atoi( val );
285 if (temp >= 0)
286 output_peer_config->rtt_drop_trickle = (uint32_t)temp;
287 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_SESSION_TIMEOUT ) == 0) {
288 int temp = atoi( val );
289 if (temp > 0)
290 output_peer_config->session_timeout = temp;
291 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_KEEPALIVE_INT ) == 0) {
292 int temp = atoi( val );
293 if (temp > 0)
294 output_peer_config->keepalive_interval = temp;
295 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_CONGESTION_CONTROL ) == 0) {
296 int temp = atoi( val );
297 if (temp >= 0 && temp <= 2)
298 output_peer_config->congestion_control_mode = temp;
299 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_TIMING_MODE ) == 0) {
300 int temp = atoi( val );
301 if (temp >= 0 && temp <= 2)
302 output_peer_config->timing_mode = temp;
303 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_MIN_RETRIES ) == 0) {
304 int temp = atoi( val );
305 if (temp > 0)
306 output_peer_config->min_retries = temp;
307 } else if (strcmp( url_params[i].key, RIST_URL_PARAM_MAX_RETRIES ) == 0) {
308 int temp = atoi( val );
309 if (temp > 0)
310 output_peer_config->max_retries = temp;
311 } else if (output_peer_config->version >= 1 &&
312 strcmp( url_params[i].key, RIST_URL_PARAM_SPLIT_MODE ) == 0) {
313 if (strcmp(val, "off") == 0)
314 output_peer_config->split_mode = LIBRIST_SPLIT_MODE_OFF;
315 else if (strcmp(val, "auto") == 0 || strcmp(val, "ts") == 0)
316 output_peer_config->split_mode = LIBRIST_SPLIT_MODE_AUTO;
317 else if (strcmp(val, "half") == 0)
318 output_peer_config->split_mode = LIBRIST_SPLIT_MODE_HALF;
319 else {
320 ret = -1;
321 fprintf(stderr, "Unknown split mode '%s'; expected off|auto|half\n", val);
322 }
323 } else if (output_peer_config->version >= 1 &&
324 strcmp( url_params[i].key, RIST_URL_PARAM_MERGE_MODE ) == 0) {
325 if (strcmp(val, "off") == 0)
326 output_peer_config->merge_mode = LIBRIST_MERGE_MODE_OFF;
327 else if (strcmp(val, "pairs") == 0)
328 output_peer_config->merge_mode = LIBRIST_MERGE_MODE_PAIRS;
329 else if (strcmp(val, "auto") == 0)
330 output_peer_config->merge_mode = LIBRIST_MERGE_MODE_AUTO;
331 else {
332 ret = -1;
333 fprintf(stderr, "Unknown merge mode '%s'; expected off|auto|pairs\n", val);
334 }
335 } else if (output_peer_config->version >= 2 && strcmp( url_params[i].key, RIST_URL_PARAM_REFLECTOR ) == 0) {
336 int temp = atoi( val );
337 if (temp >= 0 && temp <= 1)
338 output_peer_config->reflector = temp;
339 } else if (output_peer_config->version >= 2 && strcmp( url_params[i].key, RIST_URL_PARAM_LOCAL_PORT ) == 0) {
340 int temp = atoi( val );
341 if (temp > 0 && temp <= 65535)
342 output_peer_config->local_port = (uint16_t)temp;
343 } else if (output_peer_config->version >= 5 &&
344 strcmp( url_params[i].key, RIST_URL_PARAM_RECOVERY_DEPTH ) == 0) {
345 char *endp = NULL;
346 long temp = strtol(val, &endp, 10);
347 if (endp == val || *endp != '\0' ||
348 temp < RIST_RECOVERY_DEPTH_MIN || temp > RIST_RECOVERY_DEPTH_MAX) {
349 ret = -1;
350 fprintf(stderr, "Invalid recovery-depth '%s'; expected %d..%d "
351 "(ring = 65536 << depth packets; default %d)\n", val,
352 RIST_RECOVERY_DEPTH_MIN, RIST_RECOVERY_DEPTH_MAX,
353 RIST_RECOVERY_DEPTH_DEFAULT);
354 } else {
355 output_peer_config->recovery_depth = (uint8_t)temp;
356 }
357 } else if (output_peer_config->version >= 4 &&
358 strcmp( url_params[i].key, RIST_URL_PARAM_PROFILE ) == 0) {
359 /* version >= 4: writing profile fields on a
360 * struct sized for an older version would
361 * overflow the caller's allocation. */
362 char *endp = NULL;
363 long temp = strtol(val, &endp, 10);
364 if (endp == val || *endp != '\0' ||
365 temp < RIST_PROFILE_SIMPLE || temp > RIST_PROFILE_ADVANCED) {
366 ret = -1;
367 fprintf(stderr, "Invalid profile '%s'; expected 0|1|2\n", val);
368 continue;
369 }
370 output_peer_config->profile = (enum rist_profile)temp;
371 output_peer_config->profile_set = 1;
372 } else {
373 ret = -1;
374 fprintf(stderr, "Unknown or invalid parameter %s\n", url_params[i].key);
375 }
376 }
377 }
378 strncpy((void *)output_peer_config->address, url, clean_url_len >= RIST_MAX_STRING_LONG ? RIST_MAX_STRING_LONG-1 : clean_url_len - 1);
379
380 free( tmp_url );
381
382 if (ret != 0)
383 return num_params;
384 else
385 return 0;
386 }
387
388 struct rist_common_ctx *get_cctx(struct rist_peer *peer)
389 {
390 if (peer->sender_ctx) {
391 return &peer->sender_ctx->common;
392 } else {
393 return &peer->receiver_ctx->common;
394 }
395 }
396
397 int rist_max_jitter_set(struct rist_common_ctx *ctx, int t)
398 {
399 if (t > 0) {
400 ctx->rist_max_jitter = t * RIST_CLOCK;
401 return 0;
402 }
403
404 return -1;
405 }
406
407 int rist_recovery_rtt_multiplier_set_internal(struct rist_common_ctx *ctx, int multiplier)
408 {
409 if (multiplier >= 1) {
410 ctx->recovery_rtt_multiplier = multiplier;
411 return 0;
412 }
413 return -1;
414 }
415
416 /* Reference packet size for the config-time recovery-window sanity check.
417 * 7x188 MPEG-TS over RTP is the common RIST framing. Smaller packets put
418 * MORE packets in the buffer and make the window tighter, so this estimate
419 * is deliberately optimistic: it only warns when the configuration clearly
420 * overruns the window even with full-size packets. */
421 #define RIST_RECOVERY_REF_PKT_BYTES 1316
422
423 /* Warn (once, at peer-config time) if the configured recovery-maxbitrate and
424 * max buffer would queue more packets than the recovery window can address.
425 * Packets beyond the window cannot be retransmitted regardless of how many
426 * NACKs are sent. window is the addressable window in packets for this role
427 * (receiver NACK window or sender retransmit window). */
428 static void rist_warn_recovery_window(struct rist_peer *peer, size_t window, bool sender)
429 {
430 uint32_t maxbitrate = peer->config.recovery_maxbitrate; /* kbps */
431 uint32_t length_max = peer->config.recovery_length_max; /* ms */
432 if (maxbitrate == 0 || length_max == 0 || window == 0)
433 return;
434 uint64_t pkts_in_buffer =
435 (uint64_t)maxbitrate * length_max / (RIST_RECOVERY_REF_PKT_BYTES * 8);
436 if (pkts_in_buffer <= window)
437 return;
438 struct rist_common_ctx *cctx = get_cctx(peer);
439 bool advanced = (cctx->profile == RIST_PROFILE_ADVANCED);
440 rist_log_priv(cctx, RIST_LOG_WARN,
441 "Peer #%"PRIu32": recovery config exceeds the %s recovery window. "
442 "At %u kbps a %u ms buffer holds ~%"PRIu64" packets (assuming ~%d-byte "
443 "packets; smaller packets are worse), but the %s-profile %s window "
444 "addresses only %zu packets - packets beyond it cannot be retransmitted. %s\n",
445 peer->adv_peer_id,
446 sender ? "sender" : "receiver",
447 maxbitrate, length_max, pkts_in_buffer, RIST_RECOVERY_REF_PKT_BYTES,
448 advanced ? "Advanced" : (cctx->profile == RIST_PROFILE_MAIN ? "Main" : "Simple"),
449 sender ? "retransmit" : "NACK",
450 window,
451 advanced
452 ? "Lower recovery-maxbitrate/buffer, or enlarge the ring via ?recovery-depth= (or rist_recovery_depth_set()) before rist_start()."
453 : "Lower recovery-maxbitrate/buffer, or use the Advanced profile for a 32-bit sequence space.");
454 }
455
456 static void init_peer_settings(struct rist_peer *peer)
457 {
458 /* 0 means unset, not unlimited: every reader below takes it as a literal
459 * ceiling of zero. ?bandwidth=0 is ignored the same way. */
460 if (peer->config.recovery_maxbitrate == 0) {
461 rist_log_priv(get_cctx(peer), RIST_LOG_WARN,
462 "Peer #%"PRIu32": a recovery-maxbitrate of 0 disables retransmission "
463 "instead of lifting the ceiling, so using the %d kbps default. Set it "
464 "to the ceiling you want for payload plus retransmissions.\n",
465 peer->adv_peer_id, RIST_DEFAULT_RECOVERY_MAXBITRATE);
466 peer->config.recovery_maxbitrate = RIST_DEFAULT_RECOVERY_MAXBITRATE;
467 }
468
469 peer->eight_times_rtt = peer->config.recovery_rtt_min * 8;
470 /* Midpoint of the configured buffer range, and the same on both ends so the
471 * two sides agree on how long a silent peer has to come back. The receiver
472 * scales its reorder buffer from here; the sender holds a dead peer's place
473 * in the send rotation for this long, and floors its liveness timeout on it. */
474 peer->recovery_buffer_ticks =
475 ((uint64_t)(peer->config.recovery_length_max - peer->config.recovery_length_min) / 2 +
476 peer->config.recovery_length_min) * RIST_CLOCK;
477 if (peer->receiver_mode) {
478 assert(peer->receiver_ctx != NULL);
479 uint32_t recovery_maxbitrate_mbps = peer->config.recovery_maxbitrate < 1000 ? 1 : peer->config.recovery_maxbitrate / 1000;
480 peer->missing_counter_max =
481 (uint32_t)(peer->recovery_buffer_ticks / RIST_CLOCK) * recovery_maxbitrate_mbps /
482 (sizeof(struct rist_gre_seq) + sizeof(struct rist_rtp_hdr) + sizeof(uint32_t));
483
484 {
485 struct rist_common_ctx *cctx = get_cctx(peer);
486 size_t rwin = ((cctx->profile == RIST_PROFILE_ADVANCED)
487 ? cctx->recovery_queue_max : UINT16_SIZE) / 2;
488 rist_warn_recovery_window(peer, rwin, false);
489 }
490
491 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
492 "New peer with id #%"PRIu32" was configured with maxrate=%d/%d bufmin=%d bufmax=%d reorder=%d rttmin=%d rttmax=%d congestion_control=%d min_retries=%d max_retries=%d\n",
493 peer->adv_peer_id, peer->config.recovery_maxbitrate, peer->config.recovery_maxbitrate_return, peer->config.recovery_length_min, peer->config.recovery_length_max, peer->config.recovery_reorder_buffer,
494 peer->config.recovery_rtt_min /RIST_CLOCK, peer->config.recovery_rtt_max /RIST_CLOCK, peer->config.congestion_control_mode, peer->config.min_retries, peer->config.max_retries);
495 if (peer->config.recovery_length_min != peer->config.recovery_length_max)
496 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Enabling automatic buffer scaling\n");
497 }
498 else {
499 assert(peer->sender_ctx != NULL);
500 struct rist_sender *ctx = peer->sender_ctx;
501 {
502 size_t swin = ((ctx->common.profile == RIST_PROFILE_ADVANCED)
503 ? ctx->sender_queue_max : UINT16_SIZE) / 2;
504 rist_warn_recovery_window(peer, swin, true);
505 }
506 /* Global context settings */
507 if (peer->config.recovery_maxbitrate > ctx->recovery_maxbitrate_max) {
508 ctx->recovery_maxbitrate_max = peer->config.recovery_maxbitrate;
509 int max_jitter_ms = ctx->common.rist_max_jitter / RIST_CLOCK;
510 // Asume MTU of 1400 for now
511 uint32_t max_nacksperloop = ctx->recovery_maxbitrate_max * max_jitter_ms / (8*1400);
512 // Normalize against the total buffer size; guard the divisor in
513 // case a 0 buffer ever gets past URL/API validation (SIGFPE).
514 if (peer->config.recovery_length_max == 0)
515 peer->config.recovery_length_max = 1;
516 max_nacksperloop = max_nacksperloop * 1000 / peer->config.recovery_length_max;
517 // Anything less that 2240Kbps at 5ms will round down to zero (100Mbps is 44)
518 if (max_nacksperloop == 0)
519 max_nacksperloop = 1;
520 // The effective buffer is 50% the total buffer size
521 max_nacksperloop = max_nacksperloop * 2;
522 if (max_nacksperloop > ctx->max_nacksperloop) {
523 ctx->max_nacksperloop = (uint32_t)max_nacksperloop;
524 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Setting max nacks per cycle to %"PRIu32"\n",
525 max_nacksperloop);
526 }
527 }
528
529 if (!peer->listening && peer->config.weight != RIST_PEER_WEIGHT_DUPLICATE && !peer->parent) {
530 ctx->total_weight += peer->config.weight;
531 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Peer weight: %lu\n", peer->config.weight);
532 }
533
534 /* Set target recover size (buffer) */
535 if ((peer->config.recovery_length_max + (2 * peer->config.recovery_rtt_min)) > ctx->sender_recover_min_time) {
536 ctx->sender_recover_min_time = peer->config.recovery_length_max + (2 * peer->config.recovery_rtt_min / RIST_CLOCK);
537 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Setting buffer size to %zums (Max buffer size + 2 * Min RTT, %zu+2*%zu)\n", ctx->sender_recover_min_time,
538 peer->config.recovery_length_max,peer->config.recovery_rtt_min / RIST_CLOCK);
539 // TODO: adjust this size based on the dynamic RTT measurement
540 }
541
542 }
543 }
544
545 struct rist_buffer *rist_new_buffer(struct rist_common_ctx *ctx, const void *buf, size_t len, uint8_t type, uint32_t seq, uint64_t source_time, uint16_t src_port, uint16_t dst_port)
546 {
547 RIST_MARK_UNUSED(ctx);
548 // TODO: we will ran out of stack before heap and when that happens malloc will crash not just
549 // return NULL ... We need to find and remove all heap allocations
550 struct rist_buffer *b;
551 b = malloc(sizeof(*b));
552 if (!b) {
553 fprintf(stderr, "OOM\n");
554 return NULL;
555 }
556
557 b->data = malloc(len + RIST_MAX_PAYLOAD_OFFSET);
558 if (!b->data) {
559 free(b);
560 fprintf(stderr, "OOM\n");
561 return NULL;
562 }
563 b->alloc_size = len;
564 if (buf != NULL && len > 0)
565 {
566 memcpy((uint8_t *)b->data + RIST_MAX_PAYLOAD_OFFSET, buf, len);
567 }
568 b->alloc_size = len;
569 b->next_free = NULL;
570 b->free = false;
571 b->size = len;
572 b->source_time = source_time;
573 b->seq = seq;
574 b->time = timestampNTP_u64();
575 b->type = type;
576 b->src_port = src_port;
577 b->dst_port = dst_port;
578 b->last_retry_request = 0;
579 b->transmit_count = 0;
580 b->use_seq = 0;
581 b->retry_queued = false;
582 return b;
583 }
584
585 void free_rist_buffer(struct rist_common_ctx *ctx, struct rist_buffer *b)
586 {
587 RIST_MARK_UNUSED(ctx);
588 free(b->data);
589 free(b);
590
591 }
592
593 static uint64_t receiver_calculate_packet_time(struct rist_flow *f, const uint64_t source_time, uint64_t now, bool retry, uint8_t payload_type)
594 {
595 //Check and correct timing
596 uint64_t packet_time = source_time + f->time_offset;
597 if (RIST_UNLIKELY(!retry && source_time < f->max_source_time && ((f->max_source_time - source_time) > (UINT32_MAX /2)) && (now - f->time_offset_changed_ts) > 3 * f->recovery_buffer_ticks))
598 {
599 int64_t new_offset = (int64_t)now - (int64_t)source_time;
600 int64_t offset_diff = llabs(new_offset - f->time_offset);
601 //Make sure the new and old offsets differ at least by 10 hrs, otherwise something is wrong.
602 if (offset_diff > (int64_t)(10LL * 3600LL * 1000LL * RIST_CLOCK)) {
603 f->time_offset_old = f->time_offset;
604 //Calculate new offset by getting max time for payload type and adding it to old offset
605 //Fast path for mpegts payload type with clock of 90khz
606 if (RIST_UNLIKELY(payload_type != RTP_PTYPE_RIST))
607 f->time_offset += convertRTPtoNTP(payload_type, 0, UINT32_MAX);
608 else
609 f->time_offset += ((uint64_t)UINT32_MAX << 32) / RTP_PTYPE_MPEGTS_CLOCKHZ;
610 rist_log_priv(get_cctx(f->peer_lst[0]), RIST_LOG_INFO, "Clock wrapped, old offset: %" PRId64 " new offset %" PRId64 "\n", f->time_offset / RIST_CLOCK, f->time_offset_old / RIST_CLOCK);
611 f->offset_recalc_sample_count = 0;
612 f->max_source_time = 0;
613 f->time_offset_changed_ts = now;
614 }
615 packet_time = source_time + f->time_offset;
616 //Packets with old clock will be too big due to the wrong offset.
617 } else if (RIST_UNLIKELY(packet_time > f->last_packet_ts && ((packet_time - f->last_packet_ts) > UINT32_MAX / 2) && (now - f->time_offset_changed_ts) < 3 * f->recovery_buffer_ticks))
618 {
619 packet_time = source_time + f->time_offset_old;
620 } else if (source_time > f->max_source_time)
621 {
622 f->last_packet_ts = packet_time;
623 f->max_source_time = source_time;
624 }
625 return packet_time;
626 }
627
628 static int receiver_insert_queue_packet(struct rist_flow *f, struct rist_peer *peer, size_t idx, const void *buf, size_t len, uint32_t seq, uint64_t source_time, uint16_t src_port, uint16_t dst_port, uint64_t packet_time)
629 {
630 /*
631 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
632 "Inserting seq %"PRIu32" len %zu source_time %"PRIu32" at idx %zu\n",
633 seq, len, source_time, idx);
634 */
635 f->receiver_queue[idx] = rist_new_buffer(get_cctx(peer), buf, len, RIST_PAYLOAD_TYPE_DATA_RAW, seq, source_time, src_port, dst_port);
636 if (RIST_UNLIKELY(!f->receiver_queue[idx])) {
637 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Could not create packet buffer inside receiver buffer, OOM, decrease max bitrate or buffer time length\n");
638 return -1;
639 }
640 f->receiver_queue[idx]->peer = peer;
641 f->receiver_queue[idx]->packet_time = packet_time;
642 f->receiver_queue[idx]->target_output_time = packet_time + f->recovery_buffer_ticks;
643 atomic_fetch_add_explicit(&f->receiver_queue_size, len, memory_order_release);
644 if (f->cbr_output) {
645 /* Counted on the way in, so the estimate measures the source. */
646 atomic_fetch_add_explicit(&f->cbr_arrived_bytes, len, memory_order_relaxed);
647 }
648
649 return 0;
650 }
651
652 static inline void receiver_mark_missing(struct rist_flow *f, struct rist_peer *peer, uint32_t current_seq, uint64_t rtt) {
653 uint32_t counter = 1;
654 uint64_t packet_time_last = 0;
655 /* Index the ring exactly as receiver_enqueue() does. 16-bit flows had a
656 * sequence range equal to receiver_queue_max so a raw seq was always a
657 * valid index, but a 32-bit (Advanced) seq can exceed receiver_queue_max
658 * and run off the array -> OOB read of a stale/NULL slot, then a NULL
659 * deref. */
660 size_t last_idx = f->last_seq_found & (f->receiver_queue_max - 1);
661 size_t cur_idx = current_seq & (f->receiver_queue_max - 1);
662 if (RIST_UNLIKELY(!f->receiver_queue[last_idx]))
663 if (RIST_LIKELY(!f->rtc_timing_mode))
664 packet_time_last = timestampNTP_u64();
665 else
666 packet_time_last = timestampNTP_RTC_u64();
667 else
668 packet_time_last = f->receiver_queue[last_idx]->packet_time;
669 uint64_t packet_time_now;
670 if (RIST_UNLIKELY(!f->receiver_queue[cur_idx])) {
671 if (RIST_LIKELY(!f->rtc_timing_mode))
672 packet_time_now = timestampNTP_u64();
673 else
674 packet_time_now = timestampNTP_RTC_u64();
675 } else {
676 packet_time_now = f->receiver_queue[cur_idx]->packet_time;
677 }
678 /* short_seq (Simple/Main) flows wrap at 16 bits; 32-bit (Advanced) flows
679 * use the true gap so a real >64k loss is not truncated. Cap mirrors the
680 * recovery-walk hole cap (UINT16_SIZE/2 short, receiver_queue_max/2 else). */
681 uint32_t missing_count = rist_seq_gap(current_seq, f->last_seq_found,
682 f->short_seq);
683 uint32_t missing_count_cap = f->short_seq
684 ? (UINT16_SIZE / 2)
685 : (uint32_t)(f->receiver_queue_max / 2);
686 if (missing_count > missing_count_cap)
687 return;
688 uint64_t interpacket_time = (packet_time_now - packet_time_last) / (missing_count +1);
689 uint32_t missing_seq = (f->last_seq_found + counter);
690
691 if (f->short_seq)
692 missing_seq = (uint16_t)missing_seq;
693
694 uint64_t nack_time = packet_time_last;
695 while (missing_seq != current_seq)
696 {
697 nack_time += interpacket_time;
698 if (RIST_UNLIKELY(peer->buffer_bloat_active || f->missing_counter > peer->missing_counter_max))
699 {
700 if (f->missing_counter > peer->missing_counter_max)
701 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
702 "Retry buffer is already too large (%d) for the configured "
703 "bandwidth ... ignoring missing packet(s).\n",
704 f->missing_counter);
705 if (peer->buffer_bloat_active)
706 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
707 "Link has collapsed. Not queuing new retries until it recovers.\n");
708 break;
709 }
710 rist_receiver_missing(f, peer, nack_time, missing_seq, rtt);
711 if (RIST_UNLIKELY(counter == f->receiver_queue_max))
712 break;
713 counter++;
714 missing_seq = (f->last_seq_found + counter);
715 if (f->short_seq)
716 missing_seq = (uint16_t)missing_seq;
717 }
718 }
719
720 int compare(const void *a, const void *b)
721 {
722 uint64_t ua = *(const uint64_t *)a;
723 uint64_t ub = *(const uint64_t *)b;
724 return (ua > ub) - (ua < ub);
725 }
726
727 static void recalculate_clock_offset(struct rist_flow *flow)
728 {
729 //arbitrarily chosen minimal sample count
730 if (flow->offset_recalc_sample_count < 100)
731 return;
732
733 /* to counter clock drift we are recalculating our offset every 2048 inserted
734 packets. Every "correctly" (in-order, no-discontinuities) packet's clock offset
735 is inserted into an array. Of which we will take the median. */
736 qsort(flow->offset_recalc_samples, flow->offset_recalc_sample_count, sizeof(uint64_t), compare);
737 size_t middle = flow->offset_recalc_sample_count / 2;
738 uint64_t median_offset = flow->offset_recalc_samples[middle];
739 flow->offset_recalc_sample_count = 0;
740 uint64_t diff = 0;
741 uint64_t negative = (median_offset < (uint64_t)flow->time_offset);
742 if (negative)
743 diff = flow->time_offset - median_offset;
744 else
745 diff = median_offset - flow->time_offset;
746 rist_log_priv2(flow->logging_settings, RIST_LOG_DEBUG, "Recalculated clock offset, old offset: %lu, new offset: %lu difference: %c%lu usec\n",
747 flow->time_offset, median_offset, negative? '-': '+', (diff * 1000 / RIST_CLOCK));
748 flow->time_offset = median_offset;
749 }
750
751
752 static int receiver_enqueue(struct rist_peer *peer, uint64_t source_time, uint64_t packet_recv_time, const void *buf, size_t len, uint32_t seq, uint64_t rtt, bool retry, uint16_t src_port, uint16_t dst_port, uint8_t payload_type)
753 {
754 struct rist_flow *f = peer->flow;
755
756 // fprintf(stderr,"receiver enqueue seq is %"PRIu32", source_time %"PRIu64"\n",
757 // seq, source_time);
758 uint64_t now;
759 uint64_t now_monotonic = packet_recv_time;
760 if (RIST_LIKELY(!f->rtc_timing_mode))
761 now = now_monotonic;
762 else
763 now = timestampNTP_RTC_u64();
764 //fprintf(stderr, "Offset would've been: %llu\n", now - source_time);
765 if (RIST_UNLIKELY((!f->receiver_queue_has_items && retry) || (f->rtc_timing_mode && f->time_offset == 0)))
766 return -1;
767 if (RIST_UNLIKELY(!f->receiver_queue_has_items)) {
768 /* we just received our first packet for this flow */
769 switch (rist_flow_reanchor_check(source_time, f->max_source_time,
770 f->recovery_buffer_ticks,
771 f->reanchor_wait_since, now_monotonic)) {
772 case RIST_REANCHOR_WAIT:
773 if (!f->reanchor_wait_since) {
774 f->reanchor_wait_since = now_monotonic;
775 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
776 "Waiting for a current packet to anchor flow on, peer %"PRIu32" is %" PRIu64 " ms behind\n",
777 peer->adv_peer_id, (f->max_source_time - source_time) / RIST_CLOCK);
778 }
779 return -1;
780 case RIST_REANCHOR_FORCED:
781 rist_log_priv(get_cctx(peer), RIST_LOG_WARN,
782 "No current packet to anchor flow on, using seq %" PRIu32 " from peer %"PRIu32", %" PRIu64 " ms behind\n",
783 seq, peer->adv_peer_id, (f->max_source_time - source_time) / RIST_CLOCK);
784 break;
785 case RIST_REANCHOR_OK:
786 break;
787 }
788 f->reanchor_wait_since = 0;
789 pthread_mutex_lock(&f->mutex);
790 if (atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire) > 0)
791 {
792 /* Clear the queue if the queue had data */
793 /* f->receiver_queue_has_items can be reset to false when the output queue is emptied */
794 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
795 "Clearing up old %zu bytes of old buffer data\n", atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire));
796 /* Delete all buffer data (if any) */
797 empty_receiver_queue(f, get_cctx(peer));
798 }
799 rist_flush_missing_flow_queue(f);
800 /* Initialize flow session timeout and stats timers */
801 f->flag_flow_buffer_start = true;
802 f->last_recv_ts = now_monotonic;
803 f->checks_next_time = now_monotonic;
804 /* Calculate and store clock offset with respect to source */
805 if (!f->rtc_timing_mode)
806 f->time_offset = (int64_t)now_monotonic - (int64_t)source_time;
807 /* This ensures the next packet does not trigger nacks */
808 f->last_seq_output = seq - 1;
809 f->last_seq_found = seq;
810 f->max_source_time = source_time;
811 /* This will synchronize idx and seq so we can insert packets into receiver buffer based on seq number */
812 size_t idx_initial = seq & (f->receiver_queue_max -1);
813 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
814 "Storing first packet seq %" PRIu32 ", idx %zu, %" PRIu64 ", offset %" PRId64 " ms, output_idx %zu\n",
815 seq, idx_initial, source_time, peer->flow->time_offset / RIST_CLOCK, idx_initial);
816 uint64_t packet_time = source_time + f->time_offset;
817
818 f->last_packet_ts = packet_time;
819 f->time_offset_changed_ts = 0;
820 f->time_offset_old = f->time_offset;
821 /* Discard clock-drift samples gathered against the previous
822 * baseline. A flow-id change or a Main<->Advanced wire-framing
823 * switch (the two framings carry source_time in different
824 * timestamp domains) lands here with stale samples still queued;
825 * blending them into the median yields a bogus multi-second
826 * offset correction that releases the whole buffer at once and
827 * overflows the data-out fifo. Matches the clock-wrap reset. */
828 f->offset_recalc_sample_count = 0;
829
830 receiver_insert_queue_packet(f, peer, idx_initial, buf, len, seq, source_time, src_port, dst_port, packet_time);
831 atomic_store_explicit(&f->receiver_queue_output_idx, idx_initial, memory_order_release);
832
833 /* reset stats and timing state */
834 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
835 memset(&f->stats_instant, 0, sizeof(f->stats_instant));
836 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
837 f->last_output_time = 0;
838 f->too_late_ctr = 0;
839 f->receiver_queue_has_items = true;
840 pthread_mutex_unlock(&f->mutex);
841 return 0; // not a dupe
842 }
843
844 uint64_t packet_time = receiver_calculate_packet_time(f, source_time, now, retry, payload_type);
845 size_t idx = seq & (f->receiver_queue_max - 1);
846 if (RIST_UNLIKELY(peer->config.timing_mode == RIST_TIMING_MODE_ARRIVAL && retry))
847 {
848 //arrival packet time would be incorrect for a retry packet, so instead we interpolate between packets.
849 //this does assume CBR
850 struct rist_buffer *previous = NULL;
851 size_t index = (idx -1)& (f->receiver_queue_max - 1);
852 while (previous == NULL && index != idx)
853 {
854 previous = f->receiver_queue[index];
855 index = (index -1)& (f->receiver_queue_max - 1);
856 }
857 struct rist_buffer *next = NULL;
858 index = (idx +1)& (f->receiver_queue_max -1);
859 while (next == NULL && index != idx)
860 {
861 next = f->receiver_queue[index];
862 index = (index +1)& (f->receiver_queue_max -1);
863 }
864 //interpolate the arrival time, assuming CBR
865 /* Neighbours can be non-monotonic under arrival-based timing;
866 * clamp the CBR estimate into the interval instead of asserting. */
867 if (next && previous && next->packet_time > previous->packet_time)
868 {
869 uint32_t steps = (next->seq - previous->seq);
870 if (f->short_seq)
871 steps = (uint16_t)steps;
872 uint32_t steps_since_previous = seq - previous->seq;
873 if (f->short_seq)
874 steps_since_previous = (uint16_t)steps_since_previous;
875 if (steps > 1 && steps_since_previous > 0 && steps_since_previous < steps) {
876 /* multiply before dividing so integer rounding cannot push
877 * the estimate up to or past next->packet_time */
878 uint64_t span = next->packet_time - previous->packet_time;
879 packet_time = previous->packet_time + (span * steps_since_previous) / steps;
880 } else {
881 /* seq is not strictly between the neighbours (gap, reorder
882 * or sequence-number wrap): place it next to next. */
883 packet_time = next->packet_time - 1;
884 }
885 if (packet_time < previous->packet_time)
886 packet_time = previous->packet_time;
887 else if (packet_time > next->packet_time)
888 packet_time = next->packet_time;
889 } else if (next)
890 {
891 /* No usable previous neighbour, or neighbours whose times are
892 * non-monotonic: use next's time. */
893 packet_time = next->packet_time;
894 }
895 }
896
897 // Now, get the new position and check what is there
898 /* We need to check if the reader queue has progressed passed this packet, if
899 this is the case we silently drop the packet as it would not be output in a
900 valid way anyway.
901 We only check this for packets that arrive out of order (i.e.: with a lower
902 output time than the highest known output time) */
903 size_t reader_idx;
904 bool out_of_order = false;
905 uint32_t expected_seq = rist_seq_next(f->last_seq_found, f->short_seq);
906 if (RIST_UNLIKELY(packet_time < f->last_packet_ts && seq != expected_seq)) {
907 if (now > (packet_time + (f->recovery_buffer_ticks *1.1)))
908 {
909 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Packet %"PRIu32" too late, dropping!\n", seq);
910 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
911 f->stats_instant.dropped_late++;
912 /* This soft reset is intentional anti-stall behavior: when a
913 * flow re-bases (received falls back toward 0) it lets the
914 * queue re-anchor onto the changed path instead of stalling.
915 * A crafted late-packet burst can trip it early, but the queue
916 * just rebuilds from the next in-window packet (no persistent
917 * effect), so it is deliberately left without a received floor
918 * here; the hard reset below keeps its received > 100 floor. */
919 if (f->stats_instant.dropped_late > 5 * f->stats_instant.received)
920 f->receiver_queue_has_items = false;
921 if ((f->stats_instant.dropped_late > (f->stats_instant.received * 5) && f->stats_instant.received > 100) ||
922 (f->stats_instant.dropped_late > 100 && f->stats_instant.received == 0)) {
923 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Too many late packets received, resetting flow");
924 f->receiver_queue_has_items = false;
925 }
926 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
927 return -1;
928 }
929 if (!retry) {
930 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
931 "Out of order packet received, seq %" PRIu32 " / age %" PRIu64 " ms\n",
932 seq, (timestampNTP_u64() - packet_time) / RIST_CLOCK);
933 out_of_order = true;
934 }
935 }
936 reader_idx = atomic_load_explicit(&f->receiver_queue_output_idx, memory_order_acquire);
937 if (RIST_UNLIKELY(idx == ((reader_idx -1) &(f->receiver_queue_max -1))))
938 {
939 //Buffer full!
940 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Buffer is full, dropping packet %"PRIu32"/%zu\n", seq, idx);
941 if (packet_time > f->last_packet_ts)
942 f->last_seq_found = seq;
943 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
944 f->stats_instant.dropped_full++;
945 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
946 //Something is wrong, and we should reset
947 if (f->stats_instant.dropped_full > 100) {
948 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Buffer is full, resetting buffer\n");
949 f->receiver_queue_has_items = false;
950 }
951 return -1;
952 }
953 if (RIST_UNLIKELY(f->receiver_queue[idx])) {
954 // TODO: record stats
955 struct rist_buffer *b = f->receiver_queue[idx];
956 /* Match on seq: the slot index is derived from the sequence number,
957 * and source_time need not be unique per packet, so it cannot
958 * identify a genuine duplicate. A different seq in this slot is a
959 * stale entry from an earlier ring cycle and is replaced below. */
960 if (b->seq == seq) {
961 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Dupe! %"PRIu32"/%zu\n", seq, idx);
962 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
963 f->stats_instant.dupe++;
964 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
965 return 1;
966 }
967 else {
968 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Invalid Dupe (possible seq discontinuity)! %"PRIu32", freeing buffer ...\n", seq);
969 free_rist_buffer(get_cctx(peer), b);
970 f->receiver_queue[idx] = NULL;
971 }
972 }
973
974
975 /* Now, we insert the packet into receiver queue */
976 if (receiver_insert_queue_packet(f, peer, idx, buf, len, seq, source_time, src_port, dst_port, packet_time)) {
977 // only error is OOM, safe to exit here ...
978 return 0;
979 }
980 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
981 if (out_of_order)
982 f->stats_instant.reordered++;
983 f->stats_instant.received++;
984 f->stats_instant.received_bytes += (uint64_t)len;
985 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
986 // Check for missing data and queue retries
987 if (!retry) {
988 /* check for missing packets */
989 // We start at the last known good packet, and look forwards till we hit this seq
990 uint32_t missing_seq = seq - 1;
991 if (f->short_seq)
992 missing_seq = (uint16_t)missing_seq;
993
994 if (!out_of_order && missing_seq != f->last_seq_found)
995 {
996 receiver_mark_missing(f, peer, seq, rtt);
997 } else if (RIST_LIKELY(!f->rtc_timing_mode && !out_of_order))
998 {
999 //packet received in order, use it's offset as a sample in calculation to
1000 //correct clock drift
1001 f->offset_recalc_samples[f->offset_recalc_sample_count] = (int64_t)now - (int64_t)source_time;
1002 f->offset_recalc_sample_count++;
1003 if (f->offset_recalc_sample_count == 2048)
1004 recalculate_clock_offset(f);
1005 }
1006 //If we stopped due to bloat or missing count max this will be incorrect.
1007 if (!out_of_order)
1008 f->last_seq_found = seq;
1009 }
1010 return 0;
1011 }
1012
1013 static int rist_process_nack(struct rist_flow *f, struct rist_missing_buffer *b)
1014 {
1015 uint64_t now;
1016 if (RIST_LIKELY(!f->rtc_timing_mode))
1017 now = timestampNTP_u64();
1018 else
1019 now = timestampNTP_RTC_u64();
1020 struct rist_peer *peer = b->peer;
1021
1022 pthread_mutex_lock(&f->mutex);
1023 uint64_t recovery_buffer_ticks = f->recovery_buffer_ticks;
1024 pthread_mutex_unlock(&f->mutex);
1025
1026 if (b->nack_count >= peer->config.max_retries) {
1027 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Datagram %"PRIu32
1028 " is missing, but nack count is too large (%u), age is %"PRIu64"ms, retry #%lu, max_retries %d, congestion_control_mode %d, stats_receiver_total.recovered_average %d\n",
1029 b->seq,
1030 b->nack_count,
1031 (now - b->insertion_time) / RIST_CLOCK,
1032 b->nack_count,
1033 peer->config.max_retries,
1034 peer->config.congestion_control_mode,
1035 f->stats_total.recovered_average);
1036 return 8;
1037 } else {
1038 if ((uint64_t)(now - b->insertion_time) > (recovery_buffer_ticks *1.1)) {
1039 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
1040 "Datagram %" PRIu32 " is missing but it is too late (%" PRIu64
1041 "ms) to send NACK!, retry #%lu, retry queue %d, max time %"PRIu64"\n",
1042 b->seq, (now - b->insertion_time)/RIST_CLOCK, b->nack_count,
1043 f->missing_counter, recovery_buffer_ticks / RIST_CLOCK);
1044 return 9;
1045 } else if (now >= b->next_nack) {
1046 uint64_t rtt = (peer->eight_times_rtt / 8);
1047 if (rtt < peer->config.recovery_rtt_min) {
1048 rtt = peer->config.recovery_rtt_min;
1049 } else if (rtt > peer->config.recovery_rtt_max) {
1050 rtt = peer->config.recovery_rtt_max;
1051 }
1052 if (b->nack_count == 0) {
1053 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
1054 f->stats_instant.missing++;
1055 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
1056 }
1057
1058 // TODO: make this 10% overhead configurable?
1059 // retry more when we are running out of time (proportional)
1060 /* start with 1.1 * 1000 and go down from there */
1061 //uint32_t ratio = 1100 - (b->nack_count * 1100)/(2*b->peer->config.max_retries);
1062 //b->next_nack = now + (uint64_t)rtt * (uint64_t)ratio * (uint64_t)RIST_CLOCK;
1063 b->next_nack = now + (uint64_t)(rtt * 1.1);
1064 b->nack_count++;
1065
1066 if (get_cctx(peer)->debug)
1067 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Datagram %" PRIu32 " is missing, sending NACK!, next retry in %" PRIu64 "ms, age is %" PRIu64 "ms, retry #%lu, max_size is %" PRIu64 "ms\n",
1068 b->seq, (b->next_nack - now) / RIST_CLOCK,
1069 (now - b->insertion_time) / RIST_CLOCK,
1070 b->nack_count,
1071 recovery_buffer_ticks / RIST_CLOCK);
1072
1073 // update peer information
1074 f->nacks.array[f->nacks.counter] = b->seq;
1075 f->nacks.counter++;
1076 pthread_mutex_lock(&(get_cctx(peer)->stats_lock));
1077 f->stats_instant.retries++;
1078 pthread_mutex_unlock(&(get_cctx(peer)->stats_lock));
1079 }
1080 }
1081
1082 return 0;
1083 }
1084
1085 void free_data_block(struct rist_data_block **const block)
1086 {
1087 assert(block != NULL);
1088 struct rist_data_block *b = *block;
1089 if (!b)
1090 return;
1091
1092 if (atomic_fetch_sub(&b->ref->refcnt, 1) == 1)
1093 {
1094 assert(b->ref->ptr == b);
1095 uint8_t *payload = ((uint8_t*)b->payload - RIST_MAX_PAYLOAD_OFFSET);//this is extremely ugly, though these offsets will stop existing in next release
1096 free(payload);
1097 free((void *)b->ref);
1098 free(b);
1099 }
1100 *block = NULL;
1101 }
1102
1103 static struct rist_data_block *new_data_block(struct rist_data_block *output_buffer_current, struct rist_buffer *b, uint8_t *payload, uint32_t flow_id, uint32_t flags)
1104 {
1105 struct rist_data_block *output_buffer;
1106 if (output_buffer_current) {
1107 if (rist_ref_iswritable(output_buffer_current->ref)) {
1108 output_buffer = output_buffer_current;
1109 uint8_t *p = ((uint8_t*)output_buffer_current->payload - RIST_MAX_PAYLOAD_OFFSET);
1110 free(p);
1111 } else {
1112 free_data_block(&output_buffer_current);
1113 output_buffer = calloc(1, sizeof(*output_buffer));
1114 }
1115 }
1116 else
1117 output_buffer = calloc(1, sizeof(struct rist_data_block));
1118 if (!output_buffer) {
1119 rist_log_priv2(get_cctx(b->peer)->logging_settings, RIST_LOG_ERROR, "Error (re)allocating rist_data_block.");
1120 return NULL;
1121 }
1122 if (!output_buffer->ref) {
1123 output_buffer->ref = rist_ref_create(output_buffer);
1124 if (!output_buffer->ref) {
1125 rist_log_priv2(get_cctx(b->peer)->logging_settings, RIST_LOG_ERROR, "Error allocating rist_ref.");
1126 free(output_buffer);
1127 return NULL;
1128 }
1129 }
1130 output_buffer->peer = b->peer;
1131 output_buffer->flow_id = flow_id;
1132 output_buffer->payload = payload;
1133 output_buffer->payload_len = b->size;
1134 output_buffer->virt_src_port = b->src_port;
1135 output_buffer->virt_dst_port = b->dst_port;
1136 output_buffer->ts_ntp = b->source_time;
1137 output_buffer->seq = b->seq;
1138 output_buffer->flags = flags;
1139 return output_buffer;
1140 }
1141
1142 static void receiver_output(struct rist_receiver *ctx, struct rist_flow *f)
1143 {
1144
1145 uint64_t recovery_buffer_ticks = f->recovery_buffer_ticks;
1146 uint64_t now;
1147 if (RIST_LIKELY(!f->rtc_timing_mode))
1148 now = timestampNTP_u64();
1149 else
1150 now = timestampNTP_RTC_u64();
1151 size_t output_idx = atomic_load_explicit(&f->receiver_queue_output_idx, memory_order_acquire);
1152 while (atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire) > 0 && atomic_load_explicit(&f->shutdown, memory_order_acquire) == 0) {
1153 // Find the first non-null packet in the queuecounter loop
1154 struct rist_buffer *b = f->receiver_queue[output_idx];
1155 size_t holes = 0;
1156 if (!b) {
1157 //rist_log_priv(&ctx->common, RIST_LOG_ERROR, "\tLooking for first non-null packet (%zu)\n", f->receiver_queue_size);
1158 size_t counter = 0;
1159 counter = output_idx;
1160 while (!b) {
1161 counter = (counter + 1)& (f->receiver_queue_max -1);
1162 holes++;
1163 b = f->receiver_queue[counter];
1164 if (counter == output_idx) {
1165 // This should never happen, if this fires queue size is out of sync with reality.
1166 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Did not find any data after a full counter loop (%zu)\n", atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire));
1167 // if the entire buffer is empty, something is very wrong, reset the queue ...
1168 f->receiver_queue_has_items = false;
1169 atomic_store_explicit(&f->receiver_queue_size, 0, memory_order_release);
1170 // exit the function and wait 5ms (max jitter time)
1171 return;
1172 }
1173 }
1174 if (b) {
1175 uint64_t delay1 = (now - b->time);
1176 if (RIST_UNLIKELY(delay1 > (2LLU * recovery_buffer_ticks))) {
1177 // According to the real time clock, it is too late, continue.
1178 } else if (b->target_output_time > now) {
1179 // The block we found is not ready for output, so we wait.
1180 break;
1181 }
1182 }
1183 /* Count the sequence gap, not the ring slots we stepped over:
1184 * the two only agree while the reader sits right behind the
1185 * data, and after an idle source or a re-anchor the walk spans
1186 * far more slots than there are missing packets. */
1187 uint32_t gap = rist_seq_gap(b->seq, rist_seq_next(f->last_seq_output, f->short_seq),
1188 f->short_seq);
1189 size_t max_holes = f->short_seq ? (UINT16_SIZE / 2) : (f->receiver_queue_max / 2);
1190 if (gap <= max_holes) {
1191 pthread_mutex_lock(&ctx->common.stats_lock);
1192 f->stats_instant.lost += gap;
1193 pthread_mutex_unlock(&ctx->common.stats_lock);
1194 }
1195 output_idx = counter;
1196 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1197 "Empty buffer element, flushing %zu hole(s), now at index %zu, size is %zu\n",
1198 holes, counter, atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire));
1199 }
1200 if (b) {
1201 bool merged = false;
1202 if (b->type == RIST_PAYLOAD_TYPE_DATA_RAW) {
1203
1204 now = timestampNTP_u64();
1205 uint64_t delay_rtc = (now - b->time);
1206 if (RIST_UNLIKELY(delay_rtc > (1.1 * recovery_buffer_ticks) )) {
1207 // Double check the age of the packet within our receiver queue
1208 // Safety net for discontinuities in source timestamp, clock drift or improperly scaled timestamp
1209 uint64_t delay = now > b->packet_time ? (now - b->packet_time) : 0;
1210 bool drop = false;
1211 //This should be impossible as we should catch it with the normal case
1212 if (RIST_UNLIKELY(delay_rtc > (2ULL * recovery_buffer_ticks))) {
1213 f->too_late_ctr++;
1214 drop = true;
1215 if (f->too_late_ctr > 100) {
1216 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Too many old packets, resetting buffer\n");
1217 /* clear the latch, else it re-fires every output cycle */
1218 f->too_late_ctr = 0;
1219 f->receiver_queue_has_items = false;
1220 return;
1221 }
1222 goto next;
1223 }
1224 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1225 "Packet %"PRIu32" (%zu bytes) is too old %"PRIu64"/%"PRIu64" ms, deadline = %"PRIu64", offset = %"PRId64" ms, %s data\n",
1226 b->seq, b->size,
1227 delay_rtc / RIST_CLOCK, delay / RIST_CLOCK,
1228 recovery_buffer_ticks / RIST_CLOCK, f->time_offset / RIST_CLOCK,
1229 drop? "dropping" : "releasing");
1230
1231 }
1232 else if (b->target_output_time > now && (!f->currently_scaling_buffer || (f->currently_scaling_buffer && (b->packet_time + f->recovery_buffer_ticks) > now))) {
1233 // This is how we keep the buffer at the correct level
1234 //rist_log_priv(&ctx->common, RIST_LOG_WARN, "age is %"PRIu64"/%"PRIu64" < %"PRIu64", size %zu\n",
1235 // delay_rtc / RIST_CLOCK , delay / RIST_CLOCK, recovery_buffer_ticks / RIST_CLOCK, f->receiver_queue_size);
1236 break;
1237 }
1238 /* The buffer has cleared this packet; pacing decides whether it
1239 * is its turn in the measured cadence yet. Delay only, and it
1240 * yields below rather than hold a packet past its deadline. */
1241 if (f->cbr_output) {
1242 uint64_t iv = rist_pacer_interval_ns(&f->cbr_pacer,
1243 rist_pacer_rate_bps(&f->cbr_rate), b->size, 0);
1244 if (iv) {
1245 uint64_t now_ns = timestampNTP_to_ns(now);
1246 f->cbr_interval_ns = iv;
1247 if (rist_pacer_due_ns(&f->cbr_pacer, now_ns) > now_ns) {
1248 uint64_t overdue = now > b->target_output_time ?
1249 (now - b->target_output_time) : 0;
1250 if (overdue < ((uint64_t)f->cbr_max_hold_us * RIST_CLOCK) / 1000) {
1251 f->cbr_paced_hold = true; /* waiting its turn, not idle */
1252 break;
1253 }
1254 /* Re-anchor, else every later packet lands here too. */
1255 f->cbr_overdue_releases++;
1256 rist_pacer_reset(&f->cbr_pacer);
1257 rist_pacer_due_ns(&f->cbr_pacer, now_ns);
1258 }
1259 rist_pacer_advance(&f->cbr_pacer, iv);
1260 }
1261 }
1262 if (holes > 0)
1263 {
1264 rist_log_priv(&ctx->common, RIST_LOG_DEBUG, "Did not find any data after %zu holes (%zu bytes in queue)\n",
1265 holes, atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire));
1266 }
1267 f->too_late_ctr = 0;
1268 // Check sequence number and report lost packet
1269 uint32_t next_seq = f->last_seq_output + 1;
1270 f->last_output_time = now;
1271 if (f->short_seq)
1272 next_seq = (uint16_t)next_seq;
1273 if (b->seq != next_seq && !holes) {
1274 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1275 "Discontinuity, expected %" PRIu32 " got %" PRIu32 "\n",
1276 f->last_seq_output + 1, b->seq);
1277 pthread_mutex_lock(&ctx->common.stats_lock);
1278 f->stats_instant.lost++;
1279 pthread_mutex_unlock(&ctx->common.stats_lock);
1280 holes = 1;
1281 }
1282 if (b->type == RIST_PAYLOAD_TYPE_DATA_RAW) {
1283 uint32_t flags = 0;
1284 if (holes)
1285 flags = RIST_DATA_FLAGS_DISCONTINUITY;
1286 if (f->flag_flow_buffer_start) {
1287 f->flag_flow_buffer_start = false;
1288 flags |= RIST_DATA_FLAGS_FLOW_BUFFER_START;
1289 }
1290
1291 bool merge_active = (ctx->merge_mode == LIBRIST_MERGE_MODE_PAIRS) ||
1292 (ctx->merge_mode == LIBRIST_MERGE_MODE_AUTO &&
1293 f->merge_auto_enabled);
1294
1295 struct rist_data_block *block = NULL;
1296
1297 if (merge_active && (b->seq & 1) == 0) {
1298 size_t partner_idx = (output_idx + 1) & (f->receiver_queue_max - 1);
1299 struct rist_buffer *b2 = f->receiver_queue[partner_idx];
1300 if (b2 && b2->type == RIST_PAYLOAD_TYPE_DATA_RAW &&
1301 b2->seq == rist_seq_next(b->seq, f->short_seq) &&
1302 b2->source_time == b->source_time) {
1303 size_t combined_len = b->size + b2->size;
1304 uint8_t *combined = malloc(RIST_MAX_PAYLOAD_OFFSET + combined_len);
1305 if (combined) {
1306 memcpy(combined + RIST_MAX_PAYLOAD_OFFSET,
1307 (uint8_t *)b->data + RIST_MAX_PAYLOAD_OFFSET, b->size);
1308 memcpy(combined + RIST_MAX_PAYLOAD_OFFSET + b->size,
1309 (uint8_t *)b2->data + RIST_MAX_PAYLOAD_OFFSET, b2->size);
1310 block = calloc(1, sizeof(*block));
1311 if (block) {
1312 block->ref = rist_ref_create(block);
1313 block->peer = b->peer;
1314 block->flow_id = f->flow_id;
1315 block->payload = combined + RIST_MAX_PAYLOAD_OFFSET;
1316 block->payload_len = combined_len;
1317 block->virt_src_port = b->src_port;
1318 block->virt_dst_port = b->dst_port;
1319 block->ts_ntp = b->source_time;
1320 block->seq = b->seq / 2;
1321 block->flags = flags;
1322 merged = true;
1323 ctx->stats_pairs_merged++;
1324 } else {
1325 free(combined);
1326 }
1327 }
1328 if (merged) {
1329 b->data = NULL;
1330 f->last_seq_output = b2->seq;
1331 atomic_fetch_sub_explicit(&f->receiver_queue_size, b2->size, memory_order_relaxed);
1332 f->receiver_queue[partner_idx] = NULL;
1333 free_rist_buffer(&ctx->common, b2);
1334 }
1335 } else {
1336 ctx->stats_orphan_first_delivered++;
1337 }
1338 } else if (merge_active && (b->seq & 1) == 1) {
1339 ctx->stats_orphan_last_delivered++;
1340 }
1341
1342 if (!merged) {
1343 uint8_t *payload = b->data;
1344 block = new_data_block(
1345 NULL, b,
1346 &payload[RIST_MAX_PAYLOAD_OFFSET], f->flow_id, flags);
1347 b->data = NULL;
1348 }
1349 if (ctx->receiver_data_fd >= 0 && block) {
1350 int written;
1351 if (ctx->receiver_data_fd_flags & RIST_DATA_FD_FLAG_TUN)
1352 written = rist_tun_write(ctx->receiver_data_fd, block->payload, block->payload_len);
1353 else
1354 written = (int)write(ctx->receiver_data_fd, block->payload, block->payload_len);
1355 if (written > 0) {
1356 atomic_fetch_add_explicit(&ctx->data_fd_rx_packets, 1, memory_order_relaxed);
1357 atomic_fetch_add_explicit(&ctx->data_fd_rx_bytes, (uint_fast64_t)written, memory_order_relaxed);
1358 }
1359 rist_receiver_data_block_free2(&block);
1360 } else if (ctx->receiver_data_callback && block) {
1361 rist_ref_inc(block->ref);
1362 // send to callback synchronously
1363 ctx->receiver_data_callback(ctx->receiver_data_callback_argument,
1364 block);
1365 }
1366
1367 size_t dataout_fifo_write_index = atomic_load_explicit(&f->dataout_fifo_queue_write_index, memory_order_relaxed);
1368 size_t dataout_fifo_read_index = atomic_load_explicit(&f->dataout_fifo_queue_read_index, memory_order_acquire);
1369 uint32_t fifo_count = (dataout_fifo_write_index - dataout_fifo_read_index)&(ctx->fifo_queue_size -1);
1370 if (fifo_count +1 == ctx->fifo_queue_size || !ctx->fifo_queue_size) {
1371 if (!ctx->receiver_data_callback && ctx->receiver_data_fd < 0)
1372 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Rist data out fifo queue overflow\n");
1373 rist_receiver_data_block_free2(&block);
1374 atomic_store_explicit(&f->fifo_overflow, true, memory_order_release);
1375 } else {
1376 if (RIST_UNLIKELY(atomic_load_explicit(&f->fifo_overflow, memory_order_relaxed) == true)) {
1377 atomic_store_explicit(&f->fifo_overflow, false, memory_order_release);
1378 }
1379 f->dataout_fifo_queue[dataout_fifo_write_index] = block;
1380 atomic_store_explicit(&f->dataout_fifo_queue_write_index, (dataout_fifo_write_index + 1)& (ctx->fifo_queue_size-1), memory_order_relaxed);
1381 // Wake up the fifo read thread (poll)
1382 if (ctx->receiver_data_ready_notify_fd) {
1383 // send a data ready signal by writing a single byte of value 0
1384 char empty = '\0';
1385 if(write(ctx->receiver_data_ready_notify_fd, &empty, 1) == -1)
1386 {
1387 // We ignore the error condition as missing data is not harmful here
1388 // It is only a signaling mechanism
1389 }
1390 }
1391 }
1392 pthread_mutex_lock(&ctx->common.stats_lock);
1393 if (f->stats_instant.buffer_duration_count < 2048)
1394 {
1395 f->stats_instant.buffer_duration[f->stats_instant.buffer_duration_count] = (uint32_t)(delay_rtc / RIST_CLOCK);
1396 f->stats_instant.buffer_duration_count++;
1397 }
1398 pthread_mutex_unlock(&ctx->common.stats_lock);
1399 if (pthread_cond_signal(&(ctx->condition)))
1400 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Call to pthread_cond_signal failed.\n");
1401 }
1402 // Track this one only for data
1403 f->last_seq_output_source_time = b->source_time;
1404 }
1405 //else
1406 // fprintf(stderr, "rtcp skip at %"PRIu32", just removing it from queue\n", b->seq);
1407
1408 next:
1409 if (!merged)
1410 f->last_seq_output = b->seq;
1411 atomic_fetch_sub_explicit(&f->receiver_queue_size, b->size, memory_order_relaxed);
1412 f->receiver_queue[output_idx] = NULL;
1413 free_rist_buffer(&ctx->common, b);
1414 output_idx = (output_idx + 1)& (f->receiver_queue_max -1);
1415 if (merged) {
1416 /* partner already freed and NULLed above; skip its slot */
1417 output_idx = (output_idx + 1) & (f->receiver_queue_max - 1);
1418 }
1419 atomic_store_explicit(&f->receiver_queue_output_idx, output_idx, memory_order_release);
1420 if (atomic_load_explicit(&f->receiver_queue_size, memory_order_acquire) == 0) {
1421 if (f->last_output_time == 0)
1422 f->last_output_time = now;
1423 uint64_t delta = now - f->last_output_time;
1424 rist_log_priv(&ctx->common, RIST_LOG_DEBUG, "Buffer is empty, it has been for %"PRIu64" < %"PRIu64" (ms)!\n",
1425 delta / RIST_CLOCK, recovery_buffer_ticks / RIST_CLOCK);
1426 // if the entire buffer is empty, something is very wrong, reset the queue ...
1427 if (delta > recovery_buffer_ticks)
1428 {
1429 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "stream is dead (%"PRIu64" ms), re-initializing flow\n",
1430 delta/ RIST_CLOCK);
1431 f->receiver_queue_has_items = false;
1432 }
1433 // exit the function and wait 5ms (max jitter time)
1434 return;
1435 }
1436 f->last_output_time = now;
1437 }
1438 }
1439
1440 }
1441
1442 static void send_nack_group(struct rist_receiver *ctx, struct rist_flow *f)
1443 {
1444 // Now actually send all the nack IP packets for this flow (the above routing will process/group them)
1445 if (f->nacks.counter == 0)
1446 return;
1447 /* Lock order: peerlist_lock outside, f->mutex inside. */
1448 pthread_mutex_lock(&ctx->common.peerlist_lock);
1449 pthread_mutex_lock(&f->mutex);
1450 struct rist_peer *peer = NULL;
1451 uint64_t best_rtt = UINT64_MAX;
1452 uint32_t best_priority = 0;
1453 if (f->peer_lst_len == 0 || f->peer_lst == NULL)
1454 goto out;
1455 /* Route NACKs to the eligible peer with the highest recovery_priority,
1456 * tie-broken by lowest RTT. With the default priority of 0 on every
1457 * peer this reduces to the historical lowest-RTT selection. */
1458 for (size_t i = 0; i < f->peer_lst_len; i++)
1459 {
1460 struct rist_peer *check = f->peer_lst[i];
1461 if (!check->is_rtcp || check->dead)
1462 continue;
1463 uint32_t priority = check->config.recovery_priority;
1464 if (rist_nack_peer_preferred(priority, check->last_rtt,
1465 best_priority, best_rtt))
1466 {
1467 peer = check;
1468 best_priority = priority;
1469 best_rtt = check->last_rtt;
1470 }
1471 }
1472 if (peer != NULL)
1473 rist_receiver_send_nacks(peer,f->nacks.array, f->nacks.counter);
1474 else
1475 {
1476 for (size_t i = 0; i < f->peer_lst_len; i++)
1477 {
1478 struct rist_peer *check = f->peer_lst[i];
1479 uint64_t dead_since = 0;
1480 if (check->is_rtcp && check->dead_since > dead_since)
1481 {
1482 peer = check;
1483 }
1484 if (peer != NULL)
1485 rist_receiver_send_nacks(peer,f->nacks.array, f->nacks.counter);
1486 }
1487 }
1488 f->nacks.counter = 0;
1489 out:
1490 pthread_mutex_unlock(&f->mutex);
1491 pthread_mutex_unlock(&ctx->common.peerlist_lock);
1492 }
1493
1494 void receiver_nack_output(struct rist_receiver *ctx, struct rist_flow *f)
1495 {
1496
1497 if (!f->authenticated) {
1498 return;
1499 }
1500
1501 const size_t maxcounter = RIST_MAX_NACKS;
1502
1503 /* Now loop through missing queue and process items */
1504 struct rist_missing_buffer *mb = f->missing;
1505 struct rist_missing_buffer **prev = &f->missing;
1506 struct rist_missing_buffer *previous = NULL;
1507 int empty = 0;
1508 while (mb) {
1509 int remove_from_queue_reason = 0;
1510 struct rist_peer *peer = mb->peer;
1511 ssize_t idx = mb->seq& (f->receiver_queue_max -1);
1512 if (peer->config.recovery_mode == RIST_RECOVERY_MODE_DISABLED) {
1513 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1514 "Nack processing is disabled for this peer, removing seq %"PRIu32" from queue ...\n",
1515 mb->seq);
1516 remove_from_queue_reason = 10;
1517 f->stats_instant.missing--;
1518 goto nack_loop_continue;
1519 } else if (f->receiver_queue[idx]) {
1520 if (f->receiver_queue[idx]->seq == mb->seq) {
1521 pthread_mutex_lock(&ctx->common.stats_lock);
1522 // We filled in the hole already ... packet has been recovered
1523 remove_from_queue_reason = 3;
1524 if (mb->nack_count > 0)
1525 f->stats_instant.recovered++;
1526 switch(mb->nack_count) {
1527 case 0:
1528 break;
1529 case 1:
1530 f->stats_instant.recovered_0nack++;
1531 break;
1532 case 2:
1533 f->stats_instant.recovered_1nack++;
1534 break;
1535 case 3:
1536 f->stats_instant.recovered_2nack++;
1537 break;
1538 case 4:
1539 f->stats_instant.recovered_3nack++;
1540 break;
1541 default:
1542 f->stats_instant.recovered_morenack++;
1543 break;
1544 }
1545 f->stats_instant.recovered_sum += mb->nack_count;
1546 pthread_mutex_unlock(&ctx->common.stats_lock);
1547 }
1548 else {
1549 // Message with wrong seq!!!
1550 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1551 "Retry queue has the wrong seq %"PRIu32" != %"PRIu32", removing ...\n",
1552 f->receiver_queue[idx]->seq, mb->seq);
1553 remove_from_queue_reason = 4;
1554 pthread_mutex_lock(&ctx->common.stats_lock);
1555 f->stats_instant.missing--;
1556 pthread_mutex_unlock(&ctx->common.stats_lock);
1557 goto nack_loop_continue;
1558 }
1559 } else if (peer->buffer_bloat_active) {
1560 if (peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_AGGRESSIVE) {
1561 if (empty == 0) {
1562 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1563 "Retry queue is too large, %d, collapsed link (%u), flushing all nacks ...\n", f->missing_counter,
1564 f->stats_total.recovered_average/8);
1565 }
1566 remove_from_queue_reason = 5;
1567 empty = 1;
1568 } else if (peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_NORMAL) {
1569 if (mb->nack_count > 4) {
1570 if (empty == 0) {
1571 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1572 "Retry queue is too large, %d, collapsed link (%u), flushing old nacks (%u > %u) ...\n",
1573 f->missing_counter, f->stats_total.recovered_average/8, mb->nack_count, 4);
1574 }
1575 remove_from_queue_reason = 6;
1576 empty = 1;
1577 }
1578 }
1579 } else {
1580 // Packet is still missing, re-stamp the expiration time so we can re-add to queue
1581 // We reject the next retry for a number of reasons checked inside the function,
1582 // in which case the nack will never be resent and we signal a queue removal
1583 if (f->nacks.counter == (maxcounter - 1)) {
1584 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1585 "nack max counter per packet (%d) exceeded. Skipping the rest\n",
1586 maxcounter);
1587 send_nack_group(ctx, f);
1588 }
1589 else if (f->nacks.counter >= maxcounter) {
1590 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1591 "nack max counter per packet (%zu) exceeded. Something is very wrong and"
1592 " there is a strong chance memory is corrupt because we wrote past the end"
1593 "of the nacks.array max size!!!\n", f->nacks.counter );
1594 f->nacks.counter = 0;
1595 //TODO: maybe assert is more appropriate here?
1596 }
1597 remove_from_queue_reason = rist_process_nack(f, mb);
1598 }
1599 nack_loop_continue:
1600 if (remove_from_queue_reason != 0) {
1601 if (ctx->common.debug)
1602 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1603 "Removing seq %" PRIu32 " from missing, queue size is %d, retry #%u, age %"PRIu64"ms, reason %d\n",
1604 mb->seq, f->missing_counter, mb->nack_count, (timestampNTP_u64() - mb->insertion_time) / RIST_CLOCK, remove_from_queue_reason);
1605 struct rist_missing_buffer *next = mb->next;
1606 if (!next)
1607 f->missing_tail = previous;
1608 *prev = next;
1609 f->missing_counter--;
1610 free(mb);
1611 mb = next;
1612 } else {
1613 /* Move it to the end of the queue */
1614 // TODO: I think this is wrong and we loose nacks when we get here
1615 previous = mb;
1616 prev = &mb->next;
1617 mb = mb->next;
1618 }
1619 }
1620
1621 // Empty all peer nack queues, i.e. send them
1622 send_nack_group(ctx, f);
1623
1624 }
1625
1626 static int rist_set_manual_sockdata(struct rist_peer *peer, const struct rist_peer_config *config)
1627 {
1628 peer->address_family = (uint16_t)config->address_family;//TODO: should it not just be a uint16_t then?
1629 peer->listening = !config->initiate_conn;
1630 const char *hostname = config->address;
1631 int ret;
1632 if ((!hostname || !*hostname) && peer->listening) {
1633 if (peer->address_family == AF_INET) {
1634 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "No hostname specified: listening to 0.0.0.0\n");
1635 peer->address_len = sizeof(struct sockaddr_in);
1636 ((struct sockaddr_in *)&peer->u.address)->sin_family = AF_INET;
1637 ((struct sockaddr_in *)&peer->u.address)->sin_addr.s_addr = INADDR_ANY;
1638 } else {
1639 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "No hostname specified: listening to [::0]\n");
1640 peer->address_len = sizeof(struct sockaddr_in6);
1641 ((struct sockaddr_in6 *)&peer->u.address)->sin6_family = AF_INET6;
1642 ((struct sockaddr_in6 *)&peer->u.address)->sin6_addr = in6addr_any;
1643 }
1644 } else {
1645 ret = udpsocket_resolve_host(hostname, config->physical_port, &peer->u.address);
1646 if (ret != 0) {
1647 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Error trying to resolve hostname %s\n", hostname);
1648 goto err;
1649 }
1650 peer->address_family = ((struct sockaddr_in *)&peer->u.address)->sin_family;
1651 if (peer->address_family == AF_INET)
1652 peer->address_len = sizeof(struct sockaddr_in);
1653 else
1654 peer->address_len = sizeof(struct sockaddr_in6);
1655 }
1656 if (peer->listening)
1657 peer->local_port = config->physical_port;
1658 else
1659 peer->remote_port = config->physical_port;
1660
1661 return 0;
1662
1663 err:
1664 peer->address_family = AF_LOCAL;
1665 peer->address_len = 0;
1666 return -1;
1667 }
1668
1669
1670
1671 struct rist_peer *_librist_peer_create_common(struct rist_common_ctx *cctx, struct rist_receiver *rctx, struct rist_sender *sctx, const struct rist_peer_config *config)
1672 {
1673 int key_size = config->key_size;
1674 if (strlen(config->secret) && !key_size) {
1675 rist_log_priv(cctx, RIST_LOG_NOTICE, "PSK Set but key size not explicitly configured, defaulting to AES256");
1676 key_size = 256;
1677 }
1678 if (key_size) {
1679 if (key_size != 128 && key_size != 192 && key_size != 256) {
1680 rist_log_priv(cctx, RIST_LOG_ERROR, "Invalid encryption key length: %d\n", key_size);
1681 return NULL;
1682 }
1683 if (!strlen(config->secret)) {
1684
1685 rist_log_priv(cctx, RIST_LOG_ERROR, "Invalid secret passphrase\n");
1686 return NULL;
1687 }
1688 rist_log_priv(cctx, RIST_LOG_INFO, "Using %d bits secret key\n", key_size);
1689 }
1690 else {
1691 rist_log_priv(cctx, RIST_LOG_INFO, "Encryption is disabled for this peer\n");
1692 }
1693
1694 /* Initialize peer */
1695 struct rist_peer *p = peer_initialize(config->address, sctx, rctx);
1696 if (!p) {
1697 return NULL;
1698 }
1699
1700 strncpy(&p->miface[0], config->miface, RIST_MAX_STRING_SHORT);
1701 p->miface[RIST_MAX_STRING_SHORT - 1] = '\0';
1702 strncpy(&p->cname[0], config->cname, RIST_MAX_STRING_SHORT);
1703 p->cname[RIST_MAX_STRING_SHORT - 1] = '\0';
1704 if (config->address_family && rist_set_manual_sockdata(p, config)) {
1705 free(p);
1706 return NULL;
1707 }
1708
1709 _librist_crypto_psk_rist_key_init(&p->key_tx, key_size, config->key_rotation, config->secret, false);
1710 _librist_crypto_psk_rist_key_init(&p->key_tx_odd, key_size, config->key_rotation, config->secret, true);
1711 _librist_crypto_psk_rist_key_clone(&p->key_tx, &p->key_rx);
1712 _librist_crypto_psk_rist_key_clone(&p->key_tx_odd, &p->key_rx_odd);
1713
1714 if (config->keepalive_interval > 0) {
1715 p->rtcp_keepalive_interval = config->keepalive_interval * RIST_CLOCK;
1716 }
1717
1718 /* Unset session_timeout means the documented default; floored at a few
1719 * RTCP intervals so a peer is never declared dead before its heartbeat
1720 * could have arrived. */
1721 uint64_t min_liveness = RIST_LIVENESS_MIN_PINGS * p->rtcp_keepalive_interval;
1722 if (config->session_timeout > 0)
1723 p->session_timeout = (uint64_t)config->session_timeout * RIST_CLOCK;
1724 else
1725 p->session_timeout = (uint64_t)RIST_DEFAULT_SESSION_TIMEOUT * RIST_CLOCK;
1726 if (p->session_timeout < min_liveness) {
1727 rist_log_priv(cctx, RIST_LOG_WARN, "The configured (%"PRIu64" ms) peer session timeout is below %"PRIu64" ms (%d RTCP intervals), using the floor instead\n",
1728 p->session_timeout / RIST_CLOCK, min_liveness / RIST_CLOCK, RIST_LIVENESS_MIN_PINGS);
1729 p->session_timeout = min_liveness;
1730 }
1731
1732 if (cctx->profile > RIST_PROFILE_SIMPLE) {
1733 if (_librist_network_get_macaddr(p->mac_addr) < 0)
1734 rist_log_priv(cctx, RIST_LOG_WARN, "Couldn't get a mac address for peer, keepalive will not contain a mac address\n");
1735 }
1736 /* Initialize socket */
1737 rist_create_socket(p);
1738 if (p->sd < 0) {
1739 rist_log_priv(cctx, RIST_LOG_ERROR, "Could not create socket\n");
1740 free(p);
1741 return NULL;
1742 }
1743 store_peer_settings(config, p);
1744 return p;
1745 }
1746
1747 struct rist_peer *rist_receiver_peer_insert_local(struct rist_receiver *ctx,
1748 const struct rist_peer_config *config)
1749 {
1750 struct rist_peer *p = _librist_peer_create_common(&ctx->common, ctx, NULL, config);
1751 if (!p)
1752 return NULL;
1753 if (config->virt_dst_port != 0) {
1754 p->remote_port = config->virt_dst_port + 1;
1755 }
1756
1757 p->adv_peer_id = ++ctx->common.peer_counter;
1758 return p;
1759 }
1760
1761 /* PEERS are created at startup. The default state is RIST_PEER_STATE_IDLE
1762 * This function will initiate the connection to the peer if a peer address is available.
1763 * If no address is configured for the endpoint, the peer is put in wait mode.
1764 */
1765 void rist_fsm_init_comm(struct rist_peer *peer)
1766 {
1767
1768 peer->authenticated = false;
1769
1770 if (!peer->receiver_mode) {
1771 if (peer->listening) {
1772 /* sender mode listening/waiting for receiver */
1773 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1774 "Initialized Sender Peer, listening mode ...\n");
1775 } else {
1776 /* sender mode connecting to receiver */
1777 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1778 "Initialized Sender Peer, connecting to receiver ...\n");
1779 }
1780 } else {
1781 if (peer->listening) {
1782 /* receiver mode listening/waiting for sender */
1783 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1784 "Initialized Receiver Peer, listening mode ...\n");
1785 } else {
1786 /* receiver mode connecting to sender */
1787 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1788 "Initialized Receiver Peer, connecting to sender ...\n");
1789 }
1790 }
1791 peer->authenticated = false;
1792 rist_print_inet_info("Active ", peer);
1793
1794 /* Start the timer that reads data from this peer */
1795 if (!peer->event_recv) {
1796 struct evsocket_ctx *evctx = get_cctx(peer)->evctx;
1797 peer->event_recv = evsocket_addevent(evctx, peer->sd, EVSOCKET_EV_READ,
1798 rist_peer_recv_wrap, rist_peer_sockerr, peer);
1799 }
1800
1801 /* Enable RTCP timer and jump start it */
1802 if (!peer->listening && peer->is_rtcp) {
1803 if (!peer->send_keepalive) {
1804 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Enabling keepalive for peer %"PRIu32"\n", peer->adv_peer_id);
1805 peer->send_keepalive = true;
1806 }
1807 if (get_cctx(peer)->profile > RIST_PROFILE_SIMPLE && !peer->eap_ctx) {
1808 //Try version 2 first
1809 _librist_proto_gre_send_keepalive(peer, 2);
1810 _librist_proto_gre_send_keepalive(peer, 2);
1811 _librist_proto_gre_send_keepalive(peer, 2);
1812 _librist_proto_gre_send_keepalive(peer, 1);
1813 _librist_proto_gre_send_keepalive(peer, 1);
1814 _librist_proto_gre_send_keepalive(peer, 1);
1815 if (peer->sender_ctx != NULL) {
1816 _librist_proto_gre_send_buffer_negotiation(peer, peer->sender_ctx->sender_recover_min_time, 0);
1817 _librist_proto_gre_send_buffer_negotiation(peer, peer->sender_ctx->sender_recover_min_time, 0);
1818 _librist_proto_gre_send_buffer_negotiation(peer, peer->sender_ctx->sender_recover_min_time, 0);
1819 }
1820 }
1821 /* call it the first time manually to speed up the handshake */
1822 rist_peer_rtcp(NULL, peer);
1823 /* send 3 echo requests to jumpstart accurate RTT calculation */
1824 rist_request_echo(peer);
1825 rist_request_echo(peer);
1826 rist_request_echo(peer);
1827 }
1828 }
1829
1830 void rist_peer_authenticate(struct rist_peer *peer)
1831 {
1832 peer->authenticated = true;
1833 if (peer->peer_data)
1834 peer->peer_data->authenticated = true;
1835
1836 /* Re-auth means any prior caller rebind converged; clear the backoff so
1837 * the next outage retries promptly instead of from an ever-growing gap. */
1838 peer->rebind_attempts = 0;
1839 peer->last_rebind_time = 0;
1840 if (peer->peer_data) {
1841 peer->peer_data->rebind_attempts = 0;
1842 peer->peer_data->last_rebind_time = 0;
1843 }
1844 if (peer->peer_rtcp) {
1845 peer->peer_rtcp->rebind_attempts = 0;
1846 peer->peer_rtcp->last_rebind_time = 0;
1847 }
1848
1849 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1850 "Successfully Authenticated peer %"PRIu32"\n", peer->adv_peer_id);
1851 }
1852
1853 void rist_calculate_bitrate(size_t len, struct rist_bandwidth_estimation *bw)
1854 {
1855 struct timeval tv;
1856 gettimeofday(&tv, NULL);
1857 uint64_t now = (uint64_t)tv.tv_sec * 1000000;
1858 now += tv.tv_usec;
1859 uint64_t time = now - bw->last_bitrate_calctime;
1860 uint64_t time_fast = now - bw->last_bitrate_calctime_fast;
1861
1862 if (!bw->last_bitrate_calctime) {
1863 bw->last_bitrate_calctime = now;
1864 bw->last_bitrate_calctime_fast = now;
1865 bw->eight_times_bitrate = 0;
1866 bw->eight_times_bitrate_fast = 0;
1867 bw->bytes = 0;
1868 bw->bytes_fast = 0;
1869 bw->bitrate = 0;
1870 bw->bitrate_fast = 0;
1871 return;
1872 }
1873
1874 if (time_fast < 100000 /* 100 ms */) {
1875 bw->bytes_fast += len;
1876 }
1877 else {
1878 bw->bytes_fast += len;
1879 bw->bitrate_fast = (size_t)((8 * bw->bytes_fast * 1000000) / time_fast);
1880 bw->eight_times_bitrate_fast += bw->bitrate_fast - bw->eight_times_bitrate_fast / 8;
1881 bw->last_bitrate_calctime_fast = now;
1882 bw->bytes_fast = 0;
1883 }
1884
1885 if (time < 1000000 /* 1 second */) {
1886 bw->bytes += len;
1887 return;
1888 }
1889 else {
1890 bw->bytes += len;
1891 bw->bitrate = (size_t)((8 * bw->bytes * 1000000) / time);
1892 bw->eight_times_bitrate += bw->bitrate - bw->eight_times_bitrate / 8;
1893 bw->last_bitrate_calctime = now;
1894 bw->bytes = 0;
1895 }
1896 }
1897
1898 /* Recompute bw->bitrate using zero new bytes so the value decays to
1899 * zero when the stats tick fires but no packets have arrived on this
1900 * counter since the last tick. Mirrors what rist_calculate_bitrate(0,
1901 * ...) does for peer-side counters, deliberately skipping the per-flow
1902 * inter-packet-spacing bookkeeping that lives in
1903 * rist_calculate_flow_bitrate(). */
1904 void rist_refresh_flow_bitrate(struct rist_bandwidth_estimation *bw)
1905 {
1906 if (!bw->last_bitrate_calctime)
1907 return;
1908
1909 struct timeval tv;
1910 gettimeofday(&tv, NULL);
1911 uint64_t now = (uint64_t)tv.tv_sec * 1000000;
1912 now += tv.tv_usec;
1913
1914 uint64_t time_fast = now - bw->last_bitrate_calctime_fast;
1915 if (time_fast >= 100000 /* 100 ms */) {
1916 bw->bitrate_fast = (size_t)((8 * bw->bytes_fast * 1000000) / time_fast);
1917 bw->eight_times_bitrate_fast += bw->bitrate_fast - bw->eight_times_bitrate_fast / 8;
1918 bw->last_bitrate_calctime_fast = now;
1919 bw->bytes_fast = 0;
1920 }
1921
1922 uint64_t time = now - bw->last_bitrate_calctime;
1923 if (time >= 1000000 /* 1 second */) {
1924 bw->bitrate = (size_t)((8 * bw->bytes * 1000000) / time);
1925 bw->eight_times_bitrate += bw->bitrate - bw->eight_times_bitrate / 8;
1926 bw->last_bitrate_calctime = now;
1927 bw->bytes = 0;
1928 }
1929 }
1930
1931 static void rist_calculate_flow_bitrate(struct rist_flow *flow, size_t len, struct rist_bandwidth_estimation *bw)
1932 {
1933 struct timeval tv;
1934 gettimeofday(&tv, NULL);
1935 uint64_t now = (uint64_t)tv.tv_sec * 1000000;
1936 now += tv.tv_usec;
1937 uint64_t time = now - bw->last_bitrate_calctime;
1938 uint64_t time_fast = now - bw->last_bitrate_calctime_fast;
1939
1940 if (!bw->last_bitrate_calctime) {
1941 bw->last_bitrate_calctime = now;
1942 bw->eight_times_bitrate = 0;
1943 bw->bitrate = 0;
1944 bw->bytes = 0;
1945 bw->eight_times_bitrate_fast = 0;
1946 bw->bitrate_fast = 0;
1947 bw->bytes_fast = 0;
1948 return;
1949 }
1950
1951 if (flow->last_ipstats_time == 0ULL) {
1952 // Initial values
1953 flow->stats_instant.cur_ips = 0ULL;
1954 flow->stats_instant.min_ips = 0xFFFFFFFFFFFFFFFFULL;
1955 flow->stats_instant.max_ips = 0ULL;
1956 flow->stats_instant.avg_count = 0UL;
1957 } else {
1958 flow->stats_instant.cur_ips = now - flow->last_ipstats_time;
1959 /* Set new min */
1960 if (flow->stats_instant.cur_ips < flow->stats_instant.min_ips)
1961 flow->stats_instant.min_ips = flow->stats_instant.cur_ips;
1962 /* Set new max */
1963 if (flow->stats_instant.cur_ips > flow->stats_instant.max_ips)
1964 flow->stats_instant.max_ips = flow->stats_instant.cur_ips;
1965
1966 /* Avg calculation */
1967 flow->stats_instant.total_ips += flow->stats_instant.cur_ips;
1968 flow->stats_instant.avg_count++;
1969 }
1970 flow->last_ipstats_time = now;
1971
1972
1973 if (time_fast < 100000 /* 100 ms */) {
1974 bw->bytes_fast += len;
1975 }
1976 else {
1977 bw->bitrate_fast = (size_t)((8 * bw->bytes_fast * 1000000) / time_fast);
1978 bw->eight_times_bitrate_fast += bw->bitrate_fast - bw->eight_times_bitrate_fast / 8;
1979 bw->last_bitrate_calctime_fast = now;
1980 bw->bytes_fast = 0;
1981 }
1982
1983 if (time < 1000000 /* 1 second */) {
1984 bw->bytes += len;
1985 return;
1986 }
1987 else {
1988 bw->bitrate = (size_t)((8 * bw->bytes * 1000000) / time);
1989 bw->eight_times_bitrate += bw->bitrate - bw->eight_times_bitrate / 8;
1990 bw->last_bitrate_calctime = now;
1991 bw->bytes = 0;
1992 }
1993 }
1994
1995 static void rist_sender_recv_nack(struct rist_peer *peer,
1996 uint32_t flow_id, uint16_t src_port, uint16_t dst_port, const uint8_t *payload,
1997 size_t payload_len, uint32_t nack_seq_msb)
1998 {
1999 RIST_MARK_UNUSED(flow_id);
2000 RIST_MARK_UNUSED(src_port);
2001 RIST_MARK_UNUSED(dst_port);
2002
2003 assert(payload_len >= sizeof(struct rist_rtcp_hdr));
2004
2005 if (peer->receiver_mode) {
2006 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
2007 "Received nack packet on receiver, ignoring ...\n");
2008 return;
2009 } else if (!peer->authenticated) {
2010 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
2011 "Received nack packet but handshake is still pending, ignoring ...\n");
2012 return;
2013 }
2014 assert(peer->sender_ctx != NULL);
2015
2016 struct rist_rtcp_hdr *rtcp = (struct rist_rtcp_hdr *) payload;
2017 uint32_t i,j;
2018
2019 if ((rtcp->flags & 0xc0) != 0x80) {
2020 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Malformed nack packet flags=%d.\n", rtcp->flags);
2021 return;
2022 }
2023
2024 if (rtcp->ptype == PTYPE_NACK_CUSTOM) {
2025 if (payload_len < sizeof(struct rist_rtcp_nack_range))
2026 return;
2027 struct rist_rtcp_nack_range *rtcp_nack = (struct rist_rtcp_nack_range *) payload;
2028 if (memcmp(rtcp_nack->name, "RIST", 4) != 0) {
2029 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Non-Rist nack packet (%.4s).\n", rtcp_nack->name);
2030 return; /* Ignore app-type not RIST */
2031 }
2032 uint16_t raw_len = ntohs(rtcp->len);
2033 if (raw_len < 2)
2034 return;
2035 uint16_t nrecords = raw_len - 2;
2036 size_t needed = sizeof(struct rist_rtcp_nack_range) + (size_t)nrecords * sizeof(struct rist_rtp_nack_record);
2037 if (needed > payload_len)
2038 return;
2039 //rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Nack (RbRR), %d record(s)\n", nrecords);
2040 /* Cap the per-record range and the per-packet total: a ~10 KB NACK
2041 * otherwise drives ~1.6e8 retry-queue operations from one packet.
2042 * 256 covers any honest loss burst; 4096/packet ~16 full records. */
2043 size_t enqueued = 0;
2044 for (i = 0; i < nrecords; i++) {
2045 uint16_t missing;
2046 uint16_t additional;
2047 struct rist_rtp_nack_record *nr = (struct rist_rtp_nack_record *)(payload + sizeof(struct rist_rtcp_nack_range) + i * sizeof(struct rist_rtp_nack_record));
2048 missing = ntohs(nr->start);
2049 additional = ntohs(nr->extra);
2050 if (additional > 256)
2051 additional = 256;
2052 rist_retry_enqueue(peer->sender_ctx, nack_seq_msb + (uint32_t)missing, peer);
2053 if (++enqueued >= 4096)
2054 return;
2055 //rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Record %"PRIu32": base packet: %"PRIu32" range len: %d\n", i, nack_seq_msb + missing, additional);
2056 for (j = 0; j < additional; j++) {
2057 rist_retry_enqueue(peer->sender_ctx, nack_seq_msb + (uint32_t)missing + j + 1, peer);
2058 if (++enqueued >= 4096)
2059 return;
2060 }
2061 }
2062 } else if (rtcp->ptype == PTYPE_NACK_BITMASK) {
2063 struct rist_rtcp_nack_bitmask *rtcp_nack = (struct rist_rtcp_nack_bitmask *) payload;
2064 (void)rtcp_nack;
2065 uint16_t raw_len = ntohs(rtcp->len);
2066 if (raw_len < 2)
2067 return;
2068 uint16_t nrecords = raw_len - 2;
2069 size_t needed = sizeof(struct rist_rtcp_nack_bitmask) + (size_t)nrecords * sizeof(struct rist_rtp_nack_record);
2070 if (needed > payload_len)
2071 return;
2072 //rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Nack (BbRR), %d record(s)\n", nrecords);
2073 for (i = 0; i < nrecords; i++) {
2074 uint16_t missing;
2075 uint16_t bitmask;
2076 struct rist_rtp_nack_record *nr = (struct rist_rtp_nack_record *)(payload + sizeof(struct rist_rtcp_nack_bitmask) + i * sizeof(struct rist_rtp_nack_record));
2077 missing = ntohs(nr->start);
2078 bitmask = ntohs(nr->extra);
2079 rist_retry_enqueue(peer->sender_ctx, nack_seq_msb + (uint32_t)missing, peer);
2080 //rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Record %"PRIu32": base packet: %"PRIu32" bitmask: %04x\n", i, nack_seq_msb + missing, bitmask);
2081 for (j = 0; j < 16; j++) {
2082 if ((bitmask & (1 << j)) == (1 << j))
2083 rist_retry_enqueue(peer->sender_ctx, nack_seq_msb + missing + j + 1, peer);
2084 }
2085 }
2086 } else {
2087 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Unsupported Type %d\n", rtcp->ptype);
2088 }
2089
2090 }
2091
2092 static bool address_compare(struct sockaddr* addr1, struct sockaddr* addr2) {
2093 if (addr1->sa_family != addr2->sa_family)
2094 return false;
2095 if (addr1->sa_family == AF_INET) {
2096 struct sockaddr_in *sa, *sb;
2097 sa = (struct sockaddr_in *)addr1;
2098 sb = (struct sockaddr_in *)addr2;
2099 return !(sa->sin_addr.s_addr - sb->sin_addr.s_addr);
2100 } else if (addr1->sa_family == AF_INET6) {
2101 struct sockaddr_in6 *sa, *sb;
2102 sa = (struct sockaddr_in6 *)addr1;
2103 sb = (struct sockaddr_in6 *)addr2;
2104 return !(memcmp(&sa->sin6_addr, &sb->sin6_addr, sizeof(sa->sin6_addr)));
2105 }
2106 return false;
2107 }
2108
2109 static bool rist_receiver_data_authenticate(struct rist_peer *peer,uint64_t packet_recv_time, uint32_t flow_id)
2110 {
2111 struct rist_receiver *ctx = peer->receiver_ctx;
2112
2113 if (ctx->common.profile == RIST_PROFILE_SIMPLE && !peer->authenticated)
2114 {
2115 //assert(0);
2116 if (peer->parent->peer_rtcp && peer->parent->peer_rtcp->authenticated) {
2117 peer->flow = peer->parent->peer_rtcp->flow;
2118 /* find correct rtcp */
2119 peer->peer_rtcp = NULL;
2120 struct rist_peer *tmp = peer->parent->peer_rtcp->child;
2121 uint16_t rtcp_port = peer->local_port+1;
2122 while (tmp) {
2123 if (tmp->is_rtcp) {
2124 if (tmp->local_port == rtcp_port && peer->adv_flow_id == tmp->adv_flow_id && address_compare(&peer->u.address, &tmp->u.address)) {
2125 if (tmp->dead)
2126 {
2127 tmp = tmp->sibling_next;
2128 continue;
2129 }
2130 peer->peer_rtcp = tmp;
2131 tmp->peer_data = peer;
2132 break;
2133 }
2134 }
2135 tmp = tmp->sibling_next;
2136 }
2137 if (!peer->peer_rtcp) {
2138 tmp = peer->parent->peer_rtcp->child;
2139 while (tmp) {
2140 if (tmp->is_rtcp) {
2141 if (tmp->local_port == rtcp_port && address_compare(&peer->u.address, &tmp->u.address)) {
2142 if (tmp->dead)
2143 {
2144 tmp = tmp->sibling_next;
2145 continue;
2146 }
2147 peer->peer_rtcp = tmp;
2148 tmp->peer_data = peer;
2149 break;
2150 }
2151 }
2152 tmp = tmp->sibling_next;
2153 }
2154 }
2155 peer->adv_flow_id = flow_id; // store the original ssrc here
2156 rist_peer_authenticate(peer);
2157 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2158 "Authenticated RTP peer %d and ssrc %"PRIu32" for connection with flowid %"PRIu32"\n",
2159 peer->adv_peer_id, peer->adv_flow_id, peer->flow->flow_id);
2160 } else {
2161 if (packet_recv_time > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
2162 rist_log_priv(&ctx->common, RIST_LOG_WARN,
2163 "Received data packet (%"PRIu32") but handshake is still pending (waiting for an RTCP packet with SDES on it), ignoring ...\n",
2164 flow_id);
2165 peer->log_repeat_timer = packet_recv_time;
2166 }
2167 return false;
2168 }
2169 }
2170 else if (ctx->common.profile > RIST_PROFILE_SIMPLE) {
2171 if (!peer->authenticated) {
2172 // rist_peer_authenticate is done during rtcp authentication (same peer)
2173 rist_log_priv(&ctx->common, RIST_LOG_WARN,
2174 "Received data packet (%"PRIu32") but handshake is still pending (waiting for an RTCP packet with SDES on it), ignoring ...\n",
2175 flow_id);
2176 return false;
2177 } else if (!peer->peer_rtcp) {
2178 peer->peer_rtcp = peer;
2179 peer->adv_flow_id = flow_id; // store the original ssrc here
2180 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2181 "Authenticated RTP peer %d and ssrc %"PRIu32" for connection with flowid %"PRIu32"\n",
2182 peer->adv_peer_id, peer->adv_flow_id, peer->peer_rtcp->adv_flow_id);
2183 }
2184 }
2185
2186 if (!peer->flow) {
2187 rist_log_priv(&ctx->common, RIST_LOG_WARN,
2188 "Received data packet but this peer (%d) is not associated with a flow, ignoring ...\n",
2189 peer->adv_peer_id);
2190 return false;
2191 } else if (!peer->flow->authenticated) {
2192 rist_log_priv(&ctx->common, RIST_LOG_WARN,
2193 "Flow %"PRIu32" has not yet been authenticated by an RTCP peer, %"PRIu32"!\n", flow_id);
2194 return false;
2195 }
2196 if (peer->parent && ctx->common.profile == RIST_PROFILE_SIMPLE)
2197 peer->parent->authenticated = true;
2198 return true;
2199 }
2200
2201 static bool rist_receiver_rtcp_authenticate(struct rist_peer *peer, uint32_t seq,
2202 uint32_t flow_id)
2203 {
2204 RIST_MARK_UNUSED(seq);
2205 assert(peer->receiver_ctx != NULL);
2206 struct rist_receiver *ctx = peer->receiver_ctx;
2207
2208 if (!strlen(peer->receiver_name)) {
2209 snprintf(peer->receiver_name, 128, "empty-sdes-name peer id#%i", peer->adv_peer_id);
2210 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Peer has empty cname in SDES packet, generating default name");
2211 }
2212
2213 // Check to see if this peer's flowid changed
2214 // (sender was restarted and we are in callback mode or sender happened to reuse the same port)
2215 if (peer->flow && (flow_id != peer->flow->flow_id)) {
2216 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Updating peer's flowid %"PRIu32"->%"PRIu32" (%zu)\n", peer->flow->flow_id, flow_id, peer->flow->peer_lst_len);
2217 if (peer->flow->peer_lst_len > 1) {
2218 remove_peer_from_flow(peer);
2219 }
2220 else {
2221 // Delete the flow and all of its resources
2222 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2223 "Old flow (%"PRIu32") has no peers left, deleting ...\n", peer->flow->flow_id);
2224 rist_delete_flow(ctx, peer->flow);
2225 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2226 "Old flow deletion complete\n");
2227 }
2228 // Reset the peer parameters
2229 peer->authenticated = false;
2230 peer->flow = NULL;
2231 }
2232
2233 if (!peer->authenticated) {
2234
2235 // the peer could already be part of a flow and it came back after timing out
2236 if (!peer->flow) {
2237 if (rist_receiver_associate_flow(peer, flow_id) != 1) {
2238 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Could not create/associate peer to flow.\n");
2239 return false;
2240 }
2241 if (ctx->common.profile == RIST_PROFILE_SIMPLE && peer->parent->peer_data->authenticated)
2242 {
2243 /* find correct data */
2244 struct rist_peer *tmp = peer->parent->peer_data->child;
2245 peer->is_data = false;
2246 peer->peer_data = NULL;
2247 peer->is_rtcp = true;
2248 uint16_t data_port = peer->local_port -1;
2249 while (tmp) {
2250 if (tmp->is_data) {
2251 if (tmp->local_port == data_port && peer->adv_flow_id == tmp->adv_flow_id && address_compare(&peer->u.address, &tmp->u.address)) {
2252 if (tmp->dead)
2253 {
2254 tmp = tmp->sibling_next;
2255 continue;
2256 }
2257 peer->peer_data = tmp;
2258 tmp->peer_rtcp = peer;
2259 break;
2260 }
2261 }
2262 tmp = tmp->sibling_next;
2263 }
2264 if (!peer->peer_data) {
2265 tmp = peer->parent->peer_data->child;
2266 while (tmp) {
2267 if (tmp->is_data) {
2268 if (tmp->local_port == data_port && address_compare(&peer->u.address, &tmp->u.address)) {
2269 if (tmp->dead)
2270 {
2271 tmp = tmp->sibling_next;
2272 continue;
2273 }
2274 peer->peer_data = tmp;
2275 tmp->peer_rtcp = peer;
2276 break;
2277 }
2278 }
2279 tmp = tmp->sibling_next;
2280 }
2281 }
2282 //randomly associate with first data peer without rtcp peer (ignores IP matching requirement)
2283 if (!peer->peer_data) {
2284 tmp = peer->parent->peer_data->child;
2285 while (tmp) {
2286 if (tmp->is_data) {
2287 if (tmp->local_port == data_port && tmp->peer_rtcp == NULL) {
2288 peer->peer_data = tmp;
2289 tmp->peer_rtcp = peer;
2290 break;
2291 }
2292 }
2293 tmp = tmp->sibling_next;
2294 }
2295 }
2296 peer->authenticated = true;
2297 return true;
2298 }
2299 }
2300
2301 if (peer->flow) {
2302 // We do multiple ifs to make these checks stateless
2303 pthread_mutex_lock(&peer->flow->mutex);
2304 if (!peer->flow->receiver_thread_running) {
2305 // Make sure this data out thread is created only once per flow
2306 if (rist_thread_create(&ctx->common, &peer->flow->receiver_thread, NULL, receiver_pthread_dataout, (void *)peer->flow) != 0) {
2307 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
2308 "Could not created receiver data output thread.\n");
2309 return false;
2310 }
2311 peer->flow->receiver_thread_running = true;
2312 }
2313 pthread_mutex_unlock(&peer->flow->mutex);
2314 rist_peer_authenticate(peer);
2315 peer->flow->authenticated = true;
2316 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2317 "Authenticated RTCP peer %d and flow %"PRIu32" for connection with cname: %s\n",
2318 peer->adv_peer_id, peer->adv_flow_id, peer->receiver_name);
2319 if (ctx->common.profile == RIST_PROFILE_SIMPLE)
2320 {
2321 peer->parent->authenticated = true;
2322 if (peer->parent->flow == NULL) {
2323 peer->parent->flow = peer->flow;
2324 peer->parent->flow->authenticated = true;
2325 }
2326 }
2327 }
2328 }
2329
2330 // The flow is added after we completed authentication
2331 if (peer->flow) {
2332 return true;
2333 } else {
2334 return false;
2335 }
2336 }
2337
2338 static void rist_receiver_recv_data(struct rist_peer *peer, uint32_t seq, uint32_t flow_id,
2339 uint64_t source_time, uint64_t packet_recv_time, struct rist_buffer *payload, uint8_t retry, uint8_t payload_type, size_t ingest_size, size_t ts_null_bytes, bool pkt_short_seq)
2340 {
2341 assert(peer->receiver_ctx != NULL);
2342 struct rist_receiver *ctx = peer->receiver_ctx;
2343
2344 if (!rist_receiver_data_authenticate(peer, packet_recv_time, flow_id)) {
2345 // Error logging happens inside the function
2346 return;
2347 }
2348
2349 /* Advanced contexts default to 32-bit framing but interoperate with a
2350 * Main-framed (16-bit) source: track the actual wire framing of the data
2351 * so the seq/wrap math matches. Simple/Main are always 16-bit.
2352 *
2353 * TR-06-3 Section 9 lets a flow switch framing mid-stream (Main->Advanced
2354 * upgrade once the peer advertises I=1, or a legacy Main-only source that
2355 * never upgrades). The two framings carry different seq widths AND
2356 * timestamp encodings, so mixing them in one flow corrupts the timing
2357 * baseline. Treat a framing change like a flow-id change: drop the old
2358 * baseline so the next enqueue re-derives time_offset and the seq->idx
2359 * mapping from the new framing instead of blending the two. */
2360 if (ctx->common.profile >= RIST_PROFILE_ADVANCED && peer->flow &&
2361 peer->flow->short_seq != pkt_short_seq) {
2362 rist_log_priv(&ctx->common, RIST_LOG_INFO,
2363 "Flow %u wire framing changed to %s sequence numbers, "
2364 "resetting flow timing baseline\n",
2365 peer->flow->flow_id, pkt_short_seq ? "16-bit" : "32-bit");
2366 peer->flow->short_seq = pkt_short_seq;
2367 peer->flow->receiver_queue_has_items = false;
2368 }
2369
2370 //rist_log_priv(&ctx->common, RIST_LOG_ERROR,
2371 // "rist_recv_data, seq %"PRIu32", retry=%d\n", seq, retry);
2372
2373 // Just some debug output
2374 // if ((seq - peer->flow->last_seq_output) != 1)
2375 // rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Received seq %"PRIu32" and last %"PRIu32"\n\n\n", seq, peer->flow->last_seq_output);
2376
2377 /**************** WIP *****************/
2378 /* * * * * * * * * * * * * * * * * * * */
2379 /** Heuristics for receiver * * * * * */
2380 /* * * * * * * * * * * * * * * * * * * */
2381 /**************** WIP *****************/
2382 peer->stats_receiver_instant.received++;
2383 peer->stats_receiver_instant.received_bytes += (uint64_t)ingest_size;
2384
2385 uint64_t rtt;
2386 rtt = peer->eight_times_rtt / 8;
2387 if (rtt < peer->config.recovery_rtt_min) {
2388 rtt = peer->config.recovery_rtt_min;
2389 }
2390 else if (rtt > peer->config.recovery_rtt_max) {
2391 rtt = peer->config.recovery_rtt_max;
2392 }
2393 // Optimal dynamic time for first retry (reorder buffer) is rtt/2
2394 rtt = rtt / 2;
2395 if (rtt < peer->config.recovery_reorder_buffer)
2396 {
2397 rtt = peer->config.recovery_reorder_buffer;
2398 }
2399
2400 if (peer->peer_rtcp != NULL &&
2401 peer->peer_ssrc != peer->peer_rtcp->peer_ssrc &&
2402 peer->flow->flow_id_actual != flow_id)
2403 {
2404 rist_log_priv(&ctx->common, RIST_LOG_NOTICE,
2405 "Detected flow id change, old flow id: %u new id: %u, "
2406 "resetting state\n",
2407 peer->flow->flow_id_actual, flow_id);
2408 peer->flow->receiver_queue_has_items = false;
2409 peer->flow->flow_id_actual = flow_id;
2410 }
2411
2412 // Wake up output thread when data comes in
2413 if (pthread_cond_signal(&(peer->flow->condition)))
2414 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Call to pthread_cond_signal failed.\n");
2415 if (!receiver_enqueue(peer, source_time, packet_recv_time, payload->data, payload->size, seq, rtt, retry, payload->src_port, payload->dst_port, payload_type)) {
2416 pthread_mutex_lock(&ctx->common.stats_lock);
2417 // bitrate only if not a dupe or other failures
2418 if (retry)
2419 rist_calculate_flow_bitrate(peer->flow, ingest_size, &peer->flow->bw_retries);
2420 else
2421 rist_calculate_flow_bitrate(peer->flow, ingest_size, &peer->flow->bw);
2422 rist_calculate_flow_bitrate(peer->flow, ts_null_bytes, &peer->flow->bw_tsnull);
2423 pthread_mutex_unlock(&ctx->common.stats_lock);
2424 }
2425 else
2426 {
2427 pthread_mutex_lock(&ctx->common.stats_lock);
2428 if (retry)
2429 rist_calculate_flow_bitrate(peer->flow, ingest_size, &peer->flow->bw_retries);
2430 else
2431 rist_calculate_flow_bitrate(peer->flow, ingest_size, &peer->flow->bw_rejected);
2432 pthread_mutex_unlock(&ctx->common.stats_lock);
2433 }
2434 }
2435
2436 static void rist_recv_oob_data(struct rist_peer *peer, struct rist_buffer *payload)
2437 {
2438 // TODO: if the calling app locks the thread for long, the protocol management thread will suffer
2439 // either use a new thread with a fifo or write warning on documentation
2440 struct rist_common_ctx *ctx = get_cctx(peer);
2441 if (!ctx->oob_data_enabled)
2442 return;
2443
2444 if (ctx->oob_current_peer == NULL || ctx->oob_current_peer->dead)
2445 ctx->oob_current_peer = peer;
2446
2447 if (ctx->oob_data_callback)
2448 {
2449 struct rist_oob_block oob_block;
2450 oob_block.peer = peer;
2451 oob_block.payload = payload->data;
2452 oob_block.payload_len = payload->size;
2453 oob_block.ts_ntp = payload->source_time;
2454 ctx->oob_data_callback(ctx->oob_data_callback_argument, &oob_block);
2455 return;
2456 }
2457
2458 /* No callback installed: stash the packet in the receive fifo so the
2459 * application can pull it via rist_oob_read(). */
2460 pthread_rwlock_wrlock(&ctx->oob_queue_lock);
2461 if ((uint16_t)(ctx->oob_rx_queue_write_index + 1) == ctx->oob_rx_queue_read_index)
2462 {
2463 pthread_rwlock_unlock(&ctx->oob_queue_lock);
2464 rist_log_priv(ctx, RIST_LOG_WARN,
2465 "oob receive queue is full, dropping packet of size %zu\n", payload->size);
2466 return;
2467 }
2468 struct rist_buffer *b = rist_new_buffer(ctx, payload->data, payload->size,
2469 RIST_PAYLOAD_TYPE_DATA_OOB, 0, payload->source_time, 0, 0);
2470 if (RIST_UNLIKELY(!b))
2471 {
2472 pthread_rwlock_unlock(&ctx->oob_queue_lock);
2473 rist_log_priv(ctx, RIST_LOG_ERROR, "Could not allocate oob receive buffer, OOM\n");
2474 return;
2475 }
2476 b->peer = peer;
2477 ctx->oob_rx_queue[ctx->oob_rx_queue_write_index] = b;
2478 ctx->oob_rx_queue_write_index = (uint16_t)(ctx->oob_rx_queue_write_index + 1);
2479 pthread_rwlock_unlock(&ctx->oob_queue_lock);
2480 }
2481
2482 /* Pull one packet from the oob receive fifo. The returned block is owned by
2483 * the library and stays valid until the next rist_oob_dequeue_rx() call.
2484 * Returns the number of packets that were available (>=1) when data is
2485 * returned, 0 when the fifo is empty. */
2486 int rist_oob_dequeue_rx(struct rist_common_ctx *ctx, const struct rist_oob_block **oob_block)
2487 {
2488 *oob_block = NULL;
2489
2490 pthread_rwlock_wrlock(&ctx->oob_queue_lock);
2491
2492 /* release the buffer handed out by the previous call */
2493 if (ctx->oob_rx_current)
2494 {
2495 free_rist_buffer(ctx, ctx->oob_rx_current);
2496 ctx->oob_rx_current = NULL;
2497 }
2498
2499 if (ctx->oob_rx_queue_read_index == ctx->oob_rx_queue_write_index)
2500 {
2501 pthread_rwlock_unlock(&ctx->oob_queue_lock);
2502 return 0;
2503 }
2504
2505 struct rist_buffer *b = ctx->oob_rx_queue[ctx->oob_rx_queue_read_index];
2506 ctx->oob_rx_queue[ctx->oob_rx_queue_read_index] = NULL;
2507 ctx->oob_rx_queue_read_index = (uint16_t)(ctx->oob_rx_queue_read_index + 1);
2508 int available = (uint16_t)(ctx->oob_rx_queue_write_index - ctx->oob_rx_queue_read_index) + 1;
2509
2510 ctx->oob_rx_current = b;
2511 ctx->oob_rx_block.peer = b->peer;
2512 ctx->oob_rx_block.payload = (uint8_t *)b->data + RIST_MAX_PAYLOAD_OFFSET;
2513 ctx->oob_rx_block.payload_len = b->size;
2514 ctx->oob_rx_block.ts_ntp = b->source_time;
2515 *oob_block = &ctx->oob_rx_block;
2516
2517 pthread_rwlock_unlock(&ctx->oob_queue_lock);
2518 return available;
2519 }
2520
2521 static void rist_rtcp_handle_echo_request(struct rist_peer *peer, struct rist_rtcp_echoext *echoreq) {
2522 if (RIST_UNLIKELY(!peer->echo_enabled))
2523 peer->echo_enabled = true;
2524 uint64_t echo_request_time = ((uint64_t)be32toh(echoreq->ntp_msw) << 32) | be32toh(echoreq->ntp_lsw);
2525 uint32_t ssrc = be32toh(echoreq->ssrc);
2526 rist_respond_echoreq(peer, echo_request_time, ssrc);
2527 }
2528
2529 static void rist_rtcp_handle_echo_response(struct rist_peer *peer, struct rist_rtcp_echoext *echoreq) {
2530 peer->echo_enabled = true;
2531 if (be32toh(echoreq->ssrc) != peer->peer_ssrc)
2532 return;
2533 uint64_t request_time = ((uint64_t)be32toh(echoreq->ntp_msw) << 32) | be32toh(echoreq->ntp_lsw);
2534 uint64_t rtt = calculate_rtt_delay(request_time, timestampNTP_u64(), be32toh(echoreq->delay));
2535 rist_peer_rtt_update(peer, rtt);
2536 }
2537
2538 static void rist_handle_sr_pkt(struct rist_peer *peer, struct rist_rtcp_sr_pkt *sr) {
2539 uint64_t ntp_time = ((uint64_t)be32toh(sr->ntp_msw) << 32) | be32toh(sr->ntp_lsw);
2540 peer->last_sender_report_time = ntp_time;
2541 peer->last_sender_report_ts = timestampNTP_u64();
2542 if (peer->config.timing_mode == RIST_TIMING_MODE_RTC)
2543 {
2544 if (peer->flow && peer->flow->time_offset == 0)
2545 {
2546 uint64_t packet_timestamp = convertRTPtoNTP(RTP_PTYPE_MPEGTS, 0, be32toh(sr->rtp_ts));
2547 peer->flow->time_offset = ntp_time - packet_timestamp;
2548 }
2549 }
2550 }
2551
2552 static void rist_handle_rr_pkt(struct rist_peer *peer, struct rist_rtcp_rr_pkt *rr) {
2553 if (peer->echo_enabled)
2554 return;
2555 uint64_t lsr_tmp = (peer->last_sender_report_time >> 16) & 0xFFFFFFFF;
2556 uint64_t lsr_ntp = be32toh(rr->lsr);
2557 uint64_t rtt;
2558 if (!peer->last_sender_report_ts)
2559 return;
2560 uint64_t dlsr = (uint64_t)be32toh(rr->dlsr) << 16;
2561 if (lsr_ntp == lsr_tmp) {
2562 uint64_t now = timestampNTP_u64();
2563 // guard the unsigned subtraction; dlsr comes from the wire
2564 if (peer->last_sender_report_ts + dlsr > now)
2565 return;
2566 rtt = now - peer->last_sender_report_ts - dlsr;
2567
2568 } else {
2569 if (!lsr_ntp)//this can happen on the first time
2570 return;
2571 //Slightly less accurate, needed when RTT is bigger than our RTCP interval.
2572 // lsr in SR is populated from RTC, so be sure to use that when comparing.
2573 uint64_t now_rtc = timestampNTP_RTC_u64();
2574 lsr_ntp = (lsr_ntp << 16) & 0x0000FFFFFFFF0000;
2575 lsr_ntp |= (now_rtc & 0xFFFF000000000000);
2576 if (lsr_ntp > now_rtc || lsr_ntp + dlsr > now_rtc)
2577 return;
2578 rtt = now_rtc - lsr_ntp - dlsr;
2579 }
2580 rist_peer_rtt_update(peer, rtt);
2581 }
2582
2583 static void rist_handle_xr_pkt(struct rist_peer *peer, uint8_t xr_pkt[], size_t pkt_len)
2584 {
2585 size_t offset = 0;
2586 if (pkt_len < sizeof(struct rist_rtcp_hdr))
2587 return;
2588 struct rist_rtcp_hdr *hdr = (struct rist_rtcp_hdr *)&xr_pkt[offset];
2589 // clamp the declared len to what we actually received
2590 size_t payload_len = ((size_t)be16toh(hdr->len) + 1) * 4;
2591 if (payload_len > pkt_len)
2592 payload_len = pkt_len;
2593 if (payload_len < sizeof(struct rist_rtcp_hdr))
2594 return;
2595 size_t bytes_remaining = payload_len - sizeof(struct rist_rtcp_hdr);
2596 offset += sizeof(struct rist_rtcp_hdr);
2597 while (bytes_remaining >= sizeof(struct rist_rtcp_xr_block_hdr))
2598 {
2599 struct rist_rtcp_xr_block_hdr *block = (struct rist_rtcp_xr_block_hdr *)&xr_pkt[offset];
2600 uint8_t block_type = block->type;
2601 size_t block_length = ((size_t)be16toh(block->length) + 1) * 4;
2602 if (block_length < sizeof(struct rist_rtcp_xr_block_hdr) ||
2603 block_length > bytes_remaining)
2604 return;
2605 if (block_type == 5)
2606 {
2607 if (block_length < sizeof(struct rist_rtcp_xr_dlrr))
2608 return;
2609 struct rist_rtcp_xr_dlrr *dlrr = (struct rist_rtcp_xr_dlrr *)&xr_pkt[offset];
2610 uint32_t ssrc = be32toh(dlrr->ssrc);
2611 if (ssrc != peer->peer_ssrc)
2612 return;
2613 uint64_t lrr_tmp = (peer->last_sender_report_ts >> 16) & 0xFFFFFFFF;
2614 uint64_t lrr = be32toh(dlrr->lrr);
2615 uint64_t delay = (uint64_t)be32toh(dlrr->delay) << 16;
2616 uint64_t rtt;
2617 if (lrr == lrr_tmp)
2618 {
2619 uint64_t now = timestampNTP_u64();
2620 // guard the unsigned subtraction; delay comes from the wire
2621 if (peer->last_sender_report_ts + delay > now)
2622 return;
2623 rtt = now - peer->last_sender_report_ts - delay;
2624 } else {
2625 //Slightly less accurate, needed when RTT is bigger than our RTCP interval.
2626 uint64_t now = timestampNTP_u64();
2627 lrr = (lrr << 16) & 0x0000FFFFFFFF0000;
2628 lrr |= (now & 0xFFFF000000000000);
2629 if (lrr > now || lrr + delay > now)
2630 return;
2631 rtt = now - lrr - delay;
2632 }
2633 rist_peer_rtt_update(peer, rtt);
2634 }
2635 offset += block_length;
2636 bytes_remaining -= block_length;
2637 }
2638 }
2639
2640 static char *get_ip_str(struct sockaddr *sa, char *s, size_t maxlen)
2641 {
2642 switch(sa->sa_family) {
2643 case AF_INET:
2644 inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
2645 s, (socklen_t)maxlen);
2646 break;
2647
2648 case AF_INET6:
2649 inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
2650 s, (socklen_t)maxlen);
2651 break;
2652
2653 default:
2654 strncpy(s, "Unknown AF", maxlen);
2655 return NULL;
2656 }
2657 return s;
2658 }
2659
2660 static bool try_listener_reassociate_by_cname(struct rist_peer *new_peer, uint64_t now);
2661 static bool try_caller_socket_rebind(struct rist_peer *peer, uint64_t now);
2662
2663 static void rist_recv_rtcp(struct rist_peer *peer, uint32_t seq,
2664 uint32_t flow_id, struct rist_buffer *payload)
2665 {
2666 uint8_t *pkt;
2667 uint8_t ptype;
2668 uint16_t processed_bytes = 0;
2669 uint16_t records;
2670 uint8_t subtype;
2671 peer->stats_receiver_instant.received_rtcp++;
2672 struct rist_common_ctx *ctx = get_cctx(peer);
2673
2674 while (processed_bytes < payload->size) {
2675 pkt = (uint8_t*)payload->data + processed_bytes;
2676 struct rist_rtcp_hdr *rtcp = (struct rist_rtcp_hdr *)pkt;
2677 /* safety checks */
2678 size_t bytes_left = payload->size - processed_bytes;
2679
2680 if ( bytes_left < 4 )
2681 {
2682 /* we must have at least 4 bytes */
2683 rist_log_priv(ctx, RIST_LOG_ERROR, "Rist rtcp packet must have at least 4 bytes, we have %zu\n",
2684 bytes_left);
2685 return;
2686 }
2687
2688 ptype = rtcp->ptype;
2689 subtype = rtcp->flags & 0x1f;
2690 records = be16toh(rtcp->len);
2691 // in size_t so 4*(1+0xFFFF) cannot wrap to 0 and spin the loop
2692 size_t bytes = (size_t)4 * ((size_t)1 + records);
2693 if (bytes < 4 || bytes > bytes_left)
2694 {
2695 /* check for a sane number of bytes */
2696 rist_log_priv(ctx, RIST_LOG_ERROR, "Malformed feedback packet, expecting %zu bytes in the" \
2697 " packet, got a buffer of %zu bytes. ptype = %d\n", bytes,
2698 bytes_left, ptype);
2699 return;
2700 }
2701
2702 switch(ptype) {
2703 case PTYPE_NACK_CUSTOM:
2704 if (subtype == ECHO_RESPONSE) {
2705 if (bytes < sizeof(struct rist_rtcp_echoext))
2706 break;
2707 struct rist_rtcp_echoext *echoresponse = (struct rist_rtcp_echoext *) pkt;
2708 rist_rtcp_handle_echo_response(peer, echoresponse);
2709 break;
2710 }
2711 else if (subtype == ECHO_REQUEST) {
2712 if (bytes < sizeof(struct rist_rtcp_echoext))
2713 break;
2714 struct rist_rtcp_echoext *echorequest = (struct rist_rtcp_echoext *)pkt;
2715 rist_rtcp_handle_echo_request(peer, echorequest);
2716 break;
2717 }
2718 else if (subtype == NACK_FMT_RANGE) {
2719 //Fallthrough
2720 RIST_FALLTHROUGH;
2721 }
2722 else {
2723 rist_log_priv(ctx, RIST_LOG_DEBUG, "Unsupported rtcp custom subtype %d, ignoring ...\n", subtype);
2724 break;
2725 }
2726 case PTYPE_NACK_BITMASK:
2727 //Also FMT Range
2728 rist_sender_recv_nack(peer, flow_id, payload->src_port, payload->dst_port, pkt, bytes_left, 0);
2729 break;
2730 case PTYPE_RR:
2731 if (ntohs(rtcp->len) == 7) {
2732 struct rist_rtcp_rr_pkt *rr = (struct rist_rtcp_rr_pkt *)pkt;
2733 rist_handle_rr_pkt(peer, rr);
2734 }
2735 break;
2736
2737 case PTYPE_SDES:
2738 {
2739 peer->stats_sender_instant.received++;
2740 if (bytes_left < RTCP_SDES_SIZE)
2741 {
2742 rist_log_priv(ctx, RIST_LOG_ERROR, "Malformed SDES packet, %zu bytes < SDES header size\n",
2743 bytes_left);
2744 return;
2745 }
2746 uint8_t name_length = pkt[9];
2747 // must fit the remaining packet AND receiver_name (incl NUL)
2748 if ((size_t)name_length + RTCP_SDES_SIZE > bytes_left ||
2749 name_length >= sizeof(peer->receiver_name))
2750 {
2751 rist_log_priv(ctx, RIST_LOG_ERROR, "Malformed SDES packet, cname len %u out of bounds (left %zu, max %zu)\n",
2752 name_length, bytes_left, sizeof(peer->receiver_name) - 1);
2753 return;
2754 }
2755 if (memcmp(pkt + RTCP_SDES_SIZE, peer->receiver_name, name_length) != 0)
2756 {
2757 memcpy(peer->receiver_name, pkt + RTCP_SDES_SIZE, name_length);
2758 peer->receiver_name[name_length] = '\0';
2759 rist_log_priv(ctx, RIST_LOG_INFO, "Peer %"PRIu32" receiver name is now: %s\n",
2760 peer->adv_peer_id, peer->receiver_name);
2761 }
2762 bool peer_authenticated = peer->authenticated;
2763 int connection_message = 0;
2764 if (peer->receiver_mode) {
2765 rist_receiver_rtcp_authenticate(peer, seq, flow_id);
2766 connection_message = RIST_CLIENT_CONNECTED;
2767 } else if (peer->sender_ctx && peer->listening) {
2768 // TODO: create rist_sender_recv_rtcp
2769 if (!peer->authenticated) {
2770 rist_peer_authenticate(peer);
2771 }
2772 connection_message = RIST_CLIENT_CONNECTED;
2773 }
2774 else {
2775 connection_message = RIST_CONNECTION_ESTABLISHED;
2776 /* Re-associate by cname before announcing a
2777 * brand-new caller. On success this kills the
2778 * new peer and returns, dropping any RTCP records
2779 * that followed the SDES in the same compound
2780 * packet. */
2781 if (!peer->send_first_connection_event &&
2782 try_listener_reassociate_by_cname(peer, timestampNTP_u64()))
2783 return;
2784 }
2785 if (peer->timed_out || !peer->send_first_connection_event || (!peer_authenticated && peer->authenticated)) {
2786 if (!peer->send_first_connection_event)
2787 rist_log_priv(ctx, RIST_LOG_INFO, "Peer %"PRIu32" receiver with name %s reconnected\n",
2788 peer->adv_peer_id, peer->receiver_name);
2789 peer->timed_out = 0;
2790 peer->send_first_connection_event = true;
2791 if (ctx->connection_status_callback)
2792 ctx->connection_status_callback(ctx->connection_status_callback_argument, peer, connection_message);
2793 }
2794 break;
2795 }
2796 case PTYPE_SR:;
2797 if (bytes < sizeof(struct rist_rtcp_sr_pkt))
2798 break;
2799 struct rist_rtcp_sr_pkt *sr = (struct rist_rtcp_sr_pkt *)pkt;
2800 rist_handle_sr_pkt(peer, sr);
2801 break;
2802 case PTYPE_XR:
2803 rist_handle_xr_pkt(peer, pkt, bytes);
2804 break;
2805 default:
2806 rist_log_priv(ctx, RIST_LOG_DEBUG, "Unrecognized RTCP packet with PTYPE=%02x!!\n", ptype);
2807 }
2808 processed_bytes += (uint16_t)bytes;
2809 }
2810
2811 }
2812
2813 void rist_peer_rtcp(struct evsocket_ctx *evctx, void *arg)
2814 {
2815 RIST_MARK_UNUSED(evctx);
2816 struct rist_peer *peer = (struct rist_peer *)arg;
2817 //struct rist_common_ctx *ctx = get_cctx(peer);
2818
2819 if (!peer || atomic_load_explicit(&peer->shutdown, memory_order_acquire) || !peer->is_rtcp) {
2820 return;
2821 }
2822
2823 if (peer->dead && peer->parent != NULL)
2824 return;//Don't send to peers that connect to us and have dropped silent
2825
2826 if (peer->receiver_mode) {
2827 rist_receiver_periodic_rtcp(peer);
2828 } else {
2829 rist_sender_periodic_rtcp(peer);
2830 }
2831 }
2832
2833 static void rist_peer_sockerr(struct evsocket_ctx *evctx, int fd, short revents, void *arg)
2834 {
2835 RIST_MARK_UNUSED(evctx);
2836 RIST_MARK_UNUSED(fd);
2837 RIST_MARK_UNUSED(revents);
2838 struct rist_peer *peer = (struct rist_peer *) arg;
2839 #ifdef _WIN32
2840 /* WSAECONNRESET indications are disabled at socket creation time via
2841 * WSAIoctl(SIO_UDP_CONNRESET, FALSE) - see udpsocket_open(). The earlier
2842 * recvfrom(drain[1], ...) drain has been removed because it could
2843 * cannibalise (or truncate via WSAEMSGSIZE) a real datagram queued
2844 * ahead of - or instead of - the synthetic error indication, leading
2845 * to malformed EAPOL packets and other downstream failures. */
2846 int wsa_err = WSAGetLastError();
2847 if (wsa_err == WSAECONNRESET)
2848 return;
2849 #endif
2850 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "\tSocket error!\n");
2851
2852 //rist_peer_remove(get_cctx(peer), peer, NULL);
2853 }
2854
2855 void sender_peer_append(struct rist_sender *ctx, struct rist_peer *peer)
2856 {
2857 /* Add a reference to ctx->peer_lst */
2858 ctx->peer_lst = realloc(ctx->peer_lst, (ctx->peer_lst_len + 1) * sizeof(*ctx->peer_lst));
2859 ctx->peer_lst[ctx->peer_lst_len] = peer;
2860 ctx->peer_lst_len++;
2861 }
2862
2863 static void peer_copy_settings(struct rist_peer *peer_src, struct rist_peer *peer)
2864 {
2865 _librist_crypto_psk_rist_key_clone(&peer_src->key_rx, &peer->key_rx);
2866 _librist_crypto_psk_rist_key_clone(&peer_src->key_rx_odd, &peer->key_rx_odd);
2867 _librist_crypto_psk_rist_key_clone(&peer_src->key_tx, &peer->key_tx);
2868 _librist_crypto_psk_rist_key_clone(&peer_src->key_tx, &peer->key_tx_odd);
2869 peer->key_tx_odd_active = peer_src->key_tx_odd_active;
2870 strncpy(&peer->cname[0], &peer_src->cname[0], RIST_MAX_STRING_SHORT);
2871 peer->cname[RIST_MAX_STRING_SHORT - 1] = '\0';
2872 strncpy(&peer->miface[0], &peer_src->miface[0], RIST_MAX_STRING_SHORT);
2873 peer->miface[RIST_MAX_STRING_SHORT - 1] = '\0';
2874 peer->config.weight = peer_src->config.weight;
2875 peer->config.recovery_priority = peer_src->config.recovery_priority;
2876 peer->config.virt_dst_port = peer_src->config.virt_dst_port;
2877 peer->config.recovery_mode = peer_src->config.recovery_mode;
2878 peer->config.recovery_maxbitrate = peer_src->config.recovery_maxbitrate;
2879 peer->config.recovery_maxbitrate_return = peer_src->config.recovery_maxbitrate_return;
2880 peer->config.recovery_length_min = peer_src->config.recovery_length_min;
2881 peer->config.recovery_length_max = peer_src->config.recovery_length_max;
2882 peer->config.recovery_reorder_buffer = peer_src->config.recovery_reorder_buffer;
2883 peer->config.recovery_rtt_min = peer_src->config.recovery_rtt_min;
2884 peer->config.recovery_rtt_max = peer_src->config.recovery_rtt_max;
2885 peer->config.congestion_control_mode = peer_src->config.congestion_control_mode;
2886 peer->config.min_retries = peer_src->config.min_retries;
2887 peer->config.max_retries = peer_src->config.max_retries;
2888 peer->config.timing_mode = peer_src->config.timing_mode;
2889 peer->config.reflector = peer_src->config.reflector;
2890 peer->config.multicast_ttl = peer_src->config.multicast_ttl;
2891 strncpy(peer->config.multicast_source, peer_src->config.multicast_source, RIST_MAX_STRING_LONG - 1);
2892 peer->config.multicast_source[RIST_MAX_STRING_LONG - 1] = '\0';
2893 peer->config.local_port = peer_src->config.local_port;
2894 peer->config.rtt_drop = peer_src->config.rtt_drop;
2895 peer->config.rtt_restore = peer_src->config.rtt_restore;
2896 peer->config.rtt_drop_settle = peer_src->config.rtt_drop_settle;
2897 peer->config.rtt_drop_trickle = peer_src->config.rtt_drop_trickle;
2898 peer->rtcp_keepalive_interval = peer_src->rtcp_keepalive_interval;
2899 peer->peer_ssrc = peer_src->peer_ssrc;
2900 peer->session_timeout = peer_src->session_timeout;
2901 peer->rist_gre_version = RIST_GRE_VERSION_MIN;
2902 memcpy(peer->mac_addr, peer_src->mac_addr, sizeof(peer->mac_addr));
2903 init_peer_settings(peer);
2904 }
2905
2906 static void kill_peer(struct rist_peer *peer)
2907 {
2908 bool current_state = peer->dead;
2909 peer->dead = true;
2910 if (peer->peer_data && (current_state != peer->peer_data->dead && peer->peer_data->parent))
2911 --peer->peer_data->parent->child_alive_count;
2912 peer->dead_since = timestampNTP_u64();
2913 }
2914
2915 /* Listener-side cname re-association for a NAT source-port rebind.
2916 * SRP only: the cname is not a per-peer secret, so an authenticated
2917 * per-peer session is required before migrating an identity to a new
2918 * source tuple. Returns true after killing new_peer. */
2919 static bool try_listener_reassociate_by_cname(struct rist_peer *new_peer, uint64_t now)
2920 {
2921 struct rist_peer *parent = new_peer->parent;
2922 if (!parent || !parent->listening || !new_peer->sender_ctx ||
2923 new_peer->receiver_mode || new_peer->receiver_name[0] == '\0')
2924 return false;
2925
2926 #if HAVE_SRP_SUPPORT
2927 if (!new_peer->eap_ctx || !eap_is_authenticated(new_peer->eap_ctx))
2928 return false;
2929 #else
2930 /* No SRP: there is no authenticated per-peer session to gate on, and
2931 * the cname is not a per-peer secret, so reassociation is unsafe. */
2932 return false;
2933 #endif
2934
2935 uint64_t ka = new_peer->rtcp_keepalive_interval
2936 ? new_peer->rtcp_keepalive_interval
2937 : (uint64_t)RIST_PING_INTERVAL * RIST_CLOCK;
2938 uint64_t silent_threshold = 2 * ka;
2939
2940 struct rist_peer *candidate = NULL;
2941 int alive_duplicates = 0;
2942 struct rist_peer *sib = parent->child;
2943 while (sib) {
2944 if (sib != new_peer &&
2945 sib->is_rtcp == new_peer->is_rtcp &&
2946 sib->is_data == new_peer->is_data &&
2947 sib->adv_flow_id == new_peer->adv_flow_id &&
2948 sib->receiver_name[0] != '\0' &&
2949 strncmp(sib->receiver_name, new_peer->receiver_name,
2950 RIST_MAX_HOSTNAME) == 0) {
2951 bool silent = sib->last_pkt_received > 0 &&
2952 now > sib->last_pkt_received &&
2953 (now - sib->last_pkt_received) > silent_threshold;
2954 if (sib->dead || silent) {
2955 if (candidate == NULL)
2956 candidate = sib;
2957 } else {
2958 alive_duplicates++;
2959 }
2960 }
2961 sib = sib->sibling_next;
2962 }
2963
2964 if (!candidate || alive_duplicates > 0)
2965 return false;
2966
2967 memcpy(&candidate->u.address, &new_peer->u.address, new_peer->address_len);
2968 candidate->address_len = new_peer->address_len;
2969 candidate->address_family = new_peer->address_family;
2970 candidate->remote_port = new_peer->remote_port;
2971 candidate->dead = 0;
2972 candidate->timed_out = 0;
2973 candidate->last_pkt_received = now;
2974 rist_log_priv(get_cctx(new_peer), RIST_LOG_INFO,
2975 "cname \"%s\" matched existing peer %"PRIu32
2976 "; migrated source tuple from new peer %"PRIu32
2977 " and retired it (NAT-rebind recovery, SRP).\n",
2978 new_peer->receiver_name, candidate->adv_peer_id,
2979 new_peer->adv_peer_id);
2980
2981 #if HAVE_SRP_SUPPORT
2982 /* Kick a fresh EAPOL START so re-auth fires now, not up to
2983 * EAP_REAUTH_PERIOD later. */
2984 if (candidate->eap_ctx)
2985 _librist_proto_eap_start(candidate->eap_ctx);
2986 #endif
2987
2988 kill_peer(new_peer);
2989 return true;
2990 }
2991
2992 /* Caller-side recovery when a peer goes silent past session_timeout.
2993 * Receiver-mode callers rebind the local socket (NAT rebind / listener
2994 * restart); SRP callers also reset EAP and re-handshake on the fresh socket.
2995 * Sender-mode callers only reach the SRP path: their miface-bound socket
2996 * survives a flap, so they reset EAP without rebinding (see the branches).
2997 * Linear backoff capped at REBIND_BACKOFF_CAP. */
2998 #define REBIND_BACKOFF_CAP 10
2999 static bool try_caller_socket_rebind(struct rist_peer *peer, uint64_t now)
3000 {
3001 struct rist_common_ctx *cctx = get_cctx(peer);
3002 if (!peer || peer->parent || peer->listening ||
3003 peer->multicast_sender || peer->multicast_receiver)
3004 return false;
3005 if (cctx->profile <= RIST_PROFILE_SIMPLE)
3006 return false;
3007 if (peer->config.local_port != 0)
3008 return false;
3009
3010 /* Require silence beyond max(session_timeout, 4*keepalive) so a
3011 * misconfigured short session_timeout against a slower keepalive
3012 * cadence does not trigger a flap loop on legitimate streams. */
3013 uint64_t ka = peer->rtcp_keepalive_interval
3014 ? peer->rtcp_keepalive_interval
3015 : (uint64_t)RIST_PING_INTERVAL * RIST_CLOCK;
3016 uint64_t min_silence = peer->session_timeout > 4 * ka
3017 ? peer->session_timeout : 4 * ka;
3018 if (peer->last_pkt_received == 0 ||
3019 now <= peer->last_pkt_received ||
3020 (now - peer->last_pkt_received) <= min_silence)
3021 return false;
3022
3023 uint32_t backoff_mult = peer->rebind_attempts > REBIND_BACKOFF_CAP
3024 ? REBIND_BACKOFF_CAP : peer->rebind_attempts;
3025 uint64_t min_gap = (uint64_t)backoff_mult * peer->session_timeout;
3026 if (peer->last_rebind_time != 0 && now > peer->last_rebind_time &&
3027 (now - peer->last_rebind_time) < min_gap)
3028 return false;
3029
3030 if (!peer->receiver_mode) {
3031 #if HAVE_SRP_SUPPORT
3032 /* Sender-mode leg: the miface-bound socket survives a flap, so
3033 * don't rebind it -- just reset EAP and re-drive the handshake on
3034 * the existing socket. Only SRP deadlocks like this; plaintext/PSK
3035 * recover via normal reconnect.
3036 *
3037 * De-authenticate the leg so it drops out of the weighted sender
3038 * balancing while it is silent (the balancer keeps a leg in rotation
3039 * only while authenticated) and re-drives the connection handshake.
3040 * eap_authentication_state is rewound to 1 so the "EAP Authentication
3041 * succeeded" transition fires again when re-auth completes; that path
3042 * restores authenticated and folds the leg back into the bond at full
3043 * weight (without this, the leg re-authenticates but never rejoins
3044 * balancing, streaming only NACK retransmits). */
3045 if (peer->eap_ctx == NULL)
3046 return false;
3047 peer->authenticated = false;
3048 peer->eap_authentication_state = 1;
3049 peer->dead = 0;
3050 peer->timed_out = 0;
3051 peer->last_pkt_received = now;
3052 eap_reset_authenticatee(peer->eap_ctx);
3053 peer->rebind_attempts++;
3054 peer->last_rebind_time = now;
3055 rist_log_priv(cctx, RIST_LOG_WARN,
3056 "Sender caller peer %"PRIu32" silent past session_timeout "
3057 "(attempt %"PRIu32"); reset EAP and re-initiated the SRP "
3058 "handshake to recover the leg without operator intervention.\n",
3059 peer->adv_peer_id, peer->rebind_attempts);
3060 return true;
3061 #else
3062 return false;
3063 #endif
3064 }
3065
3066 struct evsocket_ctx *evctx = cctx->evctx;
3067 int old_sd = peer->sd;
3068 uint16_t old_local_port = peer->local_port;
3069
3070 if (peer->event_recv) {
3071 evsocket_delevent(evctx, peer->event_recv);
3072 peer->event_recv = NULL;
3073 }
3074 if (old_sd >= 0) {
3075 udpsocket_close(old_sd);
3076 peer->sd = -1;
3077 }
3078
3079 rist_create_socket(peer);
3080 if (peer->sd < 0) {
3081 rist_log_priv(cctx, RIST_LOG_ERROR,
3082 "Caller socket rebind failed for peer %"PRIu32
3083 " (errno=%d), falling through to kill_peer.\n",
3084 peer->adv_peer_id, errno);
3085 return false;
3086 }
3087
3088 peer->event_recv = evsocket_addevent(evctx, peer->sd, EVSOCKET_EV_READ,
3089 rist_peer_recv_wrap,
3090 rist_peer_sockerr, peer);
3091
3092 /* Force a fresh handshake on the new tuple. */
3093 peer->authenticated = false;
3094 peer->dead = 0;
3095 peer->timed_out = 0;
3096 peer->last_pkt_received = now;
3097 peer->next_periodic_rtcp = now;
3098 peer->next_keepalive_packet = now;
3099 peer->send_keepalive = true;
3100 peer->send_first_connection_event = false;
3101
3102 #if HAVE_SRP_SUPPORT
3103 /* SRP callers: the authenticated session is bound to the old source
3104 * tuple and (after a listener restart) to state the far end no longer
3105 * has. Reset EAP back to UNAUTH and re-send EAPOL START on the new
3106 * socket so the authenticator re-challenges us immediately, exactly as
3107 * on a cold connect. Non-SRP callers just resume via the keepalives
3108 * armed above. */
3109 if (peer->eap_ctx != NULL)
3110 eap_reset_authenticatee(peer->eap_ctx);
3111 #endif
3112
3113 peer->rebind_attempts++;
3114 peer->last_rebind_time = now;
3115
3116 rist_log_priv(cctx, RIST_LOG_WARN,
3117 "Receiver peer %"PRIu32" silent past session_timeout "
3118 "(attempt %"PRIu32"); rebound caller socket %d->%d "
3119 "(local_port %u->%u) for NAT/dynamic-IP recovery.\n",
3120 peer->adv_peer_id, peer->rebind_attempts, old_sd, peer->sd,
3121 (unsigned)old_local_port, (unsigned)peer->local_port);
3122
3123 return true;
3124 }
3125
3126 static void rist_peer_recv_wrap(struct evsocket_ctx *evctx, int fd, short revents, void *arg) {
3127 bool again = true;
3128 while (true) {
3129 rist_peer_recv(evctx, fd, revents, arg, &again);
3130 if (!again)
3131 return;
3132 }
3133 }
3134
3135 static void rist_new_connection(struct rist_peer *peer, struct rist_peer *p, uint32_t flow_id) {
3136 const char *peer_type = "?";
3137 const char *id_name = "?";
3138 if (peer->is_rtcp) {
3139 peer_type = "RTCP";
3140 id_name = "flow_id";
3141 } else if (peer->is_data) {
3142 peer_type = "RTP";
3143 id_name = "ssrc";
3144 }
3145 if (peer->receiver_mode) {
3146 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "New %s peer connecting, %s %"PRIu32", peer_id %"PRIu32", ports %u <- %u\n",
3147 peer_type, id_name, flow_id, p->adv_peer_id, p->local_port, p->remote_port);
3148 p->adv_flow_id = flow_id;
3149 }
3150 else {
3151 if (flow_id) {
3152 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "New reverse %s peer connecting with old flow_id %"PRIu32", peer_id %"PRIu32", ports %u <- %u\n",
3153 peer_type, flow_id, p->adv_peer_id, p->local_port, p->remote_port);
3154 } else {
3155 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "New reverse %s peer connecting, peer_id %"PRIu32", ports %u <- %u\n",
3156 peer_type, p->adv_peer_id, p->local_port, p->remote_port);
3157 }
3158 p->peer_ssrc = p->adv_flow_id = p->sender_ctx->adv_flow_id;
3159 }
3160 }
3161
3162 static void rist_peer_recv(struct evsocket_ctx *evctx, int fd, short revents, void *arg, bool *again)
3163 {
3164 RIST_MARK_UNUSED(evctx);
3165 RIST_MARK_UNUSED(revents);
3166 RIST_MARK_UNUSED(fd);
3167
3168 struct rist_peer *peer = (struct rist_peer *) arg;
3169 if (atomic_load_explicit(&peer->shutdown, memory_order_acquire)) {
3170 return;
3171 }
3172 uint64_t now = timestampNTP_u64();
3173 struct rist_common_ctx *cctx = get_cctx(peer);
3174
3175 socklen_t addrlen = peer->address_len;
3176 size_t recv_bufsize = 0;
3177 uint16_t family = peer->address_family;
3178 struct sockaddr_storage ss = {0};
3179 struct sockaddr *addr = (struct sockaddr *)&ss;
3180 struct rist_peer *p = NULL;
3181 uint8_t *recv_buf = cctx->buf.recv;
3182 uint8_t *recv_buf_npd = cctx->buf.recv_npd;
3183 uint16_t port = 0;
3184
3185 ssize_t ret = rist_transport_recvfrom(peer, recv_buf, RIST_MAX_PACKET_SIZE, MSG_DONTWAIT, addr, &addrlen);
3186 if (ss.ss_family == AF_INET)
3187 port = htons(((struct sockaddr_in *)addr)->sin_port);
3188 else
3189 port = htons(((struct sockaddr_in6 *)addr)->sin6_port);
3190
3191 #ifndef _WIN32
3192 if (ret <= 0) {
3193 *again = false;
3194 int errorcode = errno;
3195 /* Custom transports compiled in a different TU may have EAGAIN
3196 * resolve to a different numeric value than this TU; match both
3197 * canonical values defensively. */
3198 if (errno == EAGAIN || errno == EWOULDBLOCK ||
3199 (ret == -1 && (errorcode == 11 || errorcode == 35)))
3200 return;
3201 #else
3202 if (ret == SOCKET_ERROR) {
3203 *again = false;
3204 int errorcode = WSAGetLastError();
3205 if (errorcode == WSAEWOULDBLOCK)
3206 return;
3207 #endif
3208 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Receive failed: errno=%d, ret=%d, socket=%d\n", errorcode, recv_bufsize, fd);
3209 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "%s\n", strerror(errorcode));
3210 return;
3211 }
3212
3213 recv_bufsize = ret;
3214
3215 /* Transparent one-to-many reflector: forward raw packets between
3216 * publisher and subscriber children before any decryption or
3217 * protocol processing. Only active when ?reflector=1 is set. */
3218 if (peer->config.reflector && peer->listening && !peer->multicast_receiver) {
3219 struct rist_peer *p_sender = _librist_peer_match_peer_addr(peer, family, addr);
3220 if (p_sender && p_sender->parent == peer) {
3221 struct rist_peer *child = peer->child;
3222 while (child) {
3223 if (child != p_sender) {
3224 if (p_sender->is_reflector_publisher) {
3225 /* Forward publisher's packet (RTP/RTCP) to subscriber children */
3226 if (!child->is_reflector_publisher) {
3227 sendto(peer->sd, (const char *)recv_buf, recv_bufsize, 0, &child->u.address, child->address_len);
3228 }
3229 } else {
3230 /* Forward subscriber's packet (NACK/RTCP) to publisher children */
3231 if (child->is_reflector_publisher) {
3232 sendto(peer->sd, (const char *)recv_buf, recv_bufsize, 0, &child->u.address, child->address_len);
3233 }
3234 }
3235 }
3236 child = child->sibling_next;
3237 }
3238 }
3239 }
3240
3241 struct rist_key *k = &peer->key_rx;
3242 uint32_t seq = 0;
3243 uint32_t time_extension = 0;
3244 uint8_t retry = 0;
3245 size_t payload_offset = 0;
3246 struct rist_buffer payload = { .data = NULL, .size = 0, .type = 0, .src_port = 0, .dst_port = 0 };
3247 uint32_t flow_id = 0;
3248 uint16_t gre_proto = 0;
3249 uint8_t rist_gre_version = RIST_GRE_VERSION_MIN;
3250 if (cctx->profile > RIST_PROFILE_SIMPLE)
3251 {
3252 /* Section 9 (TR-06-3): Auto-detect GRE vs RTP framing.
3253 * First byte bits [7:6]:
3254 * 0b0x = GRE (bit 7 = 0 → Main/Advanced GRE tunnel)
3255 * 0b10 = RTP V=2 → Advanced Profile if PT=127 */
3256 if (cctx->profile == RIST_PROFILE_ADVANCED &&
3257 recv_bufsize >= RIST_ADV_HEADER_MIN &&
3258 (recv_buf[0] & 0xC0) == 0x80) {
3259 /* Looks like RTP V=2. Check PT field for Advanced Profile. */
3260 uint8_t pt = recv_buf[1] & 0x7F;
3261 if (pt == RIST_ADV_PT || pt >= 96) {
3262 struct rist_adv_parsed adv_parsed;
3263 if (rist_adv_parse(recv_buf, recv_bufsize, &adv_parsed) == 0) {
3264 p = _librist_peer_match_peer_addr(peer, family, addr);
3265 if (!p) {
3266 if (peer->listening || peer->multicast_sender) {
3267 p = peer_initialize(NULL, peer->sender_ctx, peer->receiver_ctx);
3268 p->handled_first = false;
3269 p->adv_peer_id = ++cctx->peer_counter;
3270 p->parent = peer;
3271 peer_copy_settings(peer, p);
3272 if (peer->receiver_ctx) {
3273 p->remote_port = port;
3274 p->local_port = peer->local_port;
3275 } else {
3276 p->remote_port = peer->remote_port;
3277 p->local_port = peer->local_port;
3278 }
3279 p->address_family = family;
3280 p->address_len = addrlen;
3281 p->listening = 0;
3282 p->is_rtcp = peer->is_rtcp;
3283 p->is_data = peer->is_data;
3284 p->peer_data = p;
3285 p->is_advanced = true;
3286 memcpy(&p->u.address, addr, addrlen);
3287 p->sd = peer->sd;
3288 p->authenticated = false;
3289 p->event_recv = peer->event_recv;
3290 p->send_keepalive = true;
3291 if (cctx->auth.conn_cb) {
3292 char incoming_ip_str[INET6_ADDRSTRLEN];
3293 char *ip_str = get_ip_str(&p->u.address, incoming_ip_str, INET6_ADDRSTRLEN);
3294 char parent_ip_str[INET6_ADDRSTRLEN];
3295 char *parent_str = get_ip_str(&p->parent->u.address, parent_ip_str, INET6_ADDRSTRLEN);
3296 if (!parent_str) parent_str = "";
3297 uint16_t parent_port = 0;
3298 if (p->parent->u.storage.ss_family == AF_INET)
3299 parent_port = htons(p->parent->u.inaddr.sin_port);
3300 else
3301 parent_port = htons(p->parent->u.inaddr6.sin6_port);
3302 if (ip_str && cctx->auth.conn_cb(cctx->auth.arg, ip_str, port, parent_str, parent_port, p)) {
3303 free(p);
3304 return;
3305 }
3306 }
3307 peer_append(p);
3308 #if HAVE_SRP_SUPPORT
3309 eap_clone_ctx(peer->eap_ctx, p);
3310 {
3311 char ip_buf[INET6_ADDRSTRLEN];
3312 char *ip = get_ip_str(&p->u.address, ip_buf, INET6_ADDRSTRLEN);
3313 if (ip)
3314 eap_set_ip_string(p->eap_ctx, ip_buf);
3315 }
3316 #endif
3317 } else {
3318 return;
3319 }
3320 }
3321 p->is_advanced = true;
3322 p->last_pkt_received = now;
3323
3324 /* Dispatch by encapsulation type */
3325 if (adv_parsed.enc_type == RIST_ADV_TYPE_CONTROL) {
3326 rist_calculate_bitrate(recv_bufsize, &p->bw);
3327 rist_adv_recv_control(p, adv_parsed.payload,
3328 adv_parsed.payload_len);
3329 return;
3330 }
3331
3332 uint32_t adv_flow_id = adv_parsed.ssrc & ~(uint32_t)1;
3333 retry = adv_parsed.retransmit ? 1 : 0;
3334
3335 if (adv_parsed.enc_type == RIST_ADV_TYPE_DIRECT) {
3336 /* PSK decryption for Advanced Profile */
3337 uint8_t adv_dec_buf[RIST_MAX_PACKET_SIZE];
3338 const uint8_t *adv_data = adv_parsed.payload;
3339 size_t adv_data_len = adv_parsed.payload_len;
3340
3341 if (adv_parsed.psk_mode == RIST_ADV_PSK_AES_CTR) {
3342 if (!p->key_rx.key_size) {
3343 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3344 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3345 "Advanced Profile: encrypted data but no PSK configured\n");
3346 peer->log_repeat_timer = now;
3347 }
3348 return;
3349 }
3350 if (!adv_parsed.psk_nonce || !adv_parsed.psk_iv) {
3351 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3352 "Advanced Profile: PSK AES-CTR missing nonce/IV\n");
3353 return;
3354 }
3355 bool odd_nonce_adv = CHECK_BIT(adv_parsed.psk_nonce[0], 7);
3356 struct rist_key *ak = &p->key_rx;
3357 if (odd_nonce_adv)
3358 ak = &p->key_rx_odd;
3359 pthread_mutex_lock(&p->peer_lock);
3360 uint32_t seq_nbe;
3361 memcpy(&seq_nbe, adv_parsed.psk_iv, sizeof(seq_nbe));
3362 _librist_crypto_psk_decrypt(ak,
3363 (uint8_t *)adv_parsed.psk_nonce, seq_nbe, 1,
3364 adv_parsed.payload, adv_dec_buf, adv_data_len);
3365 pthread_mutex_unlock(&p->peer_lock);
3366 if (ak->bad_decryption)
3367 return;
3368 adv_data = adv_dec_buf;
3369 } else if (adv_parsed.psk_mode != RIST_ADV_PSK_NONE) {
3370 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3371 rist_log_priv(get_cctx(peer), RIST_LOG_WARN,
3372 "Advanced Profile: unsupported PSK mode %u\n",
3373 adv_parsed.psk_mode);
3374 peer->log_repeat_timer = now;
3375 }
3376 return;
3377 } else if (p->key_rx.key_size) {
3378 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3379 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3380 "Advanced Profile: expect encrypted data but received clear\n");
3381 peer->log_repeat_timer = now;
3382 }
3383 return;
3384 }
3385
3386 uint8_t adv_lz4_buf[RIST_MAX_PACKET_SIZE];
3387 if (adv_parsed.lpc_mode == RIST_ADV_LPC_LZ4 && adv_data_len > 0) {
3388 int dlen = LZ4_decompress_safe(
3389 (const char *)adv_data, (char *)adv_lz4_buf,
3390 (int)adv_data_len, RIST_MAX_PACKET_SIZE);
3391 if (dlen <= 0) {
3392 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3393 "Advanced Profile: LZ4 decompress failed\n");
3394 return;
3395 }
3396 adv_data = adv_lz4_buf;
3397 adv_data_len = (size_t)dlen;
3398 } else if (adv_parsed.lpc_mode != RIST_ADV_LPC_NONE) {
3399 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3400 rist_log_priv(get_cctx(peer), RIST_LOG_WARN,
3401 "Advanced Profile: unsupported LPC mode %u\n",
3402 adv_parsed.lpc_mode);
3403 peer->log_repeat_timer = now;
3404 }
3405 return;
3406 }
3407
3408 /* Stamp with the sender's timeline rebuilt from the 1 MHz
3409 * RTP timestamp so the dejitter buffer smooths off the
3410 * source clock like the Main path, not raw arrival. ARRIVAL
3411 * mode keeps arrival; otherwise the reconstruct dejitters off
3412 * the source clock immediately and, because older releases
3413 * emitted a broken clock, corrects to arrival after the first
3414 * second if the sender's clock is not advancing at real time. */
3415 uint64_t adv_source_time;
3416 if (RIST_UNLIKELY(p->config.timing_mode == RIST_TIMING_MODE_ARRIVAL))
3417 adv_source_time = now;
3418 else
3419 adv_source_time = rist_adv_ts_reconstruct(&p->rx_adv_ts,
3420 adv_parsed.timestamp, now,
3421 ONE_SECOND, !retry);
3422
3423 if (peer->receiver_ctx) {
3424 rist_calculate_bitrate(recv_bufsize, &p->bw);
3425 uint16_t adv_src_port = (uint16_t)(32768 + p->adv_peer_id);
3426 uint16_t adv_dst_port = p->config.virt_dst_port;
3427 if (adv_parsed.has_flow_id && adv_parsed.flow_id) {
3428 adv_dst_port = rist_adv_flow_outer(adv_parsed.flow_id);
3429 adv_src_port = rist_adv_flow_inner(adv_parsed.flow_id);
3430 }
3431 struct rist_buffer adv_payload = {
3432 .data = (void *)adv_data,
3433 .size = adv_data_len,
3434 .type = RIST_PAYLOAD_TYPE_DATA_RAW,
3435 .src_port = adv_src_port,
3436 .dst_port = adv_dst_port,
3437 };
3438 /* Pass the delivered payload size (adv_data_len), not
3439 * the full datagram, so received_bytes and bitrate
3440 * match the Main path's payload-only accounting.
3441 * ts_null_bytes is 0: the Advanced receive path does
3442 * no ts-null reinsertion. */
3443 rist_receiver_recv_data(p, adv_parsed.seq, adv_flow_id,
3444 adv_source_time, now, &adv_payload, retry,
3445 RIST_PAYLOAD_TYPE_DATA_RAW, adv_data_len, 0, false);
3446 }
3447 return;
3448 }
3449
3450 if (adv_parsed.enc_type == RIST_ADV_TYPE_GRE_MAIN) {
3451 /* Type 8: Strip Advanced Profile header, process inner GRE.
3452 * The payload is a Main Profile GRE packet — feed it back
3453 * through the existing GRE receive path by updating the
3454 * buffer pointer and falling through. */
3455 recv_buf = (uint8_t *)adv_parsed.payload;
3456 recv_bufsize = adv_parsed.payload_len;
3457 /* Fall through to GRE processing below */
3458 } else {
3459 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
3460 "Advanced Profile: unsupported encapsulation type %u\n",
3461 adv_parsed.enc_type);
3462 return;
3463 }
3464 }
3465 }
3466 }
3467
3468 struct rist_gre_hdr *gre = NULL;
3469 // Make sure we have enough bytes
3470 if (recv_bufsize < (int)sizeof(*gre)) {
3471 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Packet too small: %d bytes, ignoring ...\n", recv_bufsize);
3472 return;
3473 }
3474
3475 gre = (void *) recv_buf;
3476 payload_offset += sizeof(*gre);
3477 gre_proto = be16toh(gre->prot_type);
3478 if (CHECK_BIT(gre->flags1, 6) != 0 || (gre->flags2 & 0x7) != 0) {
3479 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3480 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3481 "Non conformant main profile packet received\n");
3482 peer->log_repeat_timer = now;
3483 }
3484 return;
3485 }
3486 uint8_t has_checksum = CHECK_BIT(gre->flags1, 7);
3487 uint8_t has_key = CHECK_BIT(gre->flags1, 5);
3488 uint8_t has_seq = CHECK_BIT(gre->flags1, 4);
3489 rist_gre_version = (gre->flags2 >> 3) & 0x7;
3490
3491 if (recv_bufsize < (sizeof(*gre) + has_checksum*4 + has_key *4 + has_seq *4)) {
3492 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Packet too small: %d bytes, ignoring ...\n", recv_bufsize);
3493 return;
3494 }
3495
3496 if (has_checksum) {
3497 payload_offset += 4;
3498 }
3499
3500 size_t nonce_offset = 0;
3501 bool odd_nonce = false;
3502 if (has_key) {
3503 nonce_offset = payload_offset;
3504 odd_nonce = CHECK_BIT(recv_buf[nonce_offset], 7);
3505 payload_offset += 4;
3506 }
3507
3508 if (has_seq) {
3509 seq = recv_buf[payload_offset] << 24 | recv_buf[payload_offset+ 1] << 16 | recv_buf[payload_offset+ 2] << 8 | recv_buf[payload_offset+ 3];
3510 payload_offset += 4;
3511 }
3512
3513 p = _librist_peer_match_peer_addr(peer, family, addr);
3514
3515 if (has_seq && has_key && gre_proto != RIST_GRE_PROTOCOL_TYPE_EAPOL) {
3516 // Key bit is set, that means the other side want to send
3517 // encrypted data.
3518 //
3519 // make sure we have a key before attempting to decrypt
3520 if (!k->key_size) {
3521 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3522 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Receiving encrypted data, but configured without keysize!\n");
3523 peer->log_repeat_timer = now;
3524 }
3525 return;
3526 }
3527
3528
3529
3530 if (!p)
3531 p = peer;
3532 #if ALLOW_INSECURE_IV_FALLBACK == 1
3533 if (rist_gre_version < 1)
3534 p->rist_gre_version = rist_gre_version;
3535 #endif
3536 pthread_mutex_lock(&p->peer_lock);
3537 k = &p->key_rx;
3538 if (odd_nonce)
3539 k = &p->key_rx_odd;
3540 p->key_rx_odd_active = odd_nonce;
3541 //Read H bit and set keysize accordingly
3542 if (p->rist_gre_version)
3543 {
3544 int bits = (CHECK_BIT(gre->flags2, 6))? 256 : 128;
3545 /* Honor the H bit only when it agrees with the configured
3546 * size (or none was configured): it is unauthenticated wire
3547 * data, and letting it rewrite key_size (e.g. a 192 config
3548 * clobbered to 128/256) desyncs every later rekey. */
3549 if (k->key_size == 0 || k->key_size == (uint32_t)bits)
3550 k->key_size = bits;
3551 }
3552 _librist_crypto_psk_decrypt(k, &recv_buf[nonce_offset], htobe32(seq), rist_gre_version,&recv_buf[payload_offset], &recv_buf[payload_offset], (recv_bufsize - payload_offset));
3553 pthread_mutex_unlock(&p->peer_lock);
3554
3555 if (p == peer)
3556 p = NULL;
3557
3558 if (k->bad_decryption)
3559 return;
3560 } else if (k->key_size && gre_proto != RIST_GRE_PROTOCOL_TYPE_EAPOL && (!has_seq || !has_key)) {
3561 if (now > (peer->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3562 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3563 "We expect encrypted data and the peer sent clear communication, ignoring ...\n");
3564 peer->log_repeat_timer = now;
3565 }
3566 return;
3567 }
3568
3569 if (gre_proto == RIST_GRE_PROTOCOL_TYPE_FULL)
3570 {
3571 payload.type = RIST_PAYLOAD_TYPE_DATA_OOB;
3572 goto protocol_bypass;
3573 }
3574 if (gre_proto == RIST_GRE_PROTOCOL_TYPE_EAPOL)
3575 {
3576 payload.type = RIST_PAYLOAD_TYPE_EAPOL;
3577 goto protocol_bypass;
3578 }
3579
3580 if (gre_proto == RIST_GRE_PROTOCOL_TYPE_VSF) {
3581 if (recv_bufsize < payload_offset + 4) {
3582 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Packet too small: %d bytes, ignoring ...\n", recv_bufsize);
3583 return;
3584 }
3585
3586 uint16_t vsf_proto = 0;
3587 uint16_t vsf_subtype = 0;
3588 vsf_proto = recv_buf[payload_offset] << 8 | recv_buf[payload_offset +1];
3589 vsf_subtype = recv_buf[payload_offset + 2] << 8 | recv_buf[payload_offset +3];
3590
3591 payload_offset += 4;
3592
3593 if (vsf_proto != 0) {//0 = RIST, rest: reserved
3594 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Receiving unknown VSF Proto\n");
3595 return;
3596 }
3597
3598 if (vsf_subtype == 0) {
3599 gre_proto = RIST_GRE_PROTOCOL_TYPE_REDUCED;
3600 } else if (vsf_subtype >= 0x8000){//Control messages
3601 if (vsf_subtype == 0x8000) {
3602 gre_proto = RIST_GRE_PROTOCOL_TYPE_KEEPALIVE;
3603 } else if (vsf_subtype == 0x8001) {
3604 /* Flow Attribute (Main Profile VSF extension) — not parsed here */
3605 return;
3606 } else if (vsf_subtype == RIST_VSF_PROTOCOL_SUBTYPE_BUFFER_NEGOTIATION) {
3607 gre_proto = RIST_VSF_PROTOCOL_SUBTYPE_BUFFER_NEGOTIATION;
3608 } else {
3609 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Receiving unknown RIST control packet\n");
3610 return;
3611 }
3612 } else {
3613 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Receiving unknown RIST packet\n");
3614 return;
3615 }
3616 }
3617
3618 if (gre_proto != RIST_GRE_PROTOCOL_TYPE_REDUCED)
3619 goto protocol_bypass;
3620
3621 if (recv_bufsize < payload_offset + 4) {
3622 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Packet too small: %d bytes, ignoring ...\n", recv_bufsize);
3623 return;
3624 }
3625
3626 /* Map the first subheader and rtp payload area to our structure */
3627 payload.src_port = recv_buf[payload_offset] << 8 | recv_buf[payload_offset +1];
3628 payload.dst_port = recv_buf[payload_offset +2] << 8 | recv_buf[payload_offset +3];
3629 payload_offset += 4;
3630 }
3631
3632 protocol_bypass:
3633 if (!p)
3634 p = _librist_peer_match_peer_addr(peer, family, addr);
3635
3636 /* The RTP header only exists on the data path (Simple profile or
3637 * Main-profile REDUCED); leave the pointer NULL elsewhere so a
3638 * stray deref shows up at compile/run time instead of silently
3639 * reading past recv_bufsize on a short FULL/EAPOL/KEEPALIVE
3640 * datagram. */
3641 struct rist_rtp_hdr *rtp = NULL;
3642 if (cctx->profile == RIST_PROFILE_SIMPLE || gre_proto == RIST_GRE_PROTOCOL_TYPE_REDUCED) {
3643 if (recv_bufsize < payload_offset + sizeof(struct rist_rtp_hdr))
3644 {
3645 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Packet too small for RTP header: %zu bytes, ignoring ...\n", recv_bufsize);
3646 return;
3647 }
3648 rtp = (struct rist_rtp_hdr *)&recv_buf[payload_offset];
3649 /* Double check for a valid rtp header */
3650 if ((rtp->flags & 0xc0) != 0x80)
3651 {
3652 if (!p)
3653 p = peer;
3654 if (now > (p->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
3655 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Malformed packet, rtp flag value is %02x instead of 0x80.\n",
3656 rtp->flags);
3657 p->log_repeat_timer = now;
3658 }
3659
3660 if (k && k->key_size > 0) {
3661 if (k->bad_count++ > 5) {
3662 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Disabling packet processing till new NONCE\n");
3663 k->bad_decryption = true;
3664 }
3665 }
3666 return;
3667 }
3668 /* A packet that decrypts to a valid RTP header proves the key is
3669 * healthy; decay the strike counter so a few garbage packets mixed
3670 * into good traffic can't accumulate into a lockout. */
3671 if (k && k->bad_count)
3672 k->bad_count = 0;
3673 }
3674
3675
3676 if (!p && (peer->listening || peer->multicast_sender) && (gre_proto == RIST_GRE_PROTOCOL_TYPE_REDUCED || gre_proto == RIST_GRE_PROTOCOL_TYPE_KEEPALIVE || gre_proto == RIST_GRE_PROTOCOL_TYPE_FULL || cctx->profile == RIST_PROFILE_SIMPLE)) {
3677 /* No match, new peer creation when on listening mode */
3678 p = peer_initialize(NULL, peer->sender_ctx, peer->receiver_ctx);
3679 p->handled_first = false;
3680 p->adv_peer_id = ++cctx->peer_counter;
3681 // Copy settings and init/update global variables that depend on settings
3682 p->parent = peer;
3683 peer_copy_settings(peer, p);
3684 if (cctx->profile == RIST_PROFILE_SIMPLE) {
3685 if (peer->address_family == AF_INET) {
3686 p->remote_port = htons( ((struct sockaddr_in *)addr)->sin_port);
3687 } else {
3688 p->remote_port = htons( ((struct sockaddr_in6 *)addr)->sin6_port);
3689 }
3690 p->local_port = peer->local_port;
3691 }
3692 else if (peer->receiver_ctx){
3693 // TODO: what happens if the first packet is a keepalive?? are we caching the wrong port?
3694 p->remote_port = payload.src_port;
3695 p->local_port = payload.dst_port;
3696 } else {
3697 p->remote_port = peer->remote_port;
3698 p->local_port = peer->local_port;
3699 }
3700
3701 // TODO: what if sender mode and flow_id != 0 and p->adv_flow_id != flow_id
3702 p->address_family = family;
3703 p->address_len = addrlen;
3704 p->listening = 0;
3705 p->is_rtcp = peer->is_rtcp;
3706 p->is_data = peer->is_data;
3707 p->peer_data = p;
3708 if (peer->multicast_sender)
3709 p->peer_data = peer->peer_data;
3710 memcpy(&p->u.address, addr, addrlen);
3711 p->sd = peer->sd;
3712 p->authenticated = false;
3713 // Copy the event handler reference to prevent the creation of a new one (they are per socket)
3714 p->event_recv = peer->event_recv;
3715 char incoming_ip_string_buffer[INET6_ADDRSTRLEN];
3716 char *incoming_ip_string = get_ip_str(&p->u.address, &incoming_ip_string_buffer[0], INET6_ADDRSTRLEN);
3717 #if HAVE_SRP_SUPPORT
3718 eap_clone_ctx(peer->eap_ctx, p);
3719 eap_set_ip_string(p->eap_ctx, incoming_ip_string_buffer);
3720 if (p->multicast_receiver && p->eap_ctx) {
3721 _librist_proto_eap_start(p->eap_ctx);
3722 }
3723 #endif
3724 // Optional validation of connecting sender
3725 if (cctx->auth.conn_cb) {
3726
3727 char parent_ip_string_buffer[INET6_ADDRSTRLEN];
3728 char *parent_ip_string = get_ip_str(&p->parent->u.address, &parent_ip_string_buffer[0], INET6_ADDRSTRLEN);
3729 if (!parent_ip_string){
3730 parent_ip_string = "";
3731 }
3732
3733 uint16_t parent_port = 0;
3734 if (p->parent->u.storage.ss_family == AF_INET)
3735 parent_port = htons(p->parent->u.inaddr.sin_port);
3736 else
3737 parent_port = htons(p->parent->u.inaddr6.sin6_port);
3738
3739 // Real source port vs virtual source port
3740 if (cctx->profile == RIST_PROFILE_SIMPLE)
3741 port = p->remote_port;
3742 if (incoming_ip_string) {
3743 if (cctx->auth.conn_cb(cctx->auth.arg,incoming_ip_string,port,parent_ip_string, parent_port, p)) {
3744 free(p->eap_ctx);
3745 free(p);
3746 return;
3747 }
3748 }
3749 }
3750
3751 if (peer->receiver_mode)
3752 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Enabling keepalive for peer %d\n", p->adv_peer_id);
3753 else {
3754 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Enabling reverse keepalive for peer %d\n", p->adv_peer_id);
3755 if (p->is_rtcp)
3756 sender_peer_append(peer->sender_ctx, p);
3757 }
3758 p->send_keepalive = true;
3759 p->rist_gre_version = rist_gre_version;
3760 if (cctx->profile > RIST_PROFILE_SIMPLE
3761 #if HAVE_SRP_SUPPORT
3762 && ((p->eap_ctx && eap_is_authenticated(p->eap_ctx)) || !p->eap_ctx)
3763 #endif
3764 ) {
3765 //Answer their keep alive with one from us
3766 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
3767 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
3768 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
3769 if (p->rist_gre_version >= 2) {
3770 uint16_t sender_max_buffer = 0;
3771 if (p->sender_ctx != NULL) {
3772 sender_max_buffer = p->sender_ctx->sender_recover_min_time;
3773 } else if (peer->config.reflector && peer->listening && !peer->multicast_receiver) {
3774 struct rist_peer *child = peer->child;
3775 while (child) {
3776 if (child->is_reflector_publisher && child->sender_max_buffer_ticks > 0) {
3777 sender_max_buffer = (uint16_t)(child->sender_max_buffer_ticks / RIST_CLOCK);
3778 break;
3779 }
3780 child = child->sibling_next;
3781 }
3782 }
3783 if (sender_max_buffer > 0) {
3784 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3785 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3786 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3787 }
3788 }
3789 }
3790 peer_append(p);
3791 }
3792 if (!p)
3793 return;
3794
3795 //Only allow upgrade of gre version
3796 if (p->rist_gre_version < rist_gre_version
3797 #if HAVE_SRP_SUPPORT
3798 && ((p->eap_ctx && eap_is_authenticated(p->eap_ctx)) || !p->eap_ctx)
3799 #endif
3800 ) {
3801 //Our GRE version got upgraded, try kickstarting buffer negotiation
3802 if (p->rist_gre_version == RIST_GRE_VERSION_MIN) {
3803 uint16_t sender_max_buffer = 0;
3804 if (p->sender_ctx != NULL) {
3805 sender_max_buffer = p->sender_ctx->sender_recover_min_time;
3806 } else if (peer->config.reflector && peer->listening && !peer->multicast_receiver) {
3807 struct rist_peer *child = peer->child;
3808 while (child) {
3809 if (child->is_reflector_publisher && child->sender_max_buffer_ticks > 0) {
3810 sender_max_buffer = (uint16_t)(child->sender_max_buffer_ticks / RIST_CLOCK);
3811 break;
3812 }
3813 child = child->sibling_next;
3814 }
3815 }
3816 if (sender_max_buffer > 0) {
3817 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3818 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3819 _librist_proto_gre_send_buffer_negotiation(p, sender_max_buffer, 0);
3820 }
3821 }
3822 p->rist_gre_version = rist_gre_version;
3823 }
3824
3825 if (gre_proto == RIST_GRE_PROTOCOL_TYPE_KEEPALIVE) {
3826 struct rist_keepalive_info info;
3827 if (_librist_proto_gre_parse_keepalive(&recv_buf[payload_offset], recv_bufsize - payload_offset, &info) != 0) {
3828 p->last_pkt_received = now;
3829 return;
3830 }
3831 if (memcmp(&info.ka, &p->data, sizeof(peer->data)) != 0) {
3832 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
3833 "New keepalive received. MAC: %x:%x:%x:%x:%x:%x"
3834 " X: %d R: %d B: %d A: %d P: %d E: %d L: %d: N: %d"
3835 " D: %d T: %d V: %d: J: %d F: %d\n",
3836 info.mac[0], info.mac[1], info.mac[2],
3837 info.mac[3], info.mac[4], info.mac[5],
3838 info.x, info.r, info.b, info.a,
3839 info.p, info.e, info.l, info.e,
3840 info.n, info.d, info.t, info.v,
3841 info.j, info.f);
3842 if (info.json_len) {
3843 /* %.*s precision must be int. Truncate the log line if some
3844 * weird future caller hands us a giant blob. */
3845 int json_log_len = info.json_len > (size_t)INT_MAX ? INT_MAX : (int)info.json_len;
3846 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Keepalive JSON:\n%.*s\n", json_log_len, info.json);
3847 }
3848 //TODO: add callback?
3849 /* TR-06-3 Section 9: detect Advanced Profile support via I bit */
3850 if (info.adv_i && !p->remote_supports_advanced) {
3851 p->remote_supports_advanced = true;
3852 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
3853 "Peer %u advertises Advanced Profile capability (I=1)\n",
3854 p->adv_peer_id);
3855 }
3856 memcpy(&p->data, &info.ka, sizeof(peer->data));
3857 }
3858 if (p->receiver_ctx &&
3859 p->receiver_ctx->merge_mode == LIBRIST_MERGE_MODE_AUTO) {
3860 struct rist_flow *fl = cctx->FLOWS;
3861 while (fl) {
3862 if (fl->merge_auto_enabled != (bool)info.l) {
3863 fl->merge_auto_enabled = (bool)info.l;
3864 rist_log_priv(cctx, RIST_LOG_INFO,
3865 "merge=auto: peer %s pair-split; "
3866 "merge %s for flow %u\n",
3867 info.l ? "advertises" : "stopped advertising",
3868 info.l ? "enabled" : "disabled",
3869 fl->flow_id);
3870 }
3871 fl = fl->next;
3872 }
3873 }
3874 p->last_pkt_received = now;
3875 return;
3876 }
3877
3878 if (gre_proto == RIST_VSF_PROTOCOL_SUBTYPE_BUFFER_NEGOTIATION) {
3879 uint16_t sender_max_buffer;
3880 uint16_t client_current_buffer;
3881 if (_librist_proto_gre_parse_buffer_negotiation(p, &recv_buf[payload_offset], recv_bufsize - payload_offset, &sender_max_buffer, &client_current_buffer) != 0)
3882 return;
3883
3884 p->is_reflector_publisher = sender_max_buffer != 0;
3885
3886 if (p->receiver_ctx != NULL && sender_max_buffer != 0) {
3887 if (sender_max_buffer < p->config.recovery_length_min) {
3888 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Sender max buffer %u smaller than min buffer %u, disabling buffer negotiation!\n", sender_max_buffer, p->config.recovery_length_min);
3889 p->sender_max_buffer_ticks = 0;
3890 } else {
3891 p->sender_max_buffer_ticks = sender_max_buffer * RIST_CLOCK;
3892 if (peer->config.reflector && peer->listening && !peer->multicast_receiver) {
3893 struct rist_peer *child = peer->child;
3894 while (child) {
3895 if (child != p && !child->is_reflector_publisher && child->rist_gre_version >= 2) {
3896 _librist_proto_gre_send_buffer_negotiation(child, sender_max_buffer, 0);
3897 }
3898 child = child->sibling_next;
3899 }
3900 }
3901 }
3902 }
3903 return;
3904 }
3905
3906 uint32_t rtp_time = 0;
3907 uint64_t source_time = 0;
3908 uint8_t payload_type = 0;
3909 int ts_null_bytes = 0;
3910
3911 if (cctx->profile == RIST_PROFILE_SIMPLE || gre_proto == RIST_GRE_PROTOCOL_TYPE_REDUCED) {
3912 // This is for legacy compatibility (to be removed later)
3913 if (rtp->payload_type == PTYPE_XR_LEGACY)
3914 rtp->payload_type = PTYPE_XR;
3915 payload_type = rtp->payload_type;
3916 uint8_t payload_type_nomarker_bit = rtp->payload_type & 127;
3917 // Finish defining the payload (we assume reduced header)
3918 // The check is for 200-205 and 72-77 (payload type minus 128)
3919 if(payload_type_nomarker_bit < 72 || payload_type_nomarker_bit > 77) {
3920 // This will mis-clasify rtp packets with payload types 72-77 as rtcp. However,
3921 // this range is reserved for "RTCP conflict avoidance” on RFC4855. Furthermore,
3922 // we are already using 77 for PTYPE_XR
3923 // Remove the marker bit as it is not part of the payload type for non-rtcp data
3924 payload_type = payload_type_nomarker_bit;
3925 flow_id = be32toh(rtp->ssrc);
3926 // If this is a retry, extract the information and restore correct flow_id
3927 if (flow_id & 1UL)
3928 {
3929 flow_id ^= 1UL;
3930 retry = 1;
3931 }
3932 payload_offset += sizeof(*rtp);
3933 uint8_t *data_payload = &recv_buf[payload_offset];
3934 payload.size = recv_bufsize - (payload_offset);
3935 payload.data = (void *)data_payload;
3936
3937 if (CHECK_BIT(rtp->flags, 4)) {
3938 // X bit promises an extension header, the packet may not actually have it
3939 if (payload.size < sizeof(struct rist_rtp_hdr_ext)) {
3940 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
3941 "Packet too small for RTP extension header: %zu bytes, ignoring ...\n",
3942 payload.size);
3943 return;
3944 }
3945 uint8_t *data_payload_out = &recv_buf_npd[0];
3946 //RTP extension header
3947 struct rist_rtp_hdr_ext * hdr_ext = (struct rist_rtp_hdr_ext *)(&recv_buf[payload_offset]);
3948 payload.size -= sizeof(*hdr_ext);
3949 data_payload += sizeof(*hdr_ext);
3950 payload.data = (void *)data_payload;
3951 if (memcmp(&hdr_ext->identifier, "RI", 2) == 0 && be16toh(hdr_ext->length) == 1)
3952 {
3953 // Null packet expansion (use a separate buffer and replace it when we had nulls)
3954 if (CHECK_BIT(hdr_ext->flags, 7)) {
3955 ts_null_bytes = expand_null_packets(data_payload, data_payload_out, &payload.size, hdr_ext->npd_bits);
3956 if (ts_null_bytes < 0)
3957 ts_null_bytes = 0; /* expansion failed; deliver unexpanded */
3958 else
3959 payload.data = (void *)data_payload_out;
3960 }
3961 }
3962 }
3963 payload.type = RIST_PAYLOAD_TYPE_DATA_RAW;
3964 } else {
3965 // remap the rtp payload to the correct rtcp header
3966 struct rist_rtcp_hdr *rtcp = (struct rist_rtcp_hdr *)rtp;
3967 //payload_offset += sizeof(*rtcp);
3968 uint8_t *data_payload = &recv_buf[payload_offset];
3969 payload.size = recv_bufsize - (payload_offset);
3970 payload.data = (void *)data_payload;
3971 flow_id = be32toh(rtcp->ssrc);
3972 payload.type = RIST_PAYLOAD_TYPE_RTCP;
3973 }
3974 }
3975
3976 // We need this protocol bypass to manage keepalives of any kind,
3977 // they need to trigger peering at the bottom of this function
3978
3979 ;
3980 bool failed_eap = false;
3981 if (p->eap_authentication_state != 1 && p->dead) {
3982 uint64_t dead_time = (now - p->last_pkt_received);
3983 p->dead = false;
3984 //Only used on main profile
3985 if (p->parent)
3986 ++p->parent->child_alive_count;
3987 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
3988 "Peer %u was dead for %"PRIu64" ms and it is now alive again\n",
3989 p->adv_peer_id, dead_time / RIST_CLOCK);
3990 if (p->peer_data)
3991 p->peer_data->dead = 0;
3992 }
3993 p->last_pkt_received = now;
3994 if (ts_null_bytes)
3995 p->stats_receiver_instant.ts_null++;
3996 if (p->flow)
3997 p->flow->last_recv_ts = now;
3998 payload.peer = p;
3999 if (cctx->profile == RIST_PROFILE_SIMPLE)
4000 {
4001 payload.src_port = p->remote_port;
4002 payload.dst_port = p->local_port;
4003 }
4004 //rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Port is %d !!!!!\n", addr4.sin_port);
4005 #if HAVE_SRP_SUPPORT
4006 if (payload.type != RIST_PAYLOAD_TYPE_EAPOL && p->eap_ctx && !eap_is_authenticated(p->eap_ctx))
4007 {
4008 if (now > (p->log_repeat_timer + RIST_LOG_QUIESCE_TIMER)) {
4009 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Waiting for EAP authentication to happen for peer connecting on port %u\n", ((struct sockaddr_in *)addr)->sin_port);
4010 p->log_repeat_timer = now;
4011 }
4012 // Do not process non EAP packets until the peer has been authenticated!
4013 return;
4014 }
4015 #endif
4016 //Cobalt's implementation has an identity crisis in it's response to our echo packets & set's the wrong SSRC (ours) on the RTP packet. Work around this flaw.
4017 if (peer && peer->receiver_ctx && flow_id == peer->peer_ssrc && peer->flow && peer->flow->flow_id && peer->flow->flow_id != flow_id)
4018 flow_id = peer->flow->flow_id;
4019
4020 switch(payload.type) {
4021 case RIST_PAYLOAD_TYPE_UNKNOWN:
4022 // Do nothing ...TODO: check for port changes?
4023 break;
4024 case RIST_PAYLOAD_TYPE_DATA_OOB:
4025 payload.size = recv_bufsize - payload_offset;
4026 payload.data = (void *)(recv_buf + payload_offset);
4027 rist_recv_oob_data(p, &payload);
4028 break;
4029 case RIST_PAYLOAD_TYPE_RTCP:
4030 if (p->is_rtcp && !p->handled_first) {
4031 rist_new_connection(peer, p, flow_id);
4032 if (!peer->receiver_mode) {
4033 // only profile > simple
4034 // authenticate sender now that we have an address
4035 rist_peer_authenticate(p);
4036 }
4037 p->handled_first = true;
4038 }
4039 RIST_FALLTHROUGH;
4040 case RIST_PAYLOAD_TYPE_RTCP_NACK:
4041 /* Need this for interop, we should move this to a per flow level eventually once we support multiple flows on a single peer*/
4042 if (RIST_UNLIKELY(p->receiver_ctx && p->local_port != payload.dst_port)) {
4043 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Updating peer virt dst port to match remote source port: %u\n", payload.src_port);
4044 p->local_port = payload.dst_port;
4045 p->remote_port = payload.src_port;
4046 }
4047 rist_recv_rtcp(p, seq, flow_id, &payload);
4048 break;
4049 case RIST_PAYLOAD_TYPE_DATA_RAW:
4050 if (p->is_data && !p->handled_first) {
4051 rist_new_connection(peer, p, flow_id);
4052 p->handled_first = true;
4053 }
4054 rtp_time = be32toh(rtp->ts);
4055 if (RIST_UNLIKELY(p->config.timing_mode == RIST_TIMING_MODE_ARRIVAL))
4056 source_time = timestampNTP_u64();
4057 else
4058 source_time = convertRTPtoNTP(payload_type, time_extension, rtp_time);
4059 seq = (uint32_t)be16toh(rtp->seq);
4060 if (RIST_UNLIKELY(!p->receiver_mode))
4061 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG,
4062 "Received data packet on sender, ignoring (%d bytes)...\n", payload.size);
4063 else {
4064 size_t received_bytes = recv_bufsize - payload_offset; //use the unexpanded size to show real BW
4065 rist_calculate_bitrate(received_bytes, &p->bw);
4066 rist_receiver_recv_data(p, seq, flow_id, source_time, now, &payload, retry, payload_type, received_bytes, ts_null_bytes, true);
4067 }
4068 break;
4069 case RIST_PAYLOAD_TYPE_EAPOL:
4070 #if HAVE_SRP_SUPPORT
4071 if (p->eap_ctx == NULL) {
4072 rist_log_priv(get_cctx(p), RIST_LOG_ERROR, "EAP authentication requested but credentials have not been configured!\n");
4073 }
4074 else {
4075 int eapret = 0;
4076 if ((eapret = eap_process_eapol(p->eap_ctx,
4077 (recv_buf + payload_offset),
4078 (recv_bufsize - payload_offset))) < 0) {
4079 rist_log_priv(get_cctx(p), RIST_LOG_ERROR, "Failed to process EAPOL pkt, return code: %i\n", eapret);
4080 /* eap_process_eapol returns a negative code; was being
4081 * compared against +255 and never matched, so failed_eap
4082 * was effectively dead. */
4083 if (eapret == EAP_AUTH_TERMINATED)
4084 failed_eap = true;
4085 }
4086 else if (p->eap_authentication_state != 2 && eap_is_authenticated(p->eap_ctx)) {
4087 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
4088 "Peer %d EAP Authentication succeeded\n", peer->adv_peer_id);
4089 p->eap_authentication_state = 2;
4090 /* A caller-sender leg that re-authenticated after going
4091 * silent (see try_caller_socket_rebind) cleared its
4092 * connection-level authenticated flag to leave the bond
4093 * while down. Restore it now so the weighted balancer
4094 * folds the leg back in at full weight. */
4095 if (!p->receiver_mode && !p->listening && !p->authenticated)
4096 rist_peer_authenticate(p);
4097 //First authentication, so send keepalive
4098 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
4099 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
4100 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
4101 if (p->rist_gre_version >= 2 && p->sender_ctx != NULL) {
4102 _librist_proto_gre_send_buffer_negotiation(p, peer->sender_ctx->sender_recover_min_time, 0);
4103 _librist_proto_gre_send_buffer_negotiation(p, peer->sender_ctx->sender_recover_min_time, 0);
4104 _librist_proto_gre_send_buffer_negotiation(p, peer->sender_ctx->sender_recover_min_time, 0);
4105 }
4106 /* Emit the binding SDES now, not on the next periodic
4107 * tick, so it precedes this leg's first forwarded data. */
4108 if (!p->receiver_mode)
4109 rist_sender_periodic_rtcp(p);
4110 }
4111 }
4112 #else
4113 if (peer->eap_ctx == NULL) {
4114 rist_log_priv(get_cctx(p), RIST_LOG_ERROR, "EAP authentication requested but EAP support not available!\n");
4115 failed_eap = true;
4116 }
4117 #endif
4118 if (failed_eap) {
4119 //A previously authenticated client fails authentication, and we're running multicast, so we need to rollover the passphrase
4120 #if HAVE_SRP_SUPPORT
4121 if (p->eap_authentication_state == 2 && p->parent && p->parent->multicast_sender) {
4122 char newpass[65];
4123 newpass[64] = '\0';
4124 if (_librist_crypto_random_get_string(newpass, sizeof(newpass)-1) == 0) {
4125 rist_peer_update_secret(p->parent, newpass);
4126 }
4127 }
4128 #endif
4129 p->eap_authentication_state = 1;
4130 kill_peer(p);
4131 }
4132 // Never create new peers using EAP packets (exit loop here)
4133 return;
4134 break;
4135 default:
4136 rist_recv_rtcp(p, seq, flow_id, &payload);
4137 break;
4138 }
4139 return;
4140 }
4141
4142 int rist_oob_enqueue(struct rist_common_ctx *ctx, struct rist_peer *peer, const void *buf, size_t len)
4143 {
4144 if (RIST_UNLIKELY(!ctx->oob_data_enabled)) {
4145 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
4146 "Trying to send oob but oob was not enabled\n");
4147 return -1;
4148 }
4149 else if ((ctx->oob_queue_write_index + 1) == ctx->oob_queue_read_index)
4150 {
4151 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR,
4152 "oob queue is full (%zu bytes), try again later\n", ctx->oob_queue_bytesize);
4153 return -1;
4154 }
4155
4156 /* insert into oob fifo queue */
4157 pthread_rwlock_wrlock(&ctx->oob_queue_lock);
4158 ctx->oob_queue[ctx->oob_queue_write_index] = rist_new_buffer(ctx, buf, len, RIST_PAYLOAD_TYPE_DATA_OOB, 0, 0, 0, 0);
4159 if (RIST_UNLIKELY(!ctx->oob_queue[ctx->oob_queue_write_index])) {
4160 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "\t Could not create oob packet buffer, OOM\n");
4161 pthread_rwlock_unlock(&ctx->oob_queue_lock);
4162 return -1;
4163 }
4164 ctx->oob_queue[ctx->oob_queue_write_index]->peer = peer;
4165 ctx->oob_queue_write_index = (ctx->oob_queue_write_index + 1);
4166 ctx->oob_queue_bytesize += len;
4167 pthread_rwlock_unlock(&ctx->oob_queue_lock);
4168
4169 return 0;
4170 }
4171
4172 static void rist_oob_dequeue(struct rist_common_ctx *ctx, int maxcount)
4173 {
4174 int counter = 0;
4175
4176 while (1) {
4177 // If we fall behind, only empty 100 every 5ms (master loop)
4178 if (counter++ > maxcount) {
4179 break;
4180 }
4181
4182 if (ctx->oob_queue_read_index == ctx->oob_queue_write_index) {
4183 //rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
4184 // "\tWe are all up to date, index is %u/%u and bytes = %zu\n",
4185 // ctx->oob_queue_read_index, ctx->oob_queue_write_index, ctx->oob_queue_bytesize);
4186 break;
4187 }
4188
4189 struct rist_buffer *oob_buffer = ctx->oob_queue[ctx->oob_queue_read_index];
4190 if (!oob_buffer->data) {
4191 rist_log_priv(ctx, RIST_LOG_ERROR, "Null oob buffer, skipping!!!\n");
4192 ctx->oob_queue_read_index++;
4193 continue;
4194 }
4195
4196 uint8_t *payload = oob_buffer->data;
4197 struct rist_peer *p = oob_buffer->peer;
4198
4199 /* The stashed peer may have been freed (NAT rebind / timeout) since
4200 * rist_oob_write() queued it; verify it is still live and hold
4201 * peerlist_lock across the send so it can't be freed under us. */
4202 pthread_mutex_lock(&ctx->peerlist_lock);
4203 bool peer_alive = false;
4204 for (struct rist_peer *pp = ctx->PEERS; pp != NULL; pp = pp->next) {
4205 if (pp == p) {
4206 peer_alive = true;
4207 break;
4208 }
4209 }
4210 if (!peer_alive) {
4211 pthread_mutex_unlock(&ctx->peerlist_lock);
4212 rist_log_priv(ctx, RIST_LOG_WARN, "OOB: target peer no longer exists, dropping packet\n");
4213 ctx->oob_queue_bytesize -= oob_buffer->size;
4214 ctx->oob_queue_read_index++;
4215 continue;
4216 }
4217 if (p->listening) {
4218 /* Listener peer: send OOB to all alive child peers. */
4219 struct rist_peer *child = p->child;
4220 bool sent = false;
4221 while (child) {
4222 if (!child->dead) {
4223 rist_send_common_rtcp(child, RIST_PAYLOAD_TYPE_DATA_OOB, &payload[RIST_MAX_PAYLOAD_OFFSET],
4224 oob_buffer->size, 0, 0, 0, 0, 0);
4225 sent = true;
4226 }
4227 child = child->sibling_next;
4228 }
4229 if (!sent)
4230 rist_log_priv(ctx, RIST_LOG_WARN, "OOB: listener peer has no alive children, dropping\n");
4231 } else {
4232 rist_send_common_rtcp(p, RIST_PAYLOAD_TYPE_DATA_OOB, &payload[RIST_MAX_PAYLOAD_OFFSET],
4233 oob_buffer->size, 0, 0, 0, 0, 0);
4234 }
4235 pthread_mutex_unlock(&ctx->peerlist_lock);
4236 ctx->oob_queue_bytesize -= oob_buffer->size;
4237 ctx->oob_queue_read_index++;
4238 }
4239
4240 return;
4241 }
4242
4243 static void sender_send_nacks(struct rist_sender *ctx)
4244 {
4245 // Send retries from the queue (if any)
4246 uint32_t counter = 1;
4247 int errors = 0;
4248 size_t total_bytes = 0;
4249
4250 if (ctx->max_nacksperloop == 0)
4251 return; // No peers yet
4252
4253 // Send nack retries. Stop when the retry queue is empty or when the data in the
4254 // send fifo queue grows to 10 packets (we do not want to harm real-time data)
4255 // We also stop on maxcounter (jitter control and max bandwidth protection)
4256 size_t queued_items = (atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire) - atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire)) &ctx->sender_queue_max;
4257 uint64_t start_time = timestampNTP_u64();
4258 while (queued_items < 10) {
4259 ssize_t ret = rist_retry_dequeue(ctx);
4260 if (ret == 0) {
4261 // ret == 0 is valid (nothing to send)
4262 break;
4263 } else if (ret < 0) {
4264 errors++;
4265 } else {
4266 total_bytes += ret;
4267 counter++;
4268 }
4269 if (counter > ctx->max_nacksperloop) {
4270 break;
4271 }
4272 if (((timestampNTP_u64() - start_time) / RIST_CLOCK) > 100)
4273 {
4274 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Nack processing loop took longer than 100ms. Something is wrong!\n");
4275 // TODO: clear out the nack queue here?
4276 break;
4277 }
4278 queued_items = (atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire) - atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire)) & ctx->sender_queue_max;
4279 }
4280 if (ctx->common.debug && 2 * (counter - 1) > ctx->max_nacksperloop)
4281 {
4282 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
4283 "Had to process multiple fifo nacks: c=%d, e=%d, b=%zu, s=%zu, m=%zu\n",
4284 counter - 1, errors, total_bytes, rist_get_sender_retry_queue_size(ctx),
4285 ctx->max_nacksperloop);
4286 }
4287
4288 }
4289
4290 static void sender_send_data(struct rist_sender *ctx, int maxcount)
4291 {
4292 int counter = 0;
4293
4294 while (1) {
4295 // If we fall behind, only empty 100 every 5ms (master loop)
4296 if (counter++ > maxcount) {
4297 break;
4298 }
4299
4300 size_t idx = ((size_t)atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire) + 1)& (ctx->sender_queue_max-1);
4301
4302 if (idx == (size_t)atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_relaxed)) {
4303 //rist_log_priv(&ctx->common, RIST_LOG_ERROR,
4304 // "\t[GOOD] We are all up to date, index is %d\n",
4305 // ctx->sender_queue_read_index);
4306 break;
4307 }
4308
4309 atomic_store_explicit(&ctx->sender_queue_read_index, idx, memory_order_release);
4310 if (RIST_UNLIKELY(ctx->sender_queue[idx] == NULL)) {
4311 ctx->sender_queue_size--;
4312 // This should never happen!
4313 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
4314 "FIFO data block was null (read/write) (%zu/%zu)\n",
4315 idx, atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_relaxed));
4316 continue;
4317 } else {
4318 struct rist_buffer *buffer = ctx->sender_queue[idx];
4319 // Send fifo data (handshake and data payloads)
4320 if (buffer->type == RIST_PAYLOAD_TYPE_RTCP) {
4321 // TODO can we ever have a null or dead buffer->peer?
4322 uint8_t *payload = buffer->data;
4323 rist_send_common_rtcp(buffer->peer, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, 0, ctx->sender_queue[idx]->ts_null_bytes);
4324 buffer->seq = ctx->common.seq;
4325 buffer->seq_rtp = ctx->common.seq_rtp;
4326 }
4327 else {
4328 rist_sender_send_data_balanced(ctx, buffer);
4329 if (ctx->common.profile == RIST_PROFILE_ADVANCED) {
4330 ctx->seq_index[buffer->seq & (ctx->sender_queue_max - 1)] = (uint32_t)idx;
4331 /* Mirror into the RTP index so a Main-downgraded peer's
4332 * 16-bit NACK can still resolve this packet. Dead data for
4333 * Advanced-negotiated peers (never read for them). */
4334 if (ctx->seq_rtp_index)
4335 ctx->seq_rtp_index[buffer->seq_rtp] = (uint32_t)idx;
4336 } else
4337 ctx->seq_index[buffer->seq_rtp] = (uint32_t)idx;
4338 }
4339 }
4340
4341 // Keep only sender_buffer_size items in buffer (this controls the size of the sender queue used on retries)
4342 int reduce = 0;
4343 do {
4344 size_t delete_idx = ((size_t)atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire) - ctx->sender_buffer_size) & (ctx->sender_queue_max - 1);
4345 ctx->sender_queue_delete_index = delete_idx;
4346 if (ctx->sender_queue[delete_idx] && ctx->sender_queue[delete_idx]->data) {
4347 /* perform the deletion based on the buffer size plus twice the configured/measured avg_rtt */
4348 uint64_t delay = (timestampNTP_u64() - ctx->sender_queue[delete_idx]->time) / RIST_CLOCK;
4349 ctx->sender_queue_timelength = delay;
4350 if (delay < ctx->sender_recover_min_time) {
4351 if (ctx->sender_buffer_size < ctx->sender_queue_max - 1)
4352 ctx->sender_buffer_size++;
4353 reduce = 0;
4354 break;
4355 }
4356 else if (reduce == 0 && delay > ctx->sender_recover_min_time * 1.1) {
4357 // Shrink the buffer size by one (packet is old enough)
4358 if (ctx->sender_buffer_size > 0) {
4359 reduce = 1;
4360 ctx->sender_buffer_size--;
4361 }
4362 }
4363 else {
4364 // We are not reducing the buffer size a second time
4365 reduce = 0;
4366 }
4367 ctx->sender_queue_bytesize -= ctx->sender_queue[delete_idx]->size;
4368 ctx->sender_queue_size--;
4369 free(ctx->sender_queue[delete_idx]->data);
4370 ctx->sender_queue[delete_idx]->data = NULL;
4371 }
4372 if (ctx->sender_queue[delete_idx]) {
4373 free(ctx->sender_queue[delete_idx]);
4374 ctx->sender_queue[delete_idx] = NULL;
4375 }
4376 } while (reduce && ctx->sender_queue_size > 0);
4377
4378 }
4379 }
4380
4381 static struct rist_peer *peer_initialize(const char *url, struct rist_sender *sender_ctx,
4382 struct rist_receiver *receiver_ctx)
4383 {
4384 struct rist_common_ctx *cctx;
4385 if (receiver_ctx)
4386 cctx = &receiver_ctx->common;
4387 else
4388 cctx = &sender_ctx->common;
4389
4390 struct rist_peer *p = calloc(1, sizeof(*p));
4391 if (!p) {
4392 rist_log_priv(cctx, RIST_LOG_ERROR, "\tNot enough memory creating peer!\n");
4393 return NULL;
4394 }
4395
4396 if (pthread_mutex_init(&p->peer_lock, NULL) != 0) {
4397 rist_log_priv(cctx, RIST_LOG_ERROR, "\tError initializing peer lock!\n");
4398 free(p);
4399 return NULL;
4400 }
4401
4402 if (url) {
4403 p->url = strdup(url);
4404 }
4405
4406 p->receiver_mode = (receiver_ctx != NULL);
4407 p->config.recovery_mode = RIST_RECOVERY_MODE_UNCONFIGURED;
4408 p->rtcp_keepalive_interval = RIST_PING_INTERVAL * RIST_CLOCK;
4409 p->sender_ctx = sender_ctx;
4410 p->receiver_ctx = receiver_ctx;
4411 p->birthtime_local = timestampNTP_u64();
4412 p->handled_first = true;
4413 p->sd = -1;
4414
4415 return p;
4416 }
4417
4418 static PTHREAD_START_FUNC(receiver_pthread_dataout, arg)
4419 {
4420 struct rist_flow *flow = (struct rist_flow *)arg;
4421 struct rist_receiver *receiver_ctx = (void *)flow->receiver_id;
4422
4423 #ifndef _WIN32
4424 int prio_max = sched_get_priority_max(SCHED_RR);
4425 struct sched_param param = { 0 };
4426 param.sched_priority = prio_max;
4427 if (pthread_setschedparam(pthread_self(), SCHED_RR, &param) != 0)
4428 rist_log_priv(&receiver_ctx->common, RIST_LOG_WARN, "Failed to set data output thread to RR scheduler with prio of %i\n", prio_max);
4429 #else
4430 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
4431 #endif
4432 // Default max jitter is 5ms
4433 int max_output_jitter_ms = flow->max_output_jitter / RIST_CLOCK;
4434 if (max_output_jitter_ms > 100)
4435 max_output_jitter_ms = 100;
4436
4437 rist_log_priv(&receiver_ctx->common, RIST_LOG_INFO, "Starting data output thread with %d ms max output jitter\n", max_output_jitter_ms);
4438
4439 /* Keep one source of truth for the wake ceiling. */
4440 flow->cbr_pacer.max_sleep_ns = (uint64_t)max_output_jitter_ms * 1000000ULL;
4441 flow->cbr_max_hold_us = rist_cbr_hold_us((uint32_t)max_output_jitter_ms);
4442 if (flow->cbr_output)
4443 rist_log_priv(&receiver_ctx->common, RIST_LOG_INFO,
4444 "CBR output pacing enabled, wake interval %u us to %d ms, hold %u us\n",
4445 flow->cbr_output_min_us, max_output_jitter_ms,
4446 flow->cbr_max_hold_us);
4447
4448 pthread_mutex_lock(&(flow->mutex));
4449 uint64_t target_recovery_buffer_size = flow->recovery_buffer_ticks;
4450 pthread_mutex_unlock(&(flow->mutex));
4451
4452 uint64_t next_buffer_adjust_step = timestampNTP_u64() + ONE_SECOND;
4453 uint64_t buffer_adjust_step_time = 0;
4454 int64_t buffer_adjust_step_size = 0;
4455 int buffer_adjust_steps_left = 0;
4456
4457 while (true) {
4458 pthread_mutex_lock(&(flow->mutex));
4459 uint64_t wait_us = (uint64_t)max_output_jitter_ms * 1000;
4460 if (flow->cbr_output) {
4461 uint64_t now_ntp = timestampNTP_u64();
4462 uint64_t arrived = atomic_load_explicit(&flow->cbr_arrived_bytes,
4463 memory_order_relaxed);
4464 uint64_t delta = arrived - flow->cbr_arrived_seen;
4465 flow->cbr_arrived_seen = arrived;
4466 /* Only on real arrivals: feeding zero would close windows during a
4467 * signal loss and average the rate away, and the estimator's outage
4468 * detection keys off the gap between calls. */
4469 if (delta)
4470 rist_pacer_rate_add(&flow->cbr_rate, (size_t)delta,
4471 timestampNTP_to_us(now_ntp));
4472 /* Wake at least twice per datagram interval, once one is known. */
4473 if (flow->cbr_interval_ns) {
4474 uint64_t floor_ns = flow->cbr_interval_ns / 2;
4475 uint64_t ceil_ns = (uint64_t)flow->cbr_output_min_us * 1000;
4476 if (floor_ns < RIST_CBR_OUTPUT_MIN_US_FLOOR * 1000ULL)
4477 floor_ns = RIST_CBR_OUTPUT_MIN_US_FLOOR * 1000ULL;
4478 if (floor_ns > ceil_ns)
4479 floor_ns = ceil_ns;
4480 flow->cbr_pacer.min_sleep_ns = floor_ns;
4481 }
4482 wait_us = rist_pacer_sleep_ns(&flow->cbr_pacer,
4483 timestampNTP_to_ns(now_ntp)) / 1000;
4484 if (!wait_us)
4485 wait_us = 1;
4486 }
4487 int ret = pthread_cond_timedwait_us(&flow->condition, &flow->mutex, wait_us);
4488 if (ret && ret != ETIMEDOUT)
4489 rist_log_priv(&receiver_ctx->common, RIST_LOG_ERROR, "Error %d in receiver data out loop\n", ret);
4490 if (atomic_load_explicit(&flow->shutdown,memory_order_acquire) > 0)
4491 break;
4492 flow->cbr_paced_hold = false;
4493 if (atomic_load_explicit(&flow->receiver_queue_size, memory_order_acquire) > 0) {
4494 receiver_output(receiver_ctx, flow);
4495 }
4496 /* Nothing sent and the pacer was not holding: idle, so don't let the
4497 * schedule accrue due times through the gap. */
4498 if (flow->cbr_output && !flow->cbr_paced_hold)
4499 rist_pacer_reset(&flow->cbr_pacer);
4500
4501 if (flow->flow_auto_buffer_scaling) {
4502 uint64_t now = timestampNTP_u64();
4503 if (target_recovery_buffer_size == flow->recovery_buffer_ticks) {
4504 if (now >= next_buffer_adjust_step) {
4505 if (flow->currently_scaling_buffer) {
4506 flow->currently_scaling_buffer = false;
4507 rist_log_priv(&receiver_ctx->common, RIST_LOG_INFO, "Done rescaling buffer\n");
4508 }
4509 next_buffer_adjust_step += ONE_SECOND;
4510 uint64_t tmp_target_buffer_size = 0;
4511 for (size_t i=0; i < flow->peer_lst_len; i++) {
4512 struct rist_peer *p = flow->peer_lst[i];
4513 if (p->recovery_buffer_ticks > tmp_target_buffer_size) {
4514 tmp_target_buffer_size = p->recovery_buffer_ticks;
4515 }
4516 }
4517
4518 uint64_t diff = target_recovery_buffer_size - tmp_target_buffer_size;
4519 if (tmp_target_buffer_size > target_recovery_buffer_size)
4520 diff = tmp_target_buffer_size - target_recovery_buffer_size;
4521
4522 if (diff > RIST_CLOCK * 15) {
4523 target_recovery_buffer_size = tmp_target_buffer_size;
4524 buffer_adjust_step_size = diff / 100;
4525 buffer_adjust_steps_left = 100;
4526 buffer_adjust_step_time = buffer_adjust_step_size * 8;//Magic factor of 8 to ensure our changes aren't too dramatic
4527 if (flow->recovery_buffer_ticks > target_recovery_buffer_size)
4528 buffer_adjust_step_size *= -1;
4529 next_buffer_adjust_step = now + buffer_adjust_step_time;
4530 if ((target_recovery_buffer_size *2ULL) > flow->session_timeout)
4531 flow->session_timeout = 2ULL * target_recovery_buffer_size;
4532 flow->currently_scaling_buffer = true;
4533 rist_log_priv(&receiver_ctx->common, RIST_LOG_INFO, "Adjusting flow buffer time to %"PRIu64"ms, flow timeout is %"PRIu64"ms\n", tmp_target_buffer_size/ RIST_CLOCK, flow->session_timeout/ RIST_CLOCK);
4534
4535 }
4536 }
4537 } else if (now >= next_buffer_adjust_step) {
4538 flow->recovery_buffer_ticks += buffer_adjust_step_size;
4539 buffer_adjust_steps_left--;
4540 next_buffer_adjust_step += buffer_adjust_step_time;
4541 if (buffer_adjust_steps_left == 0) {
4542 flow->recovery_buffer_ticks = target_recovery_buffer_size;
4543 uint64_t next_min = 2 * ONE_SECOND;
4544 if (flow->recovery_buffer_ticks *1.5 > next_min)
4545 next_min = flow->recovery_buffer_ticks *1.5;
4546 next_buffer_adjust_step = now + 2 *ONE_SECOND;// We don't want to adjust to often, so keep 2 seconds between adjustments
4547 }
4548 }
4549 }
4550
4551 pthread_mutex_unlock(&(flow->mutex));
4552 }
4553 rist_log_priv(&receiver_ctx->common, RIST_LOG_INFO, "Data output thread shutting down\n");
4554 atomic_store_explicit(&flow->shutdown, 2, memory_order_release);
4555 pthread_mutex_unlock(&flow->mutex);
4556 return 0;
4557 }
4558
4559 static void rist_peer_periodic(struct rist_peer *p, uint64_t now) {
4560 bool adv_negotiated = (get_cctx(p)->profile == RIST_PROFILE_ADVANCED &&
4561 p->is_advanced && p->remote_supports_advanced);
4562 if (p->send_keepalive) {
4563 if (now > p->next_periodic_rtcp) {
4564 p->next_periodic_rtcp = now + p->rtcp_keepalive_interval;
4565 if (p->remote_port != 0) {
4566 rist_peer_rtcp(NULL, p);
4567 if (adv_negotiated)
4568 rist_adv_send_rtt_echo_request(p);
4569 }
4570 }
4571 if (get_cctx(p)->profile >= RIST_PROFILE_MAIN && p->next_keepalive_packet <= now) {
4572 p->next_keepalive_packet = now + ONE_SECOND;
4573 if (adv_negotiated) {
4574 rist_adv_send_keepalive(p);
4575 if (p->sender_ctx && p->next_flow_attr <= now) {
4576 p->next_flow_attr = now + ONE_SECOND;
4577 rist_adv_send_flow_attr(p);
4578 }
4579 } else
4580 _librist_proto_gre_send_keepalive(p, p->rist_gre_version);
4581 #if HAVE_SRP_SUPPORT
4582 if (!p->child && !eap_is_authenticated(p->eap_ctx) && p->eap_authentication_state == 2 && p->parent && p->parent->multicast_sender) {
4583 p->eap_authentication_state = 1;
4584 char newpass[65];
4585 newpass[64] = '\0';
4586 if (_librist_crypto_random_get_string(newpass, sizeof(newpass)-1) == 0) {
4587 rist_peer_update_secret(p->parent, newpass);
4588 }
4589 }
4590 #endif
4591 }
4592 }
4593 #if HAVE_SRP_SUPPORT
4594 if ((!p->listening || p->parent) && !p->multicast_sender)
4595 eap_periodic(p->eap_ctx);
4596 #endif
4597 }
4598
4599 static void sender_peer_events(struct rist_sender *ctx, uint64_t now)
4600 {
4601 pthread_mutex_lock(&ctx->common.peerlist_lock);
4602 for (size_t j = 0; j < ctx->peer_lst_len; j++) {
4603 rist_peer_periodic(ctx->peer_lst[j], now);
4604 }
4605 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4606 }
4607
4608
4609 static void receiver_peer_events(struct rist_receiver *ctx, uint64_t now)
4610 {
4611 pthread_mutex_lock(&ctx->common.peerlist_lock);
4612
4613 for (struct rist_peer *p = ctx->common.PEERS; p != NULL; p = p->next) {
4614 rist_peer_periodic(p, now);
4615 }
4616 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4617 }
4618
4619 /* Silence before an authenticated leg is torn down and re-handshaked: the
4620 * configured session_timeout, or twice the receiver buffer when that is larger
4621 * (a leg returning within the buffer window can still contribute packets). */
4622 static inline uint64_t rist_peer_liveness_timeout(const struct rist_peer *peer)
4623 {
4624 uint64_t buf = 2 * peer->recovery_buffer_ticks;
4625 return buf > peer->session_timeout ? buf : peer->session_timeout;
4626 }
4627
4628 void rist_timeout_check(struct rist_common_ctx *cctx, uint64_t now)
4629 {
4630 struct rist_peer *peer = cctx->PEERS;
4631 while (peer)
4632 {
4633 struct rist_peer *next = peer->next;
4634 uint64_t last_rtcp_received = peer->last_pkt_received;
4635 if (cctx->profile == RIST_PROFILE_SIMPLE &&
4636 !peer->is_rtcp && peer->peer_rtcp != NULL &&
4637 peer->peer_rtcp->last_pkt_received > last_rtcp_received)
4638 last_rtcp_received = peer->peer_rtcp->last_pkt_received;
4639 if (!peer->dead && now > last_rtcp_received && last_rtcp_received > 0)
4640 {
4641 if ((now - last_rtcp_received) > rist_peer_liveness_timeout(peer))
4642 {
4643 rist_log_priv2(cctx->logging_settings, RIST_LOG_WARN, "Listening peer %u timed out after %"PRIu64" ms\n", peer->adv_peer_id,
4644 (now - last_rtcp_received)/ RIST_CLOCK);
4645 if (try_caller_socket_rebind(peer, now))
4646 {
4647 /* Rebind kept the peer alive with a fresh
4648 * socket; skip kill_peer. */
4649 peer = next;
4650 continue;
4651 }
4652 kill_peer(peer);
4653 }
4654 } else if (peer->dead && peer->parent)
4655 {
4656 if ( peer->dead_since < now && (now - peer->dead_since) > 5000 * RIST_CLOCK)
4657 {
4658 rist_log_priv2(cctx->logging_settings, RIST_LOG_INFO, "Removing timed-out peer %u\n", peer->adv_peer_id);
4659 rist_peer_remove(cctx, peer, NULL);
4660 }
4661 } else if (!peer->timed_out && peer->dead && peer->dead_since < now && (now - peer->dead_since) > 5000 * RIST_CLOCK) {
4662 peer->timed_out = 1;
4663 if (cctx->connection_status_callback && peer->send_first_connection_event)
4664 cctx->connection_status_callback( cctx->connection_status_callback_argument, peer, RIST_CONNECTION_TIMED_OUT);
4665 }
4666 peer = next;
4667 }
4668 }
4669
4670 /* True for a bonded data leg that participates in weighted balancing.
4671 * Listeners, children, and duplicate (weight 0) legs are out of scope. */
4672 static inline bool rist_peer_bonded_data_leg(const struct rist_peer *peer)
4673 {
4674 return peer->is_data && !peer->parent && !peer->listening
4675 && peer->config.weight != RIST_PEER_WEIGHT_DUPLICATE;
4676 }
4677
4678 /* True for a bonded data leg that also has RTT auto-mute configured.
4679 * Caller must hold peerlist_lock. */
4680 static inline bool rist_peer_rtt_mute_eligible(const struct rist_peer *peer)
4681 {
4682 return rist_peer_bonded_data_leg(peer) && peer->config.rtt_drop > 0;
4683 }
4684
4685 /* Silent for a few probe intervals: well short of the liveness timeout, since
4686 * fast-mute only reroutes payload rather than tearing the session down. Scales
4687 * with the configured keepalive_interval. */
4688 static inline bool rist_peer_stall_silent(const struct rist_peer *peer, uint64_t now)
4689 {
4690 uint64_t thr = RIST_STALL_MUTE_PINGS * peer->rtcp_keepalive_interval;
4691 return peer->last_pkt_received > 0 && now > peer->last_pkt_received
4692 && (now - peer->last_pkt_received) > thr;
4693 }
4694
4695 /* Fast-mute briefly-silent bonded legs so their payload reroutes to a healthy
4696 * sibling rather than pouring into a stalled path until the liveness timeout
4697 * tears the session down. Any bonded leg qualifies (no rtt-drop needed); the
4698 * flag is recomputed each tick, so a resumed leg clears at once. The last leg
4699 * with a live return path is never muted. Short tick, peerlist_lock held. */
4700 static void rist_sender_stall_check(struct rist_sender *ctx, uint64_t now)
4701 {
4702 struct rist_peer *peer;
4703 int eligible = 0, live = 0;
4704
4705 for (peer = ctx->common.PEERS; peer; peer = peer->next) {
4706 if (!rist_peer_bonded_data_leg(peer))
4707 continue;
4708 eligible++;
4709 if (!rist_peer_stall_silent(peer, now))
4710 live++;
4711 }
4712 /* Nothing to fail over to: never stall-mute a single leg. */
4713 if (eligible < 2) {
4714 for (peer = ctx->common.PEERS; peer; peer = peer->next)
4715 peer->stalled = false;
4716 return;
4717 }
4718 for (peer = ctx->common.PEERS; peer; peer = peer->next) {
4719 if (!rist_peer_bonded_data_leg(peer)) {
4720 peer->stalled = false;
4721 continue;
4722 }
4723 bool silent = rist_peer_stall_silent(peer, now);
4724 /* keep every leg sending if all are silent, rather than black out */
4725 bool stall = silent && live > 0;
4726 if (stall && !peer->stalled)
4727 rist_log_priv(&ctx->common, RIST_LOG_INFO,
4728 "Peer %"PRIu32" stalled: silent %"PRIu64"ms, rerouting payload to healthy leg(s)\n",
4729 peer->adv_peer_id, (now - peer->last_pkt_received) / RIST_CLOCK);
4730 else if (!stall && peer->stalled)
4731 rist_log_priv(&ctx->common, RIST_LOG_INFO,
4732 "Peer %"PRIu32" resumed from stall\n", peer->adv_peer_id);
4733 peer->stalled = stall;
4734 }
4735 }
4736
4737 /* Advance the RTT hysteresis for every eligible bonded leg, then decide which
4738 * legs are actually pulled from the payload rotation. rtt_mute_state.muted is
4739 * the *desired* state; peer->rtt_muted (what the balancer skips) is only set
4740 * when pulling the leg still leaves a carrier -- a bonded leg that is neither
4741 * muted nor stalled. Since the stall check runs first, a leg that wants mute
4742 * but whose only sibling is stalled is simply kept carrying, never actually
4743 * muted: that avoids blacking out the bond and, because the hysteresis state is
4744 * left untouched, avoids re-muting (and re-counting/logging) it every dwell.
4745 * Caller holds peerlist_lock; runs on a short tick (see the sender loop). */
4746 static void rist_sender_rtt_mute_check(struct rist_sender *ctx, uint64_t now)
4747 {
4748 struct rist_peer *peer;
4749 int eligible = 0;
4750
4751 for (peer = ctx->common.PEERS; peer; peer = peer->next)
4752 if (rist_peer_rtt_mute_eligible(peer))
4753 eligible++;
4754 /* Nothing to fail over to: never mute a single leg. */
4755 if (eligible < 2)
4756 return;
4757
4758 for (peer = ctx->common.PEERS; peer; peer = peer->next) {
4759 if (!rist_peer_rtt_mute_eligible(peer))
4760 continue;
4761 if (peer->eight_times_rtt == 0)
4762 continue; /* no RTT sample yet */
4763
4764 uint64_t smoothed = peer->eight_times_rtt / 8;
4765 uint64_t drop = (uint64_t)peer->config.rtt_drop * RIST_CLOCK;
4766 uint64_t restore = peer->config.rtt_restore
4767 ? (uint64_t)peer->config.rtt_restore * RIST_CLOCK
4768 : (drop * 4) / 5;
4769 if (restore >= drop)
4770 restore = (drop * 4) / 5;
4771 uint64_t drop_settle = (uint64_t)peer->config.rtt_drop_settle * RIST_CLOCK;
4772 /* Rejoin dwell is twice the drop dwell so a still-marginal link
4773 * cannot immediately flap back in. */
4774 uint64_t restore_settle = drop_settle * 2;
4775 rist_rtt_mute_step(&peer->rtt_mute_state, smoothed, drop, restore,
4776 drop_settle, restore_settle, now);
4777 }
4778
4779 /* Count natural carriers; among the legs that want mute but could still
4780 * carry (not stalled), find the incumbent sole carrier and the best
4781 * challenger. */
4782 int carriers = 0;
4783 struct rist_peer *incumbent = NULL, *best = NULL;
4784 uint64_t incumbent_rtt = UINT64_MAX, best_rtt = UINT64_MAX;
4785 for (peer = ctx->common.PEERS; peer; peer = peer->next) {
4786 if (!rist_peer_bonded_data_leg(peer))
4787 continue;
4788 bool want = rist_peer_rtt_mute_eligible(peer) && peer->rtt_mute_state.muted;
4789 if (!want && !peer->stalled) {
4790 carriers++;
4791 } else if (want && !peer->stalled) {
4792 uint64_t smoothed = peer->eight_times_rtt ? peer->eight_times_rtt / 8 : UINT64_MAX;
4793 if (smoothed < best_rtt) { best_rtt = smoothed; best = peer; }
4794 if (peer->rtt_sole_carrier) { incumbent = peer; incumbent_rtt = smoothed; }
4795 }
4796 }
4797
4798 /* Pick the leg to keep when nothing else can carry. Re-running this from
4799 * the instantaneous RTT every tick made the payload path ping-pong between
4800 * two equally bad legs roughly once a second, which is worse for the stream
4801 * than staying on either one, so the incumbent holds the role until it
4802 * recovers, goes stalled, or a sibling measures several times better and
4803 * the incumbent has served at least one drop dwell. */
4804 struct rist_peer *keep = NULL;
4805 if (carriers == 0) {
4806 keep = incumbent ? incumbent : best;
4807 if (incumbent && best && best != incumbent
4808 && rist_rtt_sole_carrier_handover(incumbent_rtt, best_rtt,
4809 now - incumbent->rtt_sole_since,
4810 (uint64_t)incumbent->config.rtt_drop_settle * RIST_CLOCK,
4811 RIST_SOLE_CARRIER_MARGIN))
4812 keep = best;
4813 }
4814 for (peer = ctx->common.PEERS; peer; peer = peer->next) {
4815 if (!rist_peer_bonded_data_leg(peer))
4816 continue;
4817 if (peer != keep)
4818 peer->rtt_sole_carrier = false;
4819 else if (!peer->rtt_sole_carrier) {
4820 peer->rtt_sole_carrier = true;
4821 peer->rtt_sole_since = now;
4822 }
4823 }
4824
4825 /* Apply, counting/logging only genuine peer->rtt_muted transitions. */
4826 for (peer = ctx->common.PEERS; peer; peer = peer->next) {
4827 if (!rist_peer_rtt_mute_eligible(peer))
4828 continue;
4829 bool mute = peer->rtt_mute_state.muted && peer != keep;
4830 if (mute && !peer->rtt_muted) {
4831 uint64_t smoothed = (peer->eight_times_rtt / 8) / RIST_CLOCK;
4832 peer->rtt_muted = true;
4833 peer->rtt_mute_count++;
4834 /* Below the ceiling means the leg spiked earlier and is still
4835 * serving out its rejoin dwell, not that it just crossed. */
4836 if (smoothed > peer->config.rtt_drop)
4837 rist_log_priv(&ctx->common, RIST_LOG_INFO,
4838 "Peer %"PRIu32" muted: smoothed RTT %"PRIu64"ms over %ums ceiling\n",
4839 peer->adv_peer_id, smoothed, peer->config.rtt_drop);
4840 else
4841 rist_log_priv(&ctx->common, RIST_LOG_INFO,
4842 "Peer %"PRIu32" muted: smoothed RTT %"PRIu64"ms, rejoin dwell not met\n",
4843 peer->adv_peer_id, smoothed);
4844 } else if (!mute && peer->rtt_muted) {
4845 peer->rtt_muted = false;
4846 peer->rtt_trickle_counter = 0;
4847 /* Rejoin gradually: an idle leg measures well until it carries
4848 * again, so ramp its share back instead of re-flooding it. */
4849 peer->rtt_ramp_start = now;
4850 if (peer->rtt_mute_state.muted)
4851 rist_log_priv(&ctx->common, RIST_LOG_INFO,
4852 "Peer %"PRIu32" kept as sole carrier (all bonded legs muted or stalled)\n",
4853 peer->adv_peer_id);
4854 else
4855 rist_log_priv(&ctx->common, RIST_LOG_INFO,
4856 "Peer %"PRIu32" restored to bond: smoothed RTT %"PRIu64"ms\n",
4857 peer->adv_peer_id,
4858 (peer->eight_times_rtt / 8) / RIST_CLOCK);
4859 }
4860 }
4861 }
4862
4863 PTHREAD_START_FUNC(sender_pthread_protocol, arg)
4864 {
4865 struct rist_sender *ctx = (struct rist_sender *) arg;
4866 // loop behavior parameters
4867 int max_dataperloop = 100;
4868 int max_oobperloop = 100;
4869
4870 int max_jitter_ms = ctx->common.rist_max_jitter / RIST_CLOCK;
4871
4872 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Starting master sender loop at %d ms max jitter\n",
4873 max_jitter_ms);
4874
4875 uint64_t now = timestampNTP_u64();
4876 ctx->stats_next_time = now;
4877 ctx->checks_next_time = now;
4878 uint64_t nacks_next_time = now;
4879 uint64_t mute_check_next_time = now;
4880 while(!atomic_load_explicit(&ctx->common.shutdown, memory_order_acquire)) {
4881 // Conditional 5ms sleep that is woken by data coming in
4882 pthread_mutex_lock(&(ctx->mutex));
4883 int ret = pthread_cond_timedwait_ms(&(ctx->condition), &(ctx->mutex), max_jitter_ms);
4884 if (RIST_UNLIKELY(!atomic_load_explicit(&ctx->common.startup_complete, memory_order_acquire))) {
4885 pthread_mutex_unlock(&(ctx->mutex));
4886 continue;
4887 }
4888 pthread_mutex_unlock(&(ctx->mutex));
4889 if (ret && ret != ETIMEDOUT)
4890 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Error %d in sender protocol loop, loop time was %d us\n", ret, (timestampNTP_u64() - now));
4891
4892 now = timestampNTP_u64();
4893
4894 /* marks peer as dead, run every second */
4895 if (now > ctx->checks_next_time)
4896 {
4897 ctx->checks_next_time += (uint64_t)1000 * (uint64_t)RIST_CLOCK;
4898 pthread_mutex_lock(&ctx->common.peerlist_lock);
4899 rist_timeout_check(&ctx->common, now);
4900 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4901 }
4902
4903 /* Short tick so the configured settle is honoured, not quantised
4904 * to the 1 s check cadence. */
4905 if (now > mute_check_next_time)
4906 {
4907 mute_check_next_time = now + (uint64_t)250 * (uint64_t)RIST_CLOCK;
4908 pthread_mutex_lock(&ctx->common.peerlist_lock);
4909 /* Stall first so the mute check sees this tick's stalled
4910 * flags and can keep a carrier when a sibling is silent. */
4911 rist_sender_stall_check(ctx, now);
4912 rist_sender_rtt_mute_check(ctx, now);
4913 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4914 }
4915
4916 // stats timer; 0 == disabled. Read fresh so a callback registered
4917 // after loop start takes effect.
4918 uint64_t rist_stats_interval = ctx->stats_report_time;
4919 if (rist_stats_interval == 0) {
4920 ctx->stats_next_time = now; // keep current to avoid a catch-up burst
4921 } else if (now > ctx->stats_next_time) {
4922 ctx->stats_next_time += rist_stats_interval;
4923 rist_sender_flow_statistics(ctx);
4924 // TODO: remove dead peers after stale flow time (both sender list and peer chain)
4925 // sender_peer_delete(peer->sender_ctx, peer);
4926 }
4927
4928 // socket polls (returns as fast as possible and processes the next 100 socket events)
4929 pthread_mutex_lock(&ctx->common.peerlist_lock);
4930 evsocket_loop_single(ctx->common.evctx, 0, 100);
4931 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4932
4933 // keepalive timer
4934 sender_peer_events(ctx, now);
4935
4936
4937 // Send data and process nacks
4938 pthread_mutex_lock(&ctx->queue_lock);
4939 if (ctx->sender_queue_bytesize > 0) {
4940 pthread_mutex_lock(&ctx->common.peerlist_lock);
4941 sender_send_data(ctx, max_dataperloop);
4942 // Group nacks and send them all at rist_max_jitter intervals.
4943 // sender_send_nacks() dereferences retry->peer for every
4944 // entry in the retry queue; the peer list (and hence any
4945 // given peer) can be torn down from rist_peer_destroy()
4946 // concurrently, so we must hold peerlist_lock across the
4947 // whole dequeue loop to prevent a use-after-free.
4948 if (now > nacks_next_time) {
4949 sender_send_nacks(ctx);
4950 nacks_next_time += ctx->common.rist_max_jitter;
4951 }
4952 pthread_mutex_unlock(&ctx->common.peerlist_lock);
4953 }
4954 pthread_mutex_unlock(&ctx->queue_lock);
4955 // Send oob data
4956 if (ctx->common.oob_queue_bytesize > 0)
4957 rist_oob_dequeue(&ctx->common, max_oobperloop);
4958
4959 }
4960
4961 #ifdef _WIN32
4962 WSACleanup();
4963 #endif
4964 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Exiting master sender loop\n");
4965 atomic_store_explicit(&ctx->common.shutdown, 2, memory_order_release);
4966
4967 return 0;
4968 }
4969
4970 /* Idempotent: re-init is fine if cctx->profile is upgraded to Advanced
4971 * after the original init_common_ctx ran (e.g. via ?profile= URL override
4972 * in rist_peer_create). Re-rolls SSRC base and clears the seq counters. */
4973 void init_advanced_state(struct rist_common_ctx *ctx)
4974 {
4975 /* Generate a random even SSRC base for the Protected flow.
4976 * The Unprotected flow uses ssrc_base | 1 (Section 5.2.1). */
4977 uint32_t rnd = 0;
4978 _librist_crypto_ramdom_get_bytes((uint8_t *)&rnd, sizeof(rnd));
4979 ctx->adv_ssrc_base = rnd & ~(uint32_t)1;
4980 ctx->adv_seq_protected = 0;
4981 ctx->adv_seq_unprotected = 0;
4982 }
4983
4984 int init_common_ctx(struct rist_common_ctx *ctx, enum rist_profile profile)
4985 {
4986 #ifdef _WIN32
4987 int ret;
4988 WSADATA wsaData;
4989 ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
4990 if (ret < 0) {
4991 rist_log_priv3(RIST_LOG_ERROR, "Failed to initialize WSA\n");
4992 return -1;
4993 }
4994 #endif
4995 ctx->evctx = evsocket_create();
4996 ctx->rist_max_jitter = RIST_MAX_JITTER * RIST_CLOCK;
4997 ctx->cbr_output = false;
4998 ctx->cbr_output_min_us = RIST_CBR_OUTPUT_MIN_US_DEFAULT;
4999 ctx->recovery_queue_max = RIST_SERVER_QUEUE_BUFFERS;
5000 if (profile > RIST_PROFILE_ADVANCED) {
5001 rist_log_priv3( RIST_LOG_ERROR, "Profile not supported (%d), using main profile instead\n", profile);
5002 profile = RIST_PROFILE_MAIN;
5003 }
5004 if (profile == RIST_PROFILE_SIMPLE)
5005 rist_log_priv3( RIST_LOG_INFO, "Starting in Simple Profile Mode\n");
5006 else if (profile == RIST_PROFILE_MAIN)
5007 rist_log_priv3( RIST_LOG_INFO, "Starting in Main Profile Mode\n");
5008 else if (profile == RIST_PROFILE_ADVANCED)
5009 rist_log_priv3( RIST_LOG_INFO, "Starting in Advanced Profile Mode\n");
5010
5011 ctx->profile = profile;
5012 atomic_store_explicit(&ctx->profile_locked, false, memory_order_release);
5013 ctx->stats_report_time = 0;
5014
5015 if (profile == RIST_PROFILE_ADVANCED)
5016 init_advanced_state(ctx);
5017
5018 if (pthread_mutex_init(&ctx->peerlist_lock, NULL) != 0) {
5019 rist_log_priv3( RIST_LOG_ERROR, "Failed to init ctx->peerlist_lock\n");
5020 return -1;
5021 }
5022 if (pthread_mutex_init(&ctx->rist_free_buffer_mutex, NULL) != 0) {
5023 rist_log_priv3( RIST_LOG_ERROR, "Failed to init ctx->rist_free_buffer_mutex\n");
5024 return -1;
5025 }
5026 if (pthread_mutex_init(&ctx->flows_lock, NULL) != 0) {
5027 rist_log_priv3( RIST_LOG_ERROR, "Failed to init ctx->flows_lock\n");
5028 return -1;
5029 }
5030 if (pthread_mutex_init(&ctx->stats_lock, NULL) != 0) {
5031 rist_log_priv3( RIST_LOG_ERROR, "Failed to init ctx->stats_lock\n");
5032 return -1;
5033 }
5034 return 0;
5035 }
5036
5037 static inline void peer_remove_child(struct rist_peer *peer) {
5038 assert(peer->parent);
5039 //head
5040 if (!peer->sibling_prev) {
5041 peer->parent->child = peer->sibling_next;
5042 //middle or tail
5043 } else {
5044 peer->sibling_prev->sibling_next = peer->sibling_next;
5045 }
5046 if (peer->sibling_next)
5047 peer->sibling_next->sibling_prev = peer->sibling_prev;
5048 return;
5049 }
5050
5051 static inline void peer_remove_linked_list(struct rist_peer *peer) {
5052 assert(peer);
5053 struct rist_common_ctx *ctx = get_cctx(peer);
5054 if (!peer->prev) {
5055 ctx->PEERS = peer->next;
5056 } else {
5057 peer->prev->next = peer->next;
5058 }
5059 if (peer->next)
5060 peer->next->prev = peer->prev;
5061 return;
5062 }
5063
5064
5065 void remove_peer_from_flow(struct rist_peer *peer)
5066 {
5067 struct rist_flow *f = peer->flow;
5068 if (f == NULL)
5069 return;
5070 pthread_mutex_lock(&f->mutex);
5071 bool found = false;
5072 for (size_t i = 0; i < f->peer_lst_len; i++)
5073 {
5074 if (f->peer_lst[i] == peer)
5075 {
5076 f->peer_lst[i] = f->peer_lst[(f->peer_lst_len -1)];
5077 found = true;
5078 break;
5079 }
5080 }
5081 if (found)
5082 {
5083 if (f->peer_lst_len > 1)
5084 {
5085 struct rist_peer **shrunk = realloc(f->peer_lst, sizeof(peer) * (f->peer_lst_len -1));
5086 /* Shrink realloc may fail; keep the oversized allocation. */
5087 if (shrunk)
5088 f->peer_lst = shrunk;
5089 f->peer_lst_len--;
5090 } else
5091 {
5092 free(f->peer_lst);
5093 f->peer_lst_len = 0;
5094 f->peer_lst = NULL;
5095 }
5096 }
5097 pthread_mutex_unlock(&f->mutex);
5098 }
5099
5100 int rist_peer_remove(struct rist_common_ctx *ctx, struct rist_peer *peer, struct rist_peer **next)
5101 {
5102 if (peer == NULL) {
5103 if (next)
5104 *next = NULL;
5105 return -1;
5106 }
5107 atomic_store_explicit(&peer->shutdown, true, memory_order_release);
5108 if (peer->send_first_connection_event && !peer->timed_out && ctx->connection_status_callback && (ctx->profile != RIST_PROFILE_SIMPLE || peer->is_rtcp))
5109 ctx->connection_status_callback(ctx->connection_status_callback_argument, peer, RIST_CONNECTION_TIMED_OUT);
5110 if (peer->child)
5111 {
5112 while (peer->child) {
5113 rist_log_priv2(ctx->logging_settings, RIST_LOG_INFO, "[CLEANUP] removing child peer %u from peer %u\n", peer->child->adv_peer_id, peer->adv_peer_id);
5114 rist_peer_remove(ctx, peer->child, NULL);
5115 }
5116 }
5117
5118 struct rist_peer *check = ctx->PEERS;
5119 while (check)
5120 {
5121 if (check->peer_data == peer)
5122 check->peer_data = NULL;
5123 if (check->peer_rtcp == peer)
5124 check->peer_rtcp = NULL;
5125 check = check->next;
5126 }
5127
5128 /* Defensive: scrub any references to this peer from the sender's
5129 * retry queue. The protocol thread now drains that queue under
5130 * peerlist_lock, so it will never see a dangling retry->peer from
5131 * here, but clearing the slot makes later triage easier and keeps
5132 * the invariant explicit. */
5133 if (peer->sender_ctx && peer->sender_ctx->sender_retry_queue) {
5134 struct rist_sender *sctx = peer->sender_ctx;
5135 for (size_t i = 0; i < sctx->sender_retry_queue_size; i++) {
5136 if (sctx->sender_retry_queue[i].peer == peer) {
5137 sctx->sender_retry_queue[i].peer = NULL;
5138 sctx->sender_retry_queue[i].active = false;
5139 }
5140 }
5141 }
5142 if (peer->parent) {
5143 peer_remove_child(peer);
5144 if (peer->parent->child == NULL) {
5145 peer->parent->authenticated = false;
5146 if (peer->sender_ctx)
5147 peer->sender_ctx->total_weight -= peer->parent->config.weight;
5148 }
5149 }
5150 peer_remove_linked_list(peer);
5151
5152 if (peer->parent && peer->flow && peer->flow->peer_lst_len > 0 && peer->flow->peer_lst != NULL) {
5153 remove_peer_from_flow(peer);
5154 }
5155
5156 if (peer->sender_ctx && peer->sender_ctx->peer_lst_len > 0) {
5157 bool found = false;
5158 for (size_t i = 0; i < peer->sender_ctx->peer_lst_len; i++) {
5159 if (peer->sender_ctx->peer_lst[i] == peer) {
5160 peer->sender_ctx->peer_lst[i] = peer->sender_ctx->peer_lst[(peer->sender_ctx->peer_lst_len -1)];
5161 found = true;
5162 break;
5163 }
5164 }
5165 if (found) {
5166 if (peer->sender_ctx->peer_lst_len > 1)
5167 {
5168 peer->sender_ctx->peer_lst = realloc(peer->sender_ctx->peer_lst, sizeof(peer) * (peer->sender_ctx->peer_lst_len -1));
5169 peer->sender_ctx->peer_lst_len--;
5170 } else
5171 {
5172 free(peer->sender_ctx->peer_lst);
5173 peer->sender_ctx->peer_lst_len = 0;
5174 peer->sender_ctx->peer_lst = NULL;
5175 }
5176 }
5177 }
5178
5179 if (peer->receiver_ctx != NULL && peer->flow != NULL) {
5180 pthread_mutex_lock(&peer->flow->mutex);
5181 bool found = false;
5182 for (size_t i=0; i < peer->flow->peer_lst_len; i++) {
5183 if (peer->flow->peer_lst[i] == peer) {
5184 peer->flow->peer_lst[i] = peer->flow->peer_lst[(peer->flow->peer_lst_len -1)];
5185 found = true;
5186 break;
5187 }
5188 }
5189
5190 if (found) {
5191 if (peer->flow->peer_lst_len > 1) {
5192 /* Shrink realloc may fail; keep the oversized allocation. */
5193 struct rist_peer **shrunk = realloc(peer->flow->peer_lst, sizeof(peer) * (peer->flow->peer_lst_len -1));
5194 if (shrunk)
5195 peer->flow->peer_lst = shrunk;
5196 peer->flow->peer_lst_len--;
5197 } else {
5198 free(peer->flow->peer_lst);
5199 peer->flow->peer_lst_len = 0;
5200 peer->flow->peer_lst = NULL;
5201 }
5202 }
5203 pthread_mutex_unlock(&peer->flow->mutex);
5204 }
5205
5206
5207 /* data receive event */
5208 if (!peer->parent && peer->event_recv)
5209 {
5210 rist_log_priv2(ctx->logging_settings, RIST_LOG_INFO, "[CLEANUP] Removing peer data received event\n");
5211 struct evsocket_ctx *evctx = ctx->evctx;
5212 evsocket_delevent(evctx, peer->event_recv);
5213 }
5214
5215 /* rtcp timer */
5216 if (peer->send_keepalive)
5217 {
5218 rist_log_priv2(ctx->logging_settings, RIST_LOG_INFO, "[CLEANUP] Removing peer handshake/ping timer\n");
5219 peer->send_keepalive = false;
5220 }
5221
5222
5223 if (!peer->parent && peer->sd > -1)
5224 {
5225 rist_log_priv2(ctx->logging_settings, RIST_LOG_INFO, "[CLEANUP] Closing peer socket on port %d\n", peer->local_port);
5226 udpsocket_close(peer->sd);
5227 peer->sd = -1;
5228 }
5229 _librist_crypto_psk_rist_key_destroy(&peer->key_rx);
5230 _librist_crypto_psk_rist_key_destroy(&peer->key_rx_odd);
5231 _librist_crypto_psk_rist_key_destroy(&peer->key_tx);
5232 _librist_crypto_psk_rist_key_destroy(&peer->key_tx_odd);
5233 #if HAVE_SRP_SUPPORT
5234 eap_delete_ctx(&peer->eap_ctx);
5235 #endif
5236 if (peer->url)
5237 free(peer->url);
5238
5239 if (peer->parent != NULL && ctx->auth.disconn_cb) {
5240 ctx->auth.disconn_cb(ctx->auth.arg, peer);
5241 }
5242 if (next != NULL)
5243 *next = peer->next;
5244 rist_log_priv2(ctx->logging_settings, RIST_LOG_INFO, "[CLEANUP] cleanup done for peer %u\n", peer->adv_peer_id);
5245
5246 if (ctx->oob_current_peer == peer) {
5247 ctx->oob_current_peer = NULL;
5248 }
5249
5250 free(peer);
5251 return 0;
5252 }
5253
5254 int rist_auth_handler(struct rist_common_ctx *ctx,
5255 int (*conn_cb)(void *arg, const char* connecting_ip, uint16_t connecting_port, const char* local_ip, uint16_t local_port, struct rist_peer *peer),
5256 int (*disconn_cb)(void *arg, struct rist_peer *peer),
5257 void *arg)
5258 {
5259 ctx->auth.conn_cb = conn_cb;
5260 ctx->auth.disconn_cb = disconn_cb;
5261 ctx->auth.arg = arg;
5262 return 0;
5263 }
5264
5265 static void store_peer_settings(const struct rist_peer_config *settings, struct rist_peer *peer)
5266 {
5267 uint32_t recovery_rtt_min;
5268 uint32_t min_retries;
5269 uint32_t max_retries;
5270
5271 // TODO: Consolidate the two settings objects into one
5272
5273 /* Set recovery options */
5274 peer->config.recovery_mode = settings->recovery_mode;
5275 peer->config.recovery_maxbitrate = settings->recovery_maxbitrate;
5276 peer->config.recovery_maxbitrate_return = settings->recovery_maxbitrate_return;
5277 peer->config.recovery_length_min = settings->recovery_length_min;
5278 peer->config.recovery_length_max = settings->recovery_length_max;
5279 peer->config.recovery_reorder_buffer = settings->recovery_reorder_buffer;
5280 /* Set buffer-bloating */
5281 if (settings->min_retries < 2 || settings->min_retries > 100) {
5282 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
5283 "The configured value for min_retries 2 <= %u <= 100 is invalid, using %u instead\n",
5284 settings->min_retries, 6);
5285 min_retries = 6;
5286 } else {
5287 min_retries = settings->min_retries;
5288 }
5289 if (settings->max_retries < 2 || settings->max_retries > 100) {
5290 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
5291 "The configured value for max_retries 2 <= %u <= 100 is invalid, using %u instead\n",
5292 settings->max_retries, 20);
5293 max_retries = 20;
5294 } else {
5295 max_retries = settings->max_retries;
5296 }
5297 if (settings->recovery_rtt_min < RIST_RTT_MIN) {
5298 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "rtt_min is too small (%u), using %dms instead\n",
5299 settings->recovery_rtt_min, RIST_RTT_MIN);
5300 recovery_rtt_min = RIST_RTT_MIN;
5301 } else {
5302 recovery_rtt_min = settings->recovery_rtt_min;
5303 }
5304 // Override rtt min if value is unreasonable
5305 uint32_t min_rtt = settings->recovery_length_min / max_retries;
5306 if (recovery_rtt_min < min_rtt) {
5307 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "rtt_min is too small (%u) for the buffer size, using %u/%u = %dms instead\n",
5308 recovery_rtt_min, settings->recovery_length_min, max_retries, min_rtt);
5309 recovery_rtt_min = min_rtt;
5310 }
5311 if (settings->recovery_rtt_max < recovery_rtt_min)
5312 {
5313 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "rtt_max is too small (%u), using %u instead\n",
5314 settings->recovery_rtt_max, recovery_rtt_min);
5315 peer->config.recovery_rtt_max = recovery_rtt_min * RIST_CLOCK;
5316 }
5317 else
5318 peer->config.recovery_rtt_max = settings->recovery_rtt_max * RIST_CLOCK;
5319 peer->config.recovery_rtt_min = recovery_rtt_min * RIST_CLOCK;
5320 peer->config.congestion_control_mode = settings->congestion_control_mode;
5321 peer->config.min_retries = min_retries;
5322 peer->config.max_retries = max_retries;
5323 peer->config.weight = settings->weight;
5324 peer->config.recovery_priority = settings->recovery_priority;
5325 peer->config.timing_mode = settings->timing_mode;
5326 peer->config.virt_dst_port = settings->virt_dst_port;
5327 if (settings->version >= 2)
5328 peer->config.reflector = settings->reflector;
5329 else
5330 peer->config.reflector = 0;
5331 if (settings->version >= 3)
5332 peer->config.srp_compat_legacy = settings->srp_compat_legacy; //read by rist_enable_eap_srp_2 after peer_create
5333 else
5334 peer->config.srp_compat_legacy = 0;
5335 if (settings->version >= 6) {
5336 peer->config.rtt_drop = settings->rtt_drop;
5337 peer->config.rtt_restore = settings->rtt_restore;
5338 peer->config.rtt_drop_settle = settings->rtt_drop_settle;
5339 peer->config.rtt_drop_trickle = settings->rtt_drop_trickle;
5340 } else {
5341 peer->config.rtt_drop = 0;
5342 peer->config.rtt_restore = 0;
5343 peer->config.rtt_drop_settle = RIST_DEFAULT_RTT_DROP_SETTLE;
5344 peer->config.rtt_drop_trickle = 0;
5345 }
5346
5347 init_peer_settings(peer);
5348 }
5349
5350 struct rist_peer *rist_sender_peer_insert_local(struct rist_sender *ctx,
5351 const struct rist_peer_config *config, bool b_rtcp)
5352 {
5353 struct rist_peer *newpeer = _librist_peer_create_common(&ctx->common, NULL, ctx, config);
5354 if (!newpeer)
5355 return NULL;
5356 if (b_rtcp)
5357 {
5358 if (newpeer->u.address.sa_family == AF_INET) {
5359 struct sockaddr_in *addrv4 = (struct sockaddr_in *)&(newpeer->u);
5360 newpeer->remote_port = htons(addrv4->sin_port) + 1;
5361 addrv4->sin_port = be16toh(newpeer->remote_port);
5362 } else {
5363 struct sockaddr_in6 *addrv6 = (struct sockaddr_in6 *)&(newpeer->u);
5364 newpeer->remote_port = htons(addrv6->sin6_port) + 1;
5365 addrv6->sin6_port = be16toh(newpeer->remote_port);
5366 }
5367 }
5368 else
5369 {
5370 newpeer->local_port = 32768 + (ctx->common.peer_counter % 28232);
5371 // This overrides the physical port populate in rist_create_socket with the gre dst port
5372 if (ctx->common.profile != RIST_PROFILE_SIMPLE && config->virt_dst_port != 0)
5373 newpeer->remote_port = config->virt_dst_port + 1;
5374 }
5375
5376 newpeer->cooldown_time = 0;
5377 newpeer->is_rtcp = b_rtcp;
5378 newpeer->adv_peer_id = ++ctx->common.peer_counter;
5379 newpeer->peer_ssrc = newpeer->adv_flow_id = ctx->adv_flow_id;
5380
5381 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Advertising flow_id %" PRIu64 " and peer_id %u, %u/%u\n",
5382 newpeer->adv_flow_id, newpeer->adv_peer_id, newpeer->local_port, newpeer->remote_port);
5383
5384 return newpeer;
5385
5386 }
5387
5388
5389 void rist_empty_oob_queue(struct rist_common_ctx *ctx)
5390 {
5391 uint16_t index = 0;
5392 while (1) {
5393 if (index == ctx->oob_queue_write_index) {
5394 break;
5395 }
5396 struct rist_buffer *oob_buffer = ctx->oob_queue[index];
5397 if (oob_buffer->data) {
5398 free(oob_buffer->data);
5399 oob_buffer->data = NULL;
5400 }
5401 if (oob_buffer) {
5402 free(oob_buffer);
5403 oob_buffer = NULL;
5404 }
5405 index++;
5406 }
5407 ctx->oob_queue_bytesize = 0;
5408
5409 /* drain the oob receive fifo and the last handed-out buffer */
5410 while (ctx->oob_rx_queue_read_index != ctx->oob_rx_queue_write_index) {
5411 struct rist_buffer *rx_buffer = ctx->oob_rx_queue[ctx->oob_rx_queue_read_index];
5412 ctx->oob_rx_queue[ctx->oob_rx_queue_read_index] = NULL;
5413 if (rx_buffer)
5414 free_rist_buffer(ctx, rx_buffer);
5415 ctx->oob_rx_queue_read_index = (uint16_t)(ctx->oob_rx_queue_read_index + 1);
5416 }
5417 if (ctx->oob_rx_current) {
5418 free_rist_buffer(ctx, ctx->oob_rx_current);
5419 ctx->oob_rx_current = NULL;
5420 }
5421 }
5422
5423 void rist_receiver_destroy_local(struct rist_receiver *ctx)
5424 {
5425
5426 pthread_mutex_lock(&ctx->common.peerlist_lock);
5427
5428 // Destroy all flows
5429 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Starting Flows cleanup\n");
5430 struct rist_flow *f = ctx->common.FLOWS;
5431 while (f) {
5432 struct rist_flow *nextflow = f->next;
5433 rist_delete_flow(ctx, f);
5434 f = nextflow;
5435 }
5436 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Flows cleanup complete\n");
5437
5438 // Destroy all peers
5439 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Starting Peers cleanup\n");
5440 struct rist_peer *peer, *next;
5441 peer = ctx->common.PEERS;
5442 for (;;) {
5443 if (!peer)
5444 break;
5445 rist_peer_remove(&ctx->common, peer, &next);
5446 peer = next;
5447 }
5448 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Peers cleanup complete\n");
5449
5450 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5451
5452 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Freeing main data buffers\n");
5453 struct rist_buffer *b = ctx->common.rist_free_buffer;
5454 struct rist_buffer *next_buf;
5455 while (b) {
5456 next_buf = b->next_free;
5457 free_rist_buffer(&ctx->common, b);
5458 b = next_buf;
5459 }
5460 evsocket_destroy(ctx->common.evctx);
5461
5462 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Removing peerlist_lock\n");
5463 pthread_mutex_destroy(&ctx->common.peerlist_lock);
5464 if (ctx->common.oob_data_enabled) {
5465 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Freeing oob fifo queue\n");
5466 rist_empty_oob_queue(&ctx->common);
5467 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Removing oob_queue_lock\n");
5468 pthread_rwlock_destroy(&ctx->common.oob_queue_lock);
5469 }
5470
5471 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Removing data fifo signaling variables (condition and mutex)\n");
5472 pthread_cond_destroy(&ctx->condition);
5473 pthread_mutex_destroy(&ctx->mutex);
5474
5475 rist_logging_unset_global_if_matches(ctx->common.logging_settings);
5476
5477 free(ctx);
5478 ctx = NULL;
5479 }
5480
5481 void _librist_receiver_buffer_calc(struct rist_receiver *ctx) {
5482 pthread_mutex_lock(&ctx->common.peerlist_lock);
5483 struct rist_peer *p = ctx->common.PEERS;
5484 while (p != NULL) {
5485 if (p->config.recovery_length_max != p->config.recovery_length_min && !p->listening && p->sender_max_buffer_ticks > 0 && p->flow && p->rist_gre_version >= 2) {
5486 //Optimal default according to rist spec (multiplier configurable via API):
5487 int rtt_mult = ctx->common.recovery_rtt_multiplier > 0 ? ctx->common.recovery_rtt_multiplier : 7;
5488 uint64_t desired_buffer_level = (p->eight_times_rtt / 8) * rtt_mult + p->config.recovery_reorder_buffer;
5489
5490 bool has_high_loss = false;
5491 double modifier = 1.0;
5492
5493 //Modify our buffersize based on some magic numbers, these likely still need tuning
5494 pthread_mutex_lock(&p->flow->mutex);
5495 modifier += p->flow->stats_instant.lost * 0.05;//5% extra per packet lost
5496 if (p->flow->stats_instant.lost > 25)
5497 has_high_loss = true;
5498
5499 modifier += p->flow->stats_instant.recovered_morenack * 0.02;
5500 modifier += p->flow->stats_instant.recovered_3nack * 0.01;
5501 pthread_mutex_unlock(&p->flow->mutex);
5502
5503 desired_buffer_level *= modifier;
5504
5505 if (has_high_loss)
5506 desired_buffer_level = p->sender_max_buffer_ticks;
5507
5508
5509 if (desired_buffer_level < p->recovery_buffer_ticks && (p->recovery_buffer_ticks - desired_buffer_level) > 50 * RIST_CLOCK) {
5510 desired_buffer_level = p->recovery_buffer_ticks - 50 * RIST_CLOCK;
5511 }
5512
5513 uint64_t recovery_base_min = p->config.recovery_length_min * RIST_CLOCK;
5514 uint64_t recovery_base_max = p->config.recovery_length_max * RIST_CLOCK;
5515
5516 if (desired_buffer_level < recovery_base_min)
5517 desired_buffer_level = recovery_base_min;
5518 else if (desired_buffer_level > recovery_base_max)
5519 desired_buffer_level = recovery_base_max;
5520
5521 if (desired_buffer_level > p->sender_max_buffer_ticks)
5522 desired_buffer_level = p->sender_max_buffer_ticks;
5523
5524 if (p->recovery_buffer_ticks != desired_buffer_level)
5525 _librist_proto_gre_send_buffer_negotiation(p, 0, desired_buffer_level/ RIST_CLOCK);
5526
5527 p->recovery_buffer_ticks = desired_buffer_level;
5528 }
5529 p = p->next;
5530 }
5531 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5532 }
5533
5534 PTHREAD_START_FUNC(receiver_pthread_protocol, arg)
5535 {
5536 struct rist_receiver *ctx = (struct rist_receiver *) arg;
5537 uint64_t now = timestampNTP_u64();
5538 int max_oobperloop = 100;
5539 uint64_t no_flow_time_check = timestampNTP_u64();
5540
5541 uint64_t rist_nack_interval = (uint64_t)ctx->common.rist_max_jitter;
5542 int max_jitter_ms = ctx->common.rist_max_jitter / RIST_CLOCK;
5543 ctx->common.nacks_next_time = timestampNTP_u64();
5544 uint64_t checks_next_time = now;
5545 uint64_t buffer_check_next_time = now + ONE_SECOND;
5546 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Starting receiver protocol loop with %d ms timer\n", max_jitter_ms);
5547
5548 while (!atomic_load_explicit(&ctx->common.shutdown, memory_order_acquire)) {
5549 now = timestampNTP_u64();
5550 pthread_mutex_lock(&ctx->common.peerlist_lock);
5551 if (ctx->common.PEERS == NULL) {
5552 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5553 usleep(5000);
5554 continue;
5555 }
5556 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5557
5558 // Limit scope of `struct rist_flow *f` for clarity since it is used again later in this loop.
5559 {
5560 // stats and session timeout timer
5561 struct rist_flow *f = ctx->common.FLOWS;
5562 if (!f)
5563 {
5564 // no flow timeout callback
5565 if ((now - no_flow_time_check) > ONE_SECOND && ctx->receiver_session_timeout_callback) {
5566 no_flow_time_check = now;
5567 ctx->receiver_session_timeout_callback(ctx->receiver_session_timeout_callback_argument, 0);
5568 }
5569 }
5570 while (f) {
5571 no_flow_time_check = now;
5572 pthread_mutex_lock(&f->mutex);
5573 if (!f->receiver_queue_has_items) {
5574 pthread_mutex_unlock(&f->mutex);
5575 f = f->next;
5576 continue;
5577 }
5578 if (now > f->checks_next_time) {
5579 if (f->last_recv_ts == 0)
5580 f->last_recv_ts = now;
5581 uint64_t flow_age = (now - f->last_recv_ts);
5582 f->checks_next_time += f->recovery_buffer_ticks;
5583 if (flow_age > f->flow_timeout) {
5584 if (f->dead != 1) {
5585 f->dead = 1;
5586 rist_log_priv(&ctx->common, RIST_LOG_WARN,
5587 "Flow with id %"PRIu32" is dead, age is %"PRIu64"ms\n",
5588 f->flow_id, flow_age / RIST_CLOCK);
5589 }
5590 }
5591 else {
5592 if (f->dead != 0) {
5593 f->dead = 0;
5594 rist_log_priv(&ctx->common, RIST_LOG_INFO,
5595 "Flow with id %"PRIu32" was dead and is now alive again\n", f->flow_id);
5596 }
5597 }
5598 if (flow_age > f->session_timeout) {
5599 f->dead = 2;
5600 struct rist_flow *next = f->next;
5601 rist_receiver_flow_statistics(ctx, f);
5602 rist_log_priv(&ctx->common, RIST_LOG_INFO,
5603 "\t************** Session Timeout after %" PRIu64 "s of no data, deleting flow with id %"PRIu32" ***************\n",
5604 flow_age / RIST_CLOCK / 1000, f->flow_id);
5605 if (ctx->receiver_session_timeout_callback) {
5606 ctx->receiver_session_timeout_callback(ctx->receiver_session_timeout_callback_argument, f->flow_id);
5607 }
5608 pthread_mutex_unlock(&f->mutex);
5609 pthread_mutex_lock(&ctx->common.peerlist_lock);
5610 pthread_mutex_lock(&f->mutex);
5611 for (size_t i = 0; i < f->peer_lst_len; i++) {
5612 struct rist_peer *peer = f->peer_lst[i];
5613 peer->flow = NULL;
5614 }
5615 pthread_mutex_unlock(&f->mutex);
5616 rist_delete_flow(ctx, f);
5617 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5618 f = next;
5619 continue;
5620 }
5621 }
5622 if (now > f->stats_next_time) {
5623 f->stats_next_time += f->stats_report_time;
5624 rist_receiver_flow_statistics(ctx, f);
5625 }
5626 pthread_mutex_unlock(&f->mutex);
5627 f = f->next;
5628 }
5629 }
5630
5631 // TODO: rist_max_jitter should be proportional to the max bitrate according to the
5632 // following table
5633 //Mbps ms
5634 //125 8.00
5635 //250 4.00
5636 //520 1.92
5637 //1000 1.00
5638
5639 // socket polls (returns in max_jitter_ms max and processes the next 100 socket events)
5640 pthread_mutex_lock(&ctx->common.peerlist_lock);
5641 evsocket_loop_single(ctx->common.evctx, max_jitter_ms, 100);
5642 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5643 // keepalive timer
5644 receiver_peer_events(ctx, now);
5645
5646 // nacks timer
5647 if (now > ctx->common.nacks_next_time) {
5648 ctx->common.nacks_next_time += rist_nack_interval;
5649 // process nacks on every loop (5 ms interval max)
5650 struct rist_flow *f = ctx->common.FLOWS;
5651 while (f) {
5652 receiver_nack_output(ctx, f);
5653 f = f->next;
5654 }
5655 }
5656 /* marks peer as dead, run every second */
5657 if (now > checks_next_time)
5658 {
5659 checks_next_time += (uint64_t)50 * (uint64_t)RIST_CLOCK;
5660 pthread_mutex_lock(&ctx->common.peerlist_lock);
5661 rist_timeout_check(&ctx->common, now);
5662 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5663 }
5664 // Send oob data
5665 if (ctx->common.oob_queue_bytesize > 0)
5666 rist_oob_dequeue(&ctx->common, max_oobperloop);
5667
5668 if (now >= buffer_check_next_time) {
5669 _librist_receiver_buffer_calc(ctx);
5670 buffer_check_next_time += 2 * ONE_SECOND;
5671 }
5672
5673 }
5674 #ifdef _WIN32
5675 WSACleanup();
5676 #endif
5677 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Exiting master receiver loop\n");
5678 atomic_store_explicit(&ctx->common.shutdown, 2, memory_order_release);
5679
5680 return 0;
5681 }
5682
5683 void rist_sender_destroy_local(struct rist_sender *ctx)
5684 {
5685 rist_log_priv(&ctx->common, RIST_LOG_INFO,
5686 "Starting peers cleanup, count %d\n",
5687 (unsigned) ctx->peer_lst_len);
5688
5689 pthread_mutex_lock(&ctx->common.peerlist_lock); // Destroy all peers
5690 while (ctx->peer_lst_len > 0) {
5691 rist_peer_remove(&ctx->common, ctx->peer_lst[0], NULL);
5692 }
5693 struct rist_peer *peer, *next;
5694 peer = ctx->common.PEERS;
5695 for (;;) {
5696 if (!peer)
5697 break;
5698 rist_peer_remove(&ctx->common, peer, &next);
5699 peer = next;
5700 }
5701 evsocket_destroy(ctx->common.evctx);
5702
5703 pthread_mutex_unlock(&ctx->common.peerlist_lock);
5704 pthread_mutex_destroy(&ctx->common.peerlist_lock);
5705 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Peers cleanup complete\n");
5706
5707 if (ctx->common.oob_data_enabled) {
5708 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Freeing oob fifo queue\n");
5709 rist_empty_oob_queue(&ctx->common);
5710 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Removing oob_queue_lock\n");
5711 pthread_rwlock_destroy(&ctx->common.oob_queue_lock);
5712 }
5713
5714 rist_log_priv(&ctx->common, RIST_LOG_INFO, "Freeing up context memory allocations\n");
5715 free(ctx->sender_retry_queue);
5716 ctx->sender_retry_queue = NULL;
5717 struct rist_buffer *b = NULL;
5718 while(1) {
5719 b = ctx->sender_queue[ctx->sender_queue_delete_index];
5720 while (!b) {
5721 ctx->sender_queue_delete_index = (ctx->sender_queue_delete_index + 1)& (ctx->sender_queue_max -1);
5722 b = ctx->sender_queue[ctx->sender_queue_delete_index];
5723 if ((size_t)atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_relaxed) == ctx->sender_queue_delete_index)
5724 break;
5725 }
5726 if (b) {
5727 ctx->sender_queue_bytesize -= b->size;
5728 ctx->sender_queue_size--;
5729 free_rist_buffer(&ctx->common, b);
5730 ctx->sender_queue[ctx->sender_queue_delete_index] = NULL;
5731 }
5732 if ((size_t)atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire) == ctx->sender_queue_delete_index) {
5733 break;
5734 }
5735 ctx->sender_queue_delete_index = (ctx->sender_queue_delete_index + 1)& (ctx->sender_queue_max -1);
5736 }
5737
5738 rist_logging_unset_global_if_matches(ctx->common.logging_settings);
5739
5740 free(ctx->sender_queue);
5741 ctx->sender_queue = NULL;
5742 free(ctx->seq_index);
5743 ctx->seq_index = NULL;
5744 free(ctx->seq_rtp_index);
5745 ctx->seq_rtp_index = NULL;
5746 free(ctx);
5747 ctx = NULL;
5748 }