Debian Codegraph @

src/udp.c

raw symbols SCIP
1 /* librist. Copyright © 2019-2020 SipRadius LLC. All right reserved.
2 * Author: Daniele Lacamera <[email protected]>
3 * Author: Kuldeep Singh Dhaka <[email protected]>
4 * Author: Sergio Ammirata, Ph.D. <[email protected]>
5 *
6 * SPDX-License-Identifier: BSD-2-Clause
7 */
8
9 #include "logging.h"
10 #include "proto/gre.h"
11 #include "proto/protocol_gre.h"
12 #include "udp-private.h"
13 #include "rist-private.h"
14 #include "rist-retx-domain.h"
15 #include "log-private.h"
16 #include "socket-shim.h"
17 #include "endian-shim.h"
18 #include "proto/rist_time.h"
19 #include "proto/protocol_rtp.h"
20 #if HAVE_SRP_SUPPORT
21 #include "proto/eap.h"
22 #endif
23 #include "crypto/psk.h"
24 #include "mpegts.h"
25 #include <lz4.h>
26 #include "transport-private.h"
27 #include <stdlib.h>
28 #include <stddef.h>
29 #include <errno.h>
30 #include <stdint.h>
31 #include <assert.h>
32 #include <fcntl.h>
33
34 /* EMSGSIZE-aware send-failure logger, rate-limited to one line per peer
35 * every 5 seconds to avoid drowning the log when the application is
36 * pushing a stream of oversized packets. The hint on the PMTU case is
37 * deliberately explicit and actionable: an operator who sees this once
38 * should be able to fix it by lowering the application packet size
39 * (e.g. risttunnel -m), without having to chase ICMP filtering. */
40 void _librist_log_send_error(struct rist_peer *p, int sock_errno,
41 size_t attempted, const char *origin)
42 {
43 struct rist_common_ctx *ctx = get_cctx(p);
44 uint64_t now = timestampNTP_u64();
45 bool is_pmtu;
46 #ifdef _WIN32
47 is_pmtu = (sock_errno == WSAEMSGSIZE);
48 #else
49 is_pmtu = (sock_errno == EMSGSIZE);
50 #endif
51 if (is_pmtu) {
52 const uint64_t five_seconds = (uint64_t)5 * 65536 * 1000;
53 if (p->last_pmtu_error_log != 0 &&
54 now - p->last_pmtu_error_log < five_seconds)
55 return;
56 p->last_pmtu_error_log = now;
57 rist_log_priv(ctx, RIST_LOG_ERROR,
58 "PMTU exceeded sending %zu-byte datagram via %s (errno=%d). The path "
59 "MTU to this peer is smaller than our RIST packet size and the "
60 "don't-fragment bit is set, so the kernel refused to fragment. "
61 "Lower the application packet size (e.g. risttunnel -m, or upstream "
62 "MPEG-TS UDP size) so that payload + ~40 bytes of headers fits in the "
63 "path MTU. Further PMTU errors on this peer will be silenced for 5s.\n",
64 attempted, origin, sock_errno);
65 } else {
66 rist_log_priv(ctx, RIST_LOG_ERROR,
67 "Send failed via %s: errno=%d, size=%zu, socket=%d\n",
68 origin, sock_errno, attempted, p->sd);
69 }
70 }
71
72 size_t rist_send_seq_rtcp(struct rist_peer *p, uint32_t seq_rtp, uint8_t payload_type, uint8_t *payload, size_t payload_len, uint64_t source_time, uint16_t src_port, uint16_t dst_port, bool retry, uint16_t ts_null_bytes)
73 {
74 struct rist_common_ctx *ctx = get_cctx(p);
75 uint8_t *data;
76 size_t len;
77 size_t hdr_len = 0;
78 ssize_t ret = 0;
79
80 uint8_t *_payload = NULL;
81 _payload = payload;
82
83 /* Advanced Profile (VSF TR-06-3): build RTP-based packet directly,
84 * bypassing GRE framing entirely. Control and OOB are handled
85 * separately through rist_adv_send_control().
86 *
87 * TR-06-3 Section 9 (interop): an Advanced device "shall start in Main
88 * Profile mode" and only switch to Advanced framing for a peer once that
89 * peer advertises Advanced capability (I=1 in its Main keep-alives, which
90 * sets remote_supports_advanced). Until then we emit Main-conformant
91 * media so a Main-only peer can decode it. */
92 if (ctx->profile == RIST_PROFILE_ADVANCED &&
93 p->remote_supports_advanced &&
94 payload_type != RIST_PAYLOAD_TYPE_DATA_OOB &&
95 payload_type != RIST_PAYLOAD_TYPE_RTCP &&
96 payload_type != RIST_PAYLOAD_TYPE_RTCP_NACK) {
97 uint8_t adv_buf[RIST_MAX_PACKET_SIZE + RIST_ADV_MAX_FIXED_HEADER];
98 struct rist_adv_params params;
99 memset(&params, 0, sizeof(params));
100
101 params.seq = seq_rtp;
102 params.timestamp = timestampRTP_u32(1, source_time);
103 params.ssrc = rist_adv_ssrc_protected(ctx->adv_ssrc_base);
104 params.enc_type = RIST_ADV_TYPE_DIRECT;
105 params.psk_mode = RIST_ADV_PSK_NONE;
106 params.lpc_mode = RIST_ADV_LPC_NONE;
107 params.first_frag = true;
108 params.last_frag = true;
109 params.expedite = false;
110 params.retransmit = retry;
111
112 struct rist_adv_flow_id fid;
113 if (dst_port || src_port) {
114 fid.outer = htons(dst_port);
115 fid.inner_hi = (uint8_t)((src_port >> 4) & 0xFF);
116 fid.inner_lo_sub = (uint8_t)((src_port & 0x0F) << 4);
117 params.flow_id = &fid;
118 }
119
120 uint8_t *wire_payload = payload;
121 size_t wire_payload_len = payload_len;
122 uint8_t lz4_buf[RIST_MAX_PACKET_SIZE];
123 uint8_t enc_buf[RIST_MAX_PACKET_SIZE];
124 uint8_t psk_iv_bytes[RIST_ADV_PSK_IV_SIZE];
125
126 if (p->compression && payload_len > 0) {
127 int bound = LZ4_compressBound((int)payload_len);
128 if (bound > 0 && (size_t)bound <= sizeof(lz4_buf)) {
129 int clen = LZ4_compress_default((const char *)payload,
130 (char *)lz4_buf, (int)payload_len, (int)sizeof(lz4_buf));
131 if (clen > 0 && (size_t)clen < payload_len) {
132 wire_payload = lz4_buf;
133 wire_payload_len = (size_t)clen;
134 params.lpc_mode = RIST_ADV_LPC_LZ4;
135 }
136 }
137 }
138
139 if (p->key_tx.key_size > 0) {
140 uint32_t seq_nbe = htobe32(seq_rtp);
141 params.psk_mode = RIST_ADV_PSK_AES_CTR;
142 uint8_t old_nonce[4];
143 memcpy(old_nonce, p->key_tx.gre_nonce, 4);
144 _librist_crypto_psk_encrypt(&p->key_tx, seq_nbe, 1,
145 wire_payload, enc_buf, wire_payload_len);
146 if (p->key_tx.csprng_failed) {
147 rist_log_priv(ctx, RIST_LOG_ERROR,
148 "Advanced Profile: PSK encrypt failed (CSPRNG)\n");
149 return 0;
150 }
151 if (memcmp(old_nonce, p->key_tx.gre_nonce, 4) != 0)
152 rist_adv_send_psk_nonce(p, p->key_tx.gre_nonce,
153 (uint16_t)p->key_tx.key_size);
154 wire_payload = enc_buf;
155 params.psk_nonce = p->key_tx.gre_nonce;
156 memcpy(psk_iv_bytes, &seq_nbe, sizeof(seq_nbe));
157 params.psk_iv = psk_iv_bytes;
158 }
159
160 int total = rist_adv_build(adv_buf, &params, wire_payload, wire_payload_len);
161 if (total < 0) {
162 rist_log_priv(ctx, RIST_LOG_ERROR, "Advanced Profile: failed to build packet\n");
163 return 0;
164 }
165
166 if (RIST_UNLIKELY((p->sender_ctx && p->sender_ctx->simulate_loss) ||
167 (p->receiver_ctx && p->receiver_ctx->simulate_loss))) {
168 uint16_t loss_percentage = p->sender_ctx ?
169 p->sender_ctx->loss_percentage : p->receiver_ctx->loss_percentage;
170 uint16_t compare = rand() % 1001;
171 if (compare <= loss_percentage) {
172 ret = total;
173 goto adv_out;
174 }
175 }
176
177 int retries_count = 0;
178 int errorcode = 0;
179 do {
180 ret = rist_transport_sendto(p, adv_buf, (size_t)total, 0);
181 if (RIST_UNLIKELY(ret < 0)) {
182 errorcode = errno;
183 retries_count++;
184 } else {
185 errorcode = 0;
186 break;
187 }
188 } while (errorcode == EAGAIN && retries_count < RIST_MAX_SEND_RETRIES);
189
190 if (RIST_UNLIKELY(ret < 0))
191 _librist_log_send_error(p, errorcode, (size_t)total, "advanced-profile sendto");
192
193 adv_out:
194 if (ret > 0) {
195 p->stats_sender_instant.sent++;
196 p->stats_sender_instant.sent_bytes += (uint64_t)ret;
197 if (ts_null_bytes)
198 p->stats_sender_instant.ts_null++;
199 p->stats_receiver_instant.sent_rtcp++;
200 rist_calculate_bitrate((size_t)ret, &p->bw);
201 rist_calculate_bitrate(ts_null_bytes, &p->ts_nulls_bw);
202 }
203 return (size_t)ret;
204 }
205
206 // TODO: write directly on the payload to make it faster
207 uint8_t header_buf[RIST_MAX_HEADER_SIZE] = {0};
208 uint16_t proto_type;
209 if (RIST_UNLIKELY(payload_type == RIST_PAYLOAD_TYPE_DATA_OOB)) {
210 proto_type = RIST_GRE_PROTOCOL_TYPE_FULL;
211 } else {
212 proto_type = RIST_GRE_PROTOCOL_TYPE_REDUCED;
213 struct rist_protocol_hdr *hdr = (void *) (header_buf);
214 hdr->src_port = htobe16(src_port);
215 hdr->dst_port = htobe16(dst_port);
216 if (payload_type == RIST_PAYLOAD_TYPE_RTCP || payload_type == RIST_PAYLOAD_TYPE_RTCP_NACK)
217 {
218 hdr_len = RIST_GRE_PROTOCOL_REDUCED_SIZE;
219 }
220 else
221 {
222 hdr_len = sizeof(*hdr);
223 // RTP header for data packets
224 hdr->rtp.flags = RTP_MPEGTS_FLAGS;
225 if (payload_type == RIST_PAYLOAD_TYPE_DATA_RAW_RTP_EXT)
226 SET_BIT(hdr->rtp.flags, 4);
227 hdr->rtp.ssrc = htobe32(p->adv_flow_id);
228 hdr->rtp.seq = htobe16(seq_rtp);
229 if (retry)
230 {
231 // This is a retransmission
232 //rist_log_priv(&ctx->common, RIST_LOG_ERROR, "\tResending: %"PRIu32"/%"PRIu16"/%"PRIu32"\n", seq, seq_rtp, ctx->seq);
233 /* Mark SSRC for retransmission (change the last bit of the ssrc to 1) */
234 //hdr->rtp.ssrc |= (1 << 31);
235 hdr->rtp.ssrc = htobe32(p->adv_flow_id | 0x01);
236 }
237 hdr->rtp.payload_type = RTP_PTYPE_MPEGTS;
238 hdr->rtp.ts = htobe32(timestampRTP_u32(0, source_time));
239 }
240 // copy the rtp header data (needed for encryption)
241 memcpy(_payload - hdr_len, hdr, hdr_len);
242 }
243
244 if (RIST_UNLIKELY(payload_type == RIST_PAYLOAD_TYPE_DATA_OOB)) {
245 /* OOB uses GRE FULL protocol with no reduced/RTP header prepended,
246 so send the raw payload without the reduced-header offset */
247 len = payload_len;
248 data = _payload;
249 } else {
250 len = hdr_len + payload_len - RIST_GRE_PROTOCOL_REDUCED_SIZE;
251 data = _payload - hdr_len + RIST_GRE_PROTOCOL_REDUCED_SIZE;
252 }
253
254
255 // TODO: compare p->sender_ctx->sender_queue_read_index and p->sender_ctx->sender_queue_write_index
256 // and warn when the difference is a multiple of 10 (slow CPU or overtaxed algorithm)
257 // The difference should always stay very low < 10
258
259 if (RIST_UNLIKELY((p->sender_ctx && p->sender_ctx->simulate_loss) || (p->receiver_ctx && p->receiver_ctx->simulate_loss))) {
260 uint16_t loss_percentage = p->sender_ctx? p->sender_ctx->loss_percentage : p->receiver_ctx->loss_percentage;
261 /* very crude calculation to see if we "randomly" drop packets, good enough for testing */
262 uint16_t compare = rand() % 1001;
263 if (compare <= loss_percentage) {
264 ret = len;
265 goto out;
266 }
267 }
268
269 int retries = 0;
270 int errorcode = 0;
271 if (ctx->profile == RIST_PROFILE_SIMPLE) {
272 // retry when kernel buffer is full instead of dropping packet (EAGAIN)
273 do {
274 ret = rist_transport_sendto(p, data, len, 0);
275 if (RIST_UNLIKELY(ret < 0))
276 {
277 errorcode = errno;
278 retries++;
279 }
280 else {
281 errorcode = 0;
282 break;
283 }
284 } while (errorcode == EAGAIN && retries < RIST_MAX_SEND_RETRIES);
285 if (RIST_UNLIKELY(retries > (RIST_MAX_SEND_RETRIES / 5)))
286 rist_log_priv(ctx, RIST_LOG_WARN, "UDP Pacing Send Succeded after retries=%d, ret=%d, socket=%d\n", retries, ret, p->sd);
287 if (RIST_UNLIKELY(ret < 0))
288 _librist_log_send_error(p, errorcode, len, "simple-profile sendto");
289 }
290 else
291 ret = _librist_proto_gre_send_data(p, payload_type, proto_type, data, len, src_port, dst_port, p->rist_gre_version);
292
293 out:
294 if (RIST_UNLIKELY(ret <= 0 && ctx->profile == RIST_PROFILE_SIMPLE && errorcode == 0)) {
295 /* Generic safety net for ret == 0 or ret < 0 without errorcode
296 * captured (out-of-band failure paths). PMTU-aware send errors
297 * have already been logged above. */
298 rist_log_priv(ctx, RIST_LOG_ERROR, "\tSend failed: errno=%d, ret=%d, socket=%d\n", errno, ret, p->sd);
299 } else if (ret > 0) {
300 p->stats_sender_instant.sent++;
301 p->stats_sender_instant.sent_bytes += (uint64_t)ret;
302 if (ts_null_bytes)
303 p->stats_sender_instant.ts_null++;
304 p->stats_receiver_instant.sent_rtcp++;
305 }
306
307 return ret;
308 }
309
310 /* This function is used by receiver for all and by sender only for rist-data and oob-data */
311 int rist_send_common_rtcp(struct rist_peer *p, uint8_t payload_type, uint8_t *payload, size_t payload_len, uint64_t source_time, uint16_t src_port, uint16_t dst_port, uint32_t seq_rtp, uint16_t ts_null_bytes)
312 {
313 // This can only and will most likely be zero for data packets. RTCP should always have a value.
314 assert(payload_type != RIST_PAYLOAD_TYPE_DATA_RAW && payload_type != RIST_PAYLOAD_TYPE_DATA_RAW_RTP_EXT && payload_type != RIST_PAYLOAD_TYPE_DATA_OOB ? dst_port != 0 : 1);
315 if (dst_port == 0)
316 dst_port = p->config.virt_dst_port;
317 if (src_port == 0)
318 src_port = 32768 + p->adv_peer_id;
319
320 struct rist_common_ctx *cctx = get_cctx(p);
321 if (p->sd < 0 || !p->address_len) {
322 rist_log_priv(cctx, RIST_LOG_ERROR, "rist_send_common_rtcp failed\n");
323 return -1;
324 }
325
326 if (payload_type == RIST_PAYLOAD_TYPE_DATA_RAW || payload_type == RIST_PAYLOAD_TYPE_DATA_OOB)
327 {
328 if (cctx->oob_current_peer == NULL || cctx->oob_current_peer->dead)
329 cctx->oob_current_peer = p;
330 }
331
332 if (RIST_UNLIKELY(p->config.timing_mode == RIST_TIMING_MODE_ARRIVAL) && !p->receiver_mode)
333 source_time = timestampNTP_u64();
334
335 size_t ret = rist_send_seq_rtcp(p, seq_rtp, payload_type, payload, payload_len, source_time, src_port, dst_port, false, ts_null_bytes);
336
337 if ((!p->compression && ret < payload_len) || ret == (size_t)-1)
338 {
339 if (p->address_family == AF_INET6) {
340 // TODO: print IP and port (and error number?)
341 rist_log_priv(cctx, RIST_LOG_ERROR,
342 "\tError on transmission sendto for seq #%"PRIu32"\n", seq_rtp);
343 } else {
344 struct sockaddr_in *sin4 = (struct sockaddr_in *)&p->u.address;
345 unsigned char *ip = (unsigned char *)&sin4->sin_addr.s_addr;
346 rist_log_priv(cctx, RIST_LOG_ERROR,
347 "\tError on transmission sendto, ret=%d to %d.%d.%d.%d:%d/%d, seq #%"PRIu32", %d bytes\n",
348 ret, ip[0], ip[1], ip[2], ip[3], htons(sin4->sin_port),
349 p->local_port, seq_rtp, payload_len);
350 }
351 }
352 else
353 {
354 /* Advanced-profile media is already bitrate-accounted in
355 * rist_send_seq_rtcp (it builds and sends before this shared
356 * path); counting it again here would double-count p->bw. */
357 bool adv_media_accounted = (cctx->profile == RIST_PROFILE_ADVANCED &&
358 p->remote_supports_advanced &&
359 payload_type != RIST_PAYLOAD_TYPE_DATA_OOB &&
360 payload_type != RIST_PAYLOAD_TYPE_RTCP &&
361 payload_type != RIST_PAYLOAD_TYPE_RTCP_NACK);
362 if (!adv_media_accounted) {
363 // update bandwidth value
364 rist_calculate_bitrate(ret, &p->bw);
365 rist_calculate_bitrate(ts_null_bytes, &p->ts_nulls_bw);
366 }
367 }
368
369 // TODO:
370 // This should return something meaningful, however ret is always >= 0 by virtue of being unsigned.
371 /*if (ret >= 0)
372 * return 0;
373 * else
374 * return -1;
375 */
376 return 0;
377 }
378
379 int rist_set_url(struct rist_peer *peer)
380 {
381 char host[512];
382 uint16_t port = 0;
383 int local;
384 if (!peer->url) {
385 if (peer->local_port > 0) {
386 /* Put sender in IPv4 learning mode */
387 peer->address_family = AF_INET;
388 peer->address_len = sizeof(struct sockaddr_in);
389 memset(&peer->u.address, 0, sizeof(struct sockaddr_in));
390 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
391 "Sender: in learning mode\n");
392 }
393 return 1;
394 }
395 if (udpsocket_parse_url(peer->url, host, 512, &port, &local) != 0) {
396 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "%s / %s\n", strerror(errno), peer->url);
397 return -1;
398 } else {
399 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "URL parsed successfully: Host %s, Port %hu\n",
400 (char *) host, port);
401 }
402 if (udpsocket_resolve_host(host, port, &peer->u.address) < 0) {
403 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Host %s cannot be resolved\n",
404 (char *) host);
405 return -1;
406 }
407 if (peer->u.inaddr6.sin6_family == AF_INET6) {
408 peer->address_family = AF_INET6;
409 peer->address_len = sizeof(struct sockaddr_in6);
410 } else {
411 peer->address_family = AF_INET;
412 peer->address_len = sizeof(struct sockaddr_in);
413 }
414 if (local) {
415 peer->listening = 1;
416 peer->local_port = port;
417 } else {
418 peer->listening = 0;
419 peer->remote_port = port;
420 }
421 if (peer->address_family == AF_INET) {
422 peer->u.inaddr.sin_port = htons(port);
423 } else {
424 peer->u.inaddr6.sin6_port = htons(port);
425 }
426 return 0;
427 }
428
429 void rist_populate_cname(struct rist_peer *peer)
430 {
431 int fd = peer->sd;
432 char *identifier = peer->cname;
433 struct rist_common_ctx *ctx = get_cctx(peer);
434 if (strlen((char *)ctx->cname) != 0)
435 {
436 ctx->cname[RIST_MAX_HOSTNAME-1] = 0;
437 strncpy(identifier, (char * )ctx->cname, RIST_MAX_HOSTNAME);
438 return;
439 }
440 /* Set the CNAME Identifier as host@ip:port and fallback to hostname if needed */
441 char hostname[RIST_MAX_HOSTNAME];
442 struct sockaddr_storage peer_sockaddr;
443 peer_sockaddr.ss_family = AF_UNSPEC;
444 int name_length = 0;
445 socklen_t peer_socklen = sizeof(peer_sockaddr);
446 int ret_hostname = gethostname(hostname, RIST_MAX_HOSTNAME);
447 if (ret_hostname == -1) {
448 snprintf(hostname, RIST_MAX_HOSTNAME, "UnknownHost");
449 }
450
451 int ret_sockname = getsockname(fd, (struct sockaddr *)&peer_sockaddr, &peer_socklen);
452 if (ret_sockname == 0)
453 {
454 struct sockaddr *xsa = (struct sockaddr *)&peer_sockaddr;
455 // TODO: why is this returning non-sense?
456 if (xsa->sa_family == AF_INET) {
457 char addr[INET_ADDRSTRLEN] = {'\0'};
458 struct sockaddr_in *xin = (struct sockaddr_in*)&peer_sockaddr;
459 inet_ntop(AF_INET, &xin->sin_addr, addr, INET_ADDRSTRLEN);
460 if (strcmp(addr, "0.0.0.0") != 0) {
461 name_length = snprintf(identifier, RIST_MAX_HOSTNAME, "%s@%s:%u", hostname,
462 addr, ntohs(xin->sin_port));
463 if (name_length >= RIST_MAX_HOSTNAME)
464 identifier[RIST_MAX_HOSTNAME-1] = 0;
465 }
466 }/* else if (xsa->sa_family == AF_INET6) {
467 struct sockaddr_in6 *xin6 = (void*)peer;
468 char str[INET6_ADDRSTRLEN];
469 inet_ntop(xin6->sin6_family, &xin6->sin6_addr, str, sizeof(struct in6_addr));
470 name_length = snprintf(identifier, RIST_MAX_HOSTNAME, "%s@%s:%u", hostname,
471 str, ntohs(xin6->sin6_port));
472 if (name_length >= RIST_MAX_HOSTNAME)
473 identifier[RIST_MAX_HOSTNAME-1] = 0;
474 }*/
475 }
476
477 if (name_length == 0)
478 {
479 name_length = snprintf(identifier, RIST_MAX_HOSTNAME, "%s", hostname);
480 if (name_length >= RIST_MAX_HOSTNAME)
481 identifier[RIST_MAX_HOSTNAME-1] = 0;
482 }
483 }
484
485 void rist_create_socket(struct rist_peer *peer)
486 {
487 if(!peer->address_family && rist_set_url(peer)) {
488 return;
489 }
490
491 if (peer->listening) {
492 const char* host;
493 uint16_t port = 0;
494
495 char buffer[256];
496 if (peer->u.address.sa_family == AF_INET) {
497 struct sockaddr_in *addrv4 = (struct sockaddr_in *)&(peer->u);
498 host = inet_ntop(AF_INET, &(addrv4->sin_addr), buffer, sizeof(buffer));
499 port = htons(addrv4->sin_port);
500 } else {
501 struct sockaddr_in6 *addrv6 = (struct sockaddr_in6 *)&(peer->u);
502 host = inet_ntop(AF_INET6, &(addrv6->sin6_addr), buffer, sizeof(buffer));
503 port = htons(addrv6->sin6_port);
504 }
505 if (!host) {
506 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "failed to convert address to string (errno=%d)", errno);
507 return;
508 }
509
510 if (peer->u.address.sa_family == AF_INET)
511 {
512 struct sockaddr_in *addrv4 = (struct sockaddr_in *)&(peer->u);
513 peer->multicast_receiver = IN_MULTICAST(ntohl(addrv4->sin_addr.s_addr));
514 }
515 else
516 {
517 struct sockaddr_in6 *addrv6 = (struct sockaddr_in6 *)&(peer->u);
518 peer->multicast_receiver = IN6_IS_ADDR_MULTICAST(&addrv6->sin6_addr);
519 }
520
521 peer->sd = udpsocket_open_bind_mcast(host, port, peer->miface,
522 peer->config.multicast_ttl, peer->config.multicast_source);
523 if (peer->sd >= 0) {
524 if (port == 0)
525 {
526 // Populate peer->local_port with ephemeral port assigned
527 struct sockaddr_storage local_addr;
528 socklen_t n = sizeof( struct sockaddr_storage );
529 if( getsockname( peer->sd, (struct sockaddr *) &local_addr, &n ) != 0)
530 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Could not find assigned port (socket# %d)\n", peer->sd);
531 else
532 {
533 if (local_addr.ss_family == AF_INET) {
534 struct sockaddr_in *a = (struct sockaddr_in *)&local_addr;
535 port = a->sin_port;
536 } else {
537 /* ipv6 */
538 struct sockaddr_in6 *a = (struct sockaddr_in6 *)&local_addr;
539 port = a->sin6_port;
540 }
541 peer->local_port = port;
542 }
543 }
544 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Starting in URL listening mode (socket# %d)\n", peer->sd);
545 } else {
546 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Could not start in URL listening mode. %s\n", strerror(errno));
547 }
548
549 // Set non-blocking only for receive sockets
550 udpsocket_set_nonblocking(peer->sd);
551 }
552 else {
553 if (peer->u.address.sa_family == AF_INET)
554 {
555 struct sockaddr_in *addrv4 = (struct sockaddr_in *)&(peer->u);
556 peer->multicast_sender = IN_MULTICAST(ntohl(addrv4->sin_addr.s_addr));
557 }
558 else
559 {
560 struct sockaddr_in6 *addrv6 = (struct sockaddr_in6 *)&(peer->u);
561 peer->multicast_sender = IN6_IS_ADDR_MULTICAST(&addrv6->sin6_addr);
562 }
563 if (peer->multicast_sender) {
564 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Peer configured for multicast\n");
565 }
566 // We use sendto ... so, no need to connect directly here
567 peer->sd = udpsocket_open(peer->address_family);
568 if (peer->sd >= 0)
569 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Starting in URL connect mode (%d)\n", peer->sd);
570 else {
571 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Could not start in URL connect mode. %s\n", strerror(errno));
572 }
573 if (peer->miface[0] != '\0') {
574 struct sockaddr_storage ss = {0};
575 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Binding socket to %s\n", peer->miface);
576 if (inet_pton(AF_INET, peer->miface, &((struct sockaddr_in *)&ss)->sin_addr) != 0) {
577 ((struct sockaddr_in *)&ss)->sin_family = AF_INET;
578 ((struct sockaddr_in *)&ss)->sin_port = htons(peer->config.local_port);
579 if (bind(peer->sd, (struct sockaddr*)&ss, sizeof(struct sockaddr_in)) != 0) {
580 #ifdef _WIN32
581 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s:%u: WSAGetLastError=%d\n", peer->miface, peer->config.local_port, WSAGetLastError());
582 #else
583 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s:%u: %s\n", peer->miface, peer->config.local_port, strerror(errno));
584 #endif
585 }
586 }
587 else if (inet_pton(AF_INET6, peer->miface, &((struct sockaddr_in6 *)&ss)->sin6_addr) != 0) {
588 ((struct sockaddr_in6 *)&ss)->sin6_family = AF_INET6;
589 ((struct sockaddr_in6 *)&ss)->sin6_port = htons(peer->config.local_port);
590 if (bind(peer->sd, (struct sockaddr*)&ss, sizeof(struct sockaddr_in6)) != 0) {
591 #ifdef _WIN32
592 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s:%u: WSAGetLastError=%d\n", peer->miface, peer->config.local_port, WSAGetLastError());
593 #else
594 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s:%u: %s\n", peer->miface, peer->config.local_port, strerror(errno));
595 #endif
596 }
597 }
598 #ifdef __linux__
599 else {
600 struct ifreq ifr = {0};
601 memcpy(ifr.ifr_name, peer->miface, IF_NAMESIZE);
602 if (setsockopt(peer->sd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)) != 0) {
603 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s: %s\n", peer->miface, strerror(errno));
604 }
605 }
606 #elif defined(__APPLE__)
607 else {
608 int idx = if_nametoindex(peer->miface);
609 if (idx == 0) {
610 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't get device %s index: %s\n", peer->miface, strerror(errno));
611 } else {
612 int proto = peer->u.address.sa_family == AF_INET? IPPROTO_IP : IPPROTO_IPV6;
613 int bound = peer->u.address.sa_family == AF_INET? IP_BOUND_IF : IPV6_BOUND_IF;
614 if (setsockopt(peer->sd, proto, bound, &idx, sizeof(idx)) != 0) {
615 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Couldn't bind to %s: %s\n", peer->miface, strerror(errno));
616 }
617 }
618 }
619 #else
620 else {
621 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "No method available to bind to %s please supply an IP to bind to\n", peer->miface);
622 }
623 #endif
624 } else if (peer->config.local_port > 0) {
625 struct sockaddr_storage ss = {0};
626 if (peer->address_family == AF_INET6) {
627 ((struct sockaddr_in6 *)&ss)->sin6_family = AF_INET6;
628 ((struct sockaddr_in6 *)&ss)->sin6_port = htons(peer->config.local_port);
629 ((struct sockaddr_in6 *)&ss)->sin6_addr = in6addr_any;
630 } else {
631 ((struct sockaddr_in *)&ss)->sin_family = AF_INET;
632 ((struct sockaddr_in *)&ss)->sin_port = htons(peer->config.local_port);
633 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = INADDR_ANY;
634 }
635 socklen_t ss_len = peer->address_family == AF_INET6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);
636 if (bind(peer->sd, (struct sockaddr *)&ss, ss_len) != 0) {
637 #ifdef _WIN32
638 rist_log_priv(get_cctx(peer), RIST_LOG_WARN, "Couldn't bind to local port %u: WSAGetLastError=%d\n", peer->config.local_port, WSAGetLastError());
639 #else
640 rist_log_priv(get_cctx(peer), RIST_LOG_WARN, "Couldn't bind to local port %u: %s\n", peer->config.local_port, strerror(errno));
641 #endif
642 } else {
643 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Bound caller socket to local port %u\n", peer->config.local_port);
644 }
645 }
646 if (peer->multicast_sender && peer->config.multicast_ttl > 0)
647 udpsocket_set_mcast_ttl(peer->sd, peer->address_family, peer->config.multicast_ttl);
648 udpsocket_set_dontfragment(peer->sd, peer->address_family);
649 if (peer->config.local_port > 0)
650 peer->local_port = peer->config.local_port;
651 else
652 peer->local_port = 32768 + (get_cctx(peer)->peer_counter % 28232);
653 #ifdef _WIN32
654 udpsocket_set_nonblocking(peer->sd);
655 #endif
656 }
657
658 // Increase default OS udp receive buffer size
659 if (udpsocket_set_optimal_buffer_size(peer->sd)) {
660 rist_log_priv(get_cctx(peer), RIST_LOG_WARN, "Unable to set the socket receive buffer size to %d Bytes. %s\n",
661 UDPSOCKET_SOCK_BUFSIZE, strerror(errno));
662 } else {
663 uint32_t current_recvbuf = udpsocket_get_buffer_size(peer->sd);
664 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Configured the starting socket receive buffer size to %d Bytes.\n",
665 current_recvbuf);
666 }
667 // Increase default OS udp send buffer size
668 if (udpsocket_set_optimal_buffer_send_size(peer->sd)) {
669 rist_log_priv(get_cctx(peer), RIST_LOG_WARN, "Unable to set the socket send buffer size to %d Bytes. %s\n",
670 UDPSOCKET_SOCK_BUFSIZE, strerror(errno));
671 } else {
672 uint32_t current_sendbuf = udpsocket_get_buffer_send_size(peer->sd);
673 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Configured the starting socket send buffer size to %d Bytes.\n",
674 current_sendbuf);
675 }
676
677 if (peer->cname[0] == 0)
678 rist_populate_cname(peer);
679 rist_log_priv(get_cctx(peer), RIST_LOG_INFO, "Peer cname is %s\n", peer->cname);
680 #ifndef _WIN32
681 if (fcntl(peer->sd, F_SETFD, FD_CLOEXEC) == -1) {
682 udpsocket_close(peer->sd);
683 rist_log_priv(get_cctx(peer), RIST_LOG_ERROR, "Could not set close-on-exec\n");
684 peer->sd = -1;
685 }
686 #endif
687 }
688
689 int rist_receiver_periodic_rtcp(struct rist_peer *peer) {
690 uint8_t payload_type = RIST_PAYLOAD_TYPE_RTCP;
691 uint8_t *rtcp_buf = get_cctx(peer)->buf.rtcp;
692
693 int payload_len = 0;
694 rist_rtcp_write_rr(rtcp_buf, &payload_len, peer);
695 rist_rtcp_write_sdes(rtcp_buf, &payload_len, peer->cname, peer->adv_flow_id);
696 if (peer->echo_enabled == false)
697 rist_rtcp_write_xr_echoreq(rtcp_buf, &payload_len, peer);
698 rist_rtcp_write_echoreq(rtcp_buf, &payload_len, peer->peer_ssrc);
699 return rist_send_common_rtcp(peer, payload_type, &rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, 0, peer->local_port, peer->remote_port, 0, 0);
700 }
701
702 static int rist_receiver_send_nacks_advanced(struct rist_peer *peer, uint32_t seq_array[], size_t array_len)
703 {
704 struct rist_common_ctx *ctx = get_cctx(peer);
705 uint32_t media_ssrc = rist_adv_ssrc_protected(ctx->adv_ssrc_base);
706
707 if (peer->receiver_ctx->nack_type == RIST_NACK_BITMASK) {
708 uint32_t pss = seq_array[0];
709 uint32_t blp = 0;
710 for (size_t i = 1; i < array_len; i++) {
711 uint32_t offset = seq_array[i] - pss;
712 if (offset >= 1 && offset <= 32) {
713 blp |= (1u << (offset - 1));
714 } else {
715 rist_adv_send_nack_bitmask(peer, media_ssrc, pss, blp);
716 pss = seq_array[i];
717 blp = 0;
718 }
719 }
720 rist_adv_send_nack_bitmask(peer, media_ssrc, pss, blp);
721 } else {
722 uint32_t pss = seq_array[0];
723 uint32_t nalp = 0;
724 for (size_t i = 1; i < array_len; i++) {
725 if (seq_array[i] == pss + nalp + 1) {
726 nalp++;
727 } else {
728 rist_adv_send_nack_range(peer, media_ssrc, pss, nalp);
729 pss = seq_array[i];
730 nalp = 0;
731 }
732 }
733 rist_adv_send_nack_range(peer, media_ssrc, pss, nalp);
734 }
735 return 0;
736 }
737
738 int rist_receiver_send_nacks(struct rist_peer *peer, uint32_t seq_array[], size_t array_len)
739 {
740 if (get_cctx(peer)->debug && array_len > 0)
741 rist_log_priv(get_cctx(peer), RIST_LOG_DEBUG, "Sending %zu nacks starting with %"PRIu32"\n",
742 array_len, seq_array[0]);
743
744 if (get_cctx(peer)->profile == RIST_PROFILE_ADVANCED &&
745 peer->is_advanced && peer->remote_supports_advanced &&
746 array_len > 0) {
747 return rist_receiver_send_nacks_advanced(peer, seq_array, array_len);
748 }
749
750 uint8_t payload_type = RIST_PAYLOAD_TYPE_RTCP;
751 uint8_t *rtcp_buf = get_cctx(peer)->buf.rtcp;
752
753 int payload_len = 0;
754 rist_rtcp_write_empty_rr(rtcp_buf, &payload_len, peer->adv_flow_id);
755 rist_rtcp_write_sdes(rtcp_buf, &payload_len, peer->cname, peer->adv_flow_id);
756 if (RIST_LIKELY(array_len > 0)) {
757 struct rist_rtp_nack_record *rec;
758 uint32_t fci_count = 1;
759
760 if (peer->receiver_ctx->nack_type == RIST_NACK_BITMASK)
761 {
762 struct rist_rtcp_nack_bitmask *rtcp = (struct rist_rtcp_nack_bitmask *)(rtcp_buf + RIST_MAX_PAYLOAD_OFFSET + payload_len);
763 rtcp->flags = RTCP_NACK_BITMASK_FLAGS;
764 rtcp->ptype = PTYPE_NACK_BITMASK;
765 rtcp->ssrc_source = 0; // TODO
766 rtcp->ssrc = htobe32(peer->adv_flow_id);
767 rec = (struct rist_rtp_nack_record *)(rtcp_buf + RIST_MAX_PAYLOAD_OFFSET + payload_len + RTCP_FB_HEADER_SIZE);
768 uint32_t last_seq, tmp_seq;
769 tmp_seq = last_seq = seq_array[0];
770 uint32_t boundary = tmp_seq +16;
771 rec->start = htons((uint16_t)tmp_seq);
772 uint16_t extra = 0;
773 for (size_t i = 1; i < array_len; i++)
774 {
775 tmp_seq = seq_array[i];
776 if (last_seq < tmp_seq && tmp_seq <= boundary) {
777 uint32_t bitnum = tmp_seq - last_seq;
778 SET_BIT(extra, (bitnum -1));
779 } else {
780 rec->extra = htons(extra);
781 rec++;
782 fci_count++;
783 extra = 0;
784 rec->start = htons((uint16_t)tmp_seq);
785 last_seq = tmp_seq;
786 boundary = tmp_seq + 16;
787 }
788 }
789 rec->extra = htons(extra);
790 rtcp->len = htons((uint16_t)(2 + fci_count));
791 }
792 else // PTYPE_NACK_CUSTOM
793 {
794 struct rist_rtcp_nack_range *rtcp = (struct rist_rtcp_nack_range *)(rtcp_buf + RIST_MAX_PAYLOAD_OFFSET + payload_len);
795 rtcp->flags = RTCP_NACK_RANGE_FLAGS;
796 rtcp->ptype = PTYPE_NACK_CUSTOM;
797 rtcp->ssrc_source = htobe32(peer->adv_flow_id);
798 memcpy(rtcp->name, "RIST", 4);
799 rec = (struct rist_rtp_nack_record *)(rtcp_buf + RIST_MAX_PAYLOAD_OFFSET + payload_len + RTCP_FB_HEADER_SIZE);
800 uint16_t tmp_seq = (uint16_t)seq_array[0];
801 uint16_t last_seq = tmp_seq;
802 rec->start = htons(tmp_seq);
803 uint16_t extra = 0;
804 for (size_t i = 1; i < array_len; i++)
805 {
806 tmp_seq = (uint16_t)seq_array[i];
807 if (RIST_UNLIKELY(extra == UINT16_MAX)) {
808 rec->extra = htons(extra);
809 rec++;
810 fci_count++;
811 rec->start = htons(tmp_seq);
812 extra = 0;
813 } else if (tmp_seq == last_seq +1) {
814 extra++;
815 } else {
816 rec->extra = htons(extra);
817 rec++;
818 fci_count++;
819 rec->start = htons(tmp_seq);
820 extra = 0;
821 }
822 last_seq = tmp_seq;
823 }
824 rec->extra = htons(extra);
825 rtcp->len = htons((uint16_t)(2 + fci_count));
826 }
827 int nack_bufsize = RTCP_FB_HEADER_SIZE + RTCP_FB_FCI_GENERIC_NACK_SIZE * fci_count;
828 payload_len += nack_bufsize;
829 payload_type = RIST_PAYLOAD_TYPE_RTCP_NACK;
830 }
831
832 // We use direct send from receiver to sender (no fifo to keep track of seq/idx)
833 return rist_send_common_rtcp(peer, payload_type, &rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, 0, peer->local_port, peer->remote_port, 0, 0);
834 }
835
836 static void rist_sender_send_rtcp(uint8_t *rtcp_buf, int payload_len, struct rist_peer *peer) {
837 rist_send_common_rtcp(peer, RIST_PAYLOAD_TYPE_RTCP, rtcp_buf, payload_len, 0, peer->local_port, peer->remote_port, 0, 0);
838 }
839
840 void rist_sender_periodic_rtcp(struct rist_peer *peer) {
841 uint8_t *rtcp_buf = get_cctx(peer)->buf.rtcp;
842 int payload_len = 0;
843
844 rist_rtcp_write_sr(rtcp_buf, &payload_len, peer);
845 rist_rtcp_write_sdes(rtcp_buf, &payload_len, peer->cname, peer->adv_flow_id);
846 if (peer->echo_enabled)
847 rist_rtcp_write_echoreq(rtcp_buf, &payload_len, peer->peer_ssrc);
848 // Push it to the FIFO buffer to be sent ASAP (even in the simple profile case)
849 rist_sender_send_rtcp(&rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, peer);
850 return;
851 }
852
853 int rist_respond_echoreq(struct rist_peer *peer, const uint64_t echo_request_time, uint32_t ssrc) {
854 uint8_t *rtcp_buf = get_cctx(peer)->buf.rtcp;
855 int payload_len = 0;
856 rist_rtcp_write_empty_rr(rtcp_buf, &payload_len, peer->adv_flow_id);
857 rist_rtcp_write_sdes(rtcp_buf, &payload_len, peer->cname, peer->adv_flow_id);
858 rist_rtcp_write_echoresp(rtcp_buf, &payload_len, echo_request_time, ssrc);
859 if (peer->receiver_mode) {
860 uint8_t payload_type = RIST_PAYLOAD_TYPE_RTCP;
861 return rist_send_common_rtcp(peer, payload_type, &rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, 0, peer->local_port, peer->remote_port, 0, 0);
862 } else {
863 /* I do this to not break advanced mode, however echo responses should really NOT be resend when lost ymmv */
864 rist_sender_send_rtcp(&rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, peer);
865 return 0;
866 }
867 }
868
869 int rist_request_echo(struct rist_peer *peer) {
870 uint8_t *rtcp_buf = get_cctx(peer)->buf.rtcp;
871 int payload_len = 0;
872 rist_rtcp_write_empty_rr(rtcp_buf, &payload_len, peer->adv_flow_id);
873 rist_rtcp_write_sdes(rtcp_buf, &payload_len, peer->cname, peer->adv_flow_id);
874 rist_rtcp_write_echoreq(rtcp_buf, &payload_len, peer->peer_ssrc);
875 if (peer->receiver_mode)
876 {
877 uint8_t payload_type = RIST_PAYLOAD_TYPE_RTCP;
878 return rist_send_common_rtcp(peer, payload_type, &rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, 0, peer->local_port, peer->remote_port, 0, 0);
879 }
880 else
881 {
882 rist_sender_send_rtcp(&rtcp_buf[RIST_MAX_PAYLOAD_OFFSET], payload_len, peer);
883 return 0;
884 }
885 }
886
887 int rist_sender_enqueue(struct rist_sender *ctx, const void *data, size_t len, uint64_t datagram_time, uint16_t src_port, uint16_t dst_port, uint32_t seq_rtp)
888 {
889 uint8_t payload_type = RIST_PAYLOAD_TYPE_DATA_RAW;
890 const void * payload = data;
891 if (ctx->common.PEERS == NULL) {
892 // Do not cache data if the lib user has not added peers
893 return -1;
894 }
895
896 /* insert into sender fifo queue */
897
898 pthread_mutex_lock(&ctx->queue_lock);
899 size_t sender_write_index = atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire);
900 if (RIST_UNLIKELY(ctx->sender_queue_size >= ctx->sender_queue_max - 1)) {
901 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "\nSender queue is full (size=%zu max=%zu), dropping packet, decrease bitrate, buffer time length or increase packet size\n",
902 ctx->sender_queue_size,
903 ctx->sender_queue_max);
904 // Another solution is to increase the size of RIST_SERVER_QUEUE_BUFFERS at compile time
905 pthread_mutex_unlock(&ctx->queue_lock);
906 return -2;
907 }
908
909 ctx->last_datagram_time = datagram_time;
910 /* Worst-case write into payload_out is (count - 1) * 204 = 6 * 204 = 1224
911 * bytes (if exactly one of the seven 204-byte packets is suppressed),
912 * sitting after the 8-byte rist_rtp_hdr_ext at offset 0. The previous
913 * sizing of 6 * 204 + 4 was 4 bytes short and let suppress_null_packets
914 * smash four bytes of stack past tmp_buf. */
915 uint8_t tmp_buf[7 * 204 + sizeof(struct rist_rtp_hdr_ext)];
916 int ts_null_bytes = 0;
917 if (ctx->null_packet_suppression && len <= 7 * 204)
918 {
919
920 struct rist_rtp_hdr_ext *hdr_ext = (struct rist_rtp_hdr_ext *)&tmp_buf;
921 memset(tmp_buf, 0, sizeof(*hdr_ext));//hdr_ext
922 ts_null_bytes = suppress_null_packets(data, &tmp_buf[sizeof(*hdr_ext)], &len, hdr_ext);
923 if (ts_null_bytes > 0)
924 {
925 memcpy(&hdr_ext->identifier, "RI", 2);
926 hdr_ext->length = htobe16(1);
927 len += sizeof(*hdr_ext);
928 payload = tmp_buf;
929 payload_type = RIST_PAYLOAD_TYPE_DATA_RAW_RTP_EXT;
930 }
931 }
932
933 ctx->sender_queue[sender_write_index] = rist_new_buffer(&ctx->common, payload, len, payload_type, 0, datagram_time, src_port, dst_port);
934 if (RIST_UNLIKELY(!ctx->sender_queue[sender_write_index])) {
935 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "\t Could not create packet buffer inside sender buffer, OOM\n");
936 pthread_mutex_unlock(&ctx->queue_lock);
937 return -3;
938 }
939 ctx->sender_queue[sender_write_index]->seq_rtp = (uint16_t)seq_rtp;
940 ctx->sender_queue[sender_write_index]->ts_null_bytes = (uint16_t)ts_null_bytes;
941 ctx->sender_queue_bytesize += len;
942 ctx->sender_queue_size++;
943 atomic_store_explicit(&ctx->sender_queue_write_index, (sender_write_index + 1) & (ctx->sender_queue_max - 1), memory_order_release);
944 pthread_mutex_unlock(&ctx->queue_lock);
945
946 return 0;
947 }
948
949 /* Share this leg should take in the weighted payload rotation. Normally the
950 * configured weight, but a leg that just rejoined after an RTT mute ramps back
951 * linearly over the rejoin dwell: it drained while muted, so it measures well
952 * until it carries again, and handing back the full share at once simply
953 * refills the queue and mutes it a second later. */
954 static uint32_t rist_peer_effective_weight(const struct rist_peer *peer, uint64_t now)
955 {
956 /* Ramp over the rejoin dwell, which is twice the drop dwell. */
957 return rist_rtt_ramped_weight(peer->config.weight, peer->rtt_ramp_start,
958 (uint64_t)peer->config.rtt_drop_settle * RIST_CLOCK * 2,
959 now);
960 }
961
962 void rist_sender_send_data_balanced(struct rist_sender *ctx, struct rist_buffer *buffer)
963 {
964 struct rist_peer *peer;
965 struct rist_peer *selected_peer_by_weight = NULL;
966 struct rist_peer *fallback = NULL;
967 uint64_t fallback_rtt = UINT64_MAX;
968 uint32_t max_remainder = 0;
969 int peercnt;
970 bool looped = false;
971
972 //We can do it safely here, since this function is only to be called once per packet
973 buffer->seq = ctx->common.seq++;
974 uint32_t wire_seq = (ctx->common.profile == RIST_PROFILE_ADVANCED) ? buffer->seq : (uint32_t)buffer->seq_rtp;
975 uint64_t now = timestampNTP_u64();
976
977 peer_select:
978
979 peercnt = 0;
980 for (peer = ctx->common.PEERS; peer; peer = peer->next) {
981
982 if (!peer->is_data || peer->parent)
983 continue;
984 #if HAVE_SRP_SUPPORT
985 if (!peer->listening && !peer->multicast_sender && !eap_is_authenticated(peer->eap_ctx))
986 continue;
987 #endif
988 bool hard_dead = !rist_peer_may_send(peer->dead, peer->dead_since,
989 peer->recovery_buffer_ticks, now);
990 if ((!peer->listening && !peer->authenticated) || hard_dead
991 || (peer->listening && !peer->child_alive_count)) {
992 ctx->weight_counter -= peer->config.weight;
993 if (ctx->weight_counter <= 0) {
994 ctx->weight_counter = ctx->total_weight;
995 }
996 peer->w_count = rist_peer_effective_weight(peer, now);
997 continue;
998 }
999
1000 /* RTT-muted leg: skipped in the unique-payload rotation. With
1001 * ?rtt-drop-trickle=N, still send a deduped duplicate every Nth packet
1002 * so RTT keeps sampling for a warm restore without stalling the buffer.
1003 * A stalled (briefly silent) leg is skipped too but never trickled: its
1004 * return path is down, so RTCP/keepalive alone probes for recovery.
1005 * The trickle also stops once the leg is queued deeper than the buffer,
1006 * where it can only deliver unusable packets; RTCP keeps measuring RTT,
1007 * and with nothing queued behind them those measurements get honest. */
1008 if (peer->rtt_muted || peer->stalled) {
1009 if (peer->rtt_muted && peer->config.rtt_drop_trickle > 0 && !looped && !peer->dead
1010 && rist_rtt_trickle_useful(peer->eight_times_rtt / 8,
1011 (uint64_t)peer->config.recovery_length_max * RIST_CLOCK)) {
1012 if (++peer->rtt_trickle_counter >= peer->config.rtt_drop_trickle) {
1013 peer->rtt_trickle_counter = 0;
1014 uint8_t *payload = buffer->data;
1015 rist_send_common_rtcp(peer, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, wire_seq, buffer->ts_null_bytes);
1016 }
1017 }
1018 ctx->weight_counter -= peer->config.weight;
1019 if (ctx->weight_counter <= 0) {
1020 ctx->weight_counter = ctx->total_weight;
1021 }
1022 peer->w_count = rist_peer_effective_weight(peer, now);
1023 /* Remember the best skipped leg for the safety net below: a
1024 * muted (late but deliverable) leg beats a stalled one (return
1025 * path down); lowest RTT breaks ties. */
1026 if (!peer->dead) {
1027 uint64_t s = peer->eight_times_rtt ? peer->eight_times_rtt / 8 : UINT64_MAX;
1028 if (!fallback
1029 || (fallback->stalled && !peer->stalled)
1030 || (fallback->stalled == peer->stalled && s < fallback_rtt)) {
1031 fallback = peer;
1032 fallback_rtt = s;
1033 }
1034 }
1035 continue;
1036 }
1037 peercnt++;
1038
1039 /*************************************/
1040 /* * * * * * * * * * * * * * * * * * */
1041 /** Heuristics for sender goes here **/
1042 /* * * * * * * * * * * * * * * * * * */
1043 /*************************************/
1044
1045 if (peer->config.weight == RIST_PEER_WEIGHT_DUPLICATE && !looped) {
1046 if (peer->listening) {
1047 struct rist_peer *child = peer->child;
1048 while (child) {
1049 #if HAVE_SRP_SUPPORT
1050 if (!eap_is_authenticated(child->eap_ctx))
1051 {
1052 //do nothing
1053 } else
1054 #endif
1055 if (child->authenticated && child->is_data && rist_peer_may_send(child->dead, child->dead_since, peer->recovery_buffer_ticks, now)) {
1056 uint8_t *payload = buffer->data;
1057 rist_send_common_rtcp(child, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, wire_seq, buffer->ts_null_bytes);
1058 }
1059 child = child->sibling_next;
1060 }
1061 } else {
1062 /* Eligibility already decided by hard_dead above. */
1063 uint8_t *payload = buffer->data;
1064 rist_send_common_rtcp(peer, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, wire_seq, buffer->ts_null_bytes);
1065 }
1066 } else {
1067 /* Election of next peer */
1068 // printf("peer election: considering %p, count=%d (wc: %d)\n",
1069 // peer, peer->w_count, ctx->weight_counter);
1070 if (peer->w_count > max_remainder) {
1071 max_remainder = peer->w_count;
1072 selected_peer_by_weight = peer;
1073 }
1074 }
1075 }
1076 looped = true;
1077 if (selected_peer_by_weight) {
1078 peer = selected_peer_by_weight;
1079 if (peer->listening) {
1080 struct rist_peer *child = peer->child;
1081 while (child) {
1082 #if HAVE_SRP_SUPPORT
1083 if (!eap_is_authenticated(child->eap_ctx))
1084 {
1085 //do nothing
1086 } else
1087 #endif
1088 if (child->authenticated && child->is_data && rist_peer_may_send(child->dead, child->dead_since, peer->recovery_buffer_ticks, now)) {
1089 uint8_t *payload = buffer->data;
1090 rist_send_common_rtcp(child, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, wire_seq, buffer->ts_null_bytes);
1091 }
1092 child = child->sibling_next;
1093 }
1094 } else {
1095 /* Eligibility already decided by hard_dead above. */
1096 uint8_t *payload = buffer->data;
1097 rist_send_common_rtcp(peer, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, wire_seq, buffer->ts_null_bytes);
1098 }
1099 ctx->weight_counter--;
1100 peer->w_count--;
1101 }
1102
1103 if (ctx->total_weight > 0 && (ctx->weight_counter == 0 || !selected_peer_by_weight)) {
1104 peer = ctx->common.PEERS;
1105 ctx->weight_counter = ctx->total_weight;
1106 for (; peer; peer = peer->next) {
1107 peer->w_count = rist_peer_effective_weight(peer, now);
1108 }
1109 if (!looped && !selected_peer_by_weight && peercnt > 0)
1110 goto peer_select;
1111 }
1112
1113 /* Safety net: every eligible leg was rtt-muted or stalled, so nothing
1114 * carried this packet. The mute and stall guards run independently and
1115 * can jointly leave no carrier; never silently drop a live packet when a
1116 * usable leg exists. Egress on the best skipped leg. */
1117 if (peercnt == 0 && !selected_peer_by_weight && fallback) {
1118 uint8_t *payload = buffer->data;
1119 rist_send_common_rtcp(fallback, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, buffer->src_port, buffer->dst_port, wire_seq, buffer->ts_null_bytes);
1120 }
1121 }
1122
1123 static size_t rist_sender_index_get(struct rist_sender *ctx, uint32_t seq,
1124 const struct rist_peer *target)
1125 {
1126 if (ctx->common.profile == RIST_PROFILE_ADVANCED) {
1127 /* A peer that negotiated down to Main NACKs in the 16-bit RTP
1128 * sequence domain (nack_seq_msb = 0), which never matches the
1129 * 32-bit advanced seq_index. Serve its retransmits from the
1130 * parallel RTP index. Advanced-negotiated peers keep the 32-bit
1131 * path, so the production Advanced<->Advanced lookup is unchanged. */
1132 if (ctx->seq_rtp_index && target &&
1133 rist_retx_use_rtp_domain(ctx->common.profile, target->remote_supports_advanced))
1134 return ctx->seq_rtp_index[(uint16_t)seq];
1135 return ctx->seq_index[seq & (ctx->sender_queue_max - 1)];
1136 }
1137 return ctx->seq_index[(uint16_t)seq];
1138 }
1139
1140 size_t rist_get_sender_retry_queue_size(struct rist_sender *ctx)
1141 {
1142 size_t retry_queue_size = (ctx->sender_retry_queue_write_index - ctx->sender_retry_queue_read_index)
1143 & (ctx->sender_retry_queue_size - 1);
1144 return retry_queue_size;
1145 }
1146
1147 /* Pick the lowest-RTT healthy bonded sibling in the same sequence domain to
1148 * egress a retransmit when the NACK's own leg is RTT-muted or stalled (its
1149 * latency/silence would make the recovery packet arrive too late). Returns the
1150 * original leg if none qualifies. Caller holds peerlist_lock. */
1151 static struct rist_peer *rist_retx_healthy_egress(struct rist_sender *ctx,
1152 struct rist_peer *muted)
1153 {
1154 uint64_t now = timestampNTP_u64();
1155 struct rist_peer *best = NULL;
1156 uint64_t best_rtt = UINT64_MAX;
1157 for (struct rist_peer *peer = ctx->common.PEERS; peer; peer = peer->next) {
1158 if (!peer->is_data || peer->parent || peer->listening)
1159 continue;
1160 if (peer->rtt_muted || peer->stalled || !peer->authenticated)
1161 continue;
1162 if (!rist_peer_may_send(peer->dead, peer->dead_since, peer->recovery_buffer_ticks, now))
1163 continue;
1164 struct rist_peer *egress = peer->peer_data ? peer->peer_data : peer;
1165 if (egress->remote_supports_advanced != muted->remote_supports_advanced)
1166 continue;
1167 uint64_t rtt = egress->eight_times_rtt ? egress->eight_times_rtt : UINT64_MAX;
1168 if (rtt < best_rtt) {
1169 best_rtt = rtt;
1170 best = egress;
1171 }
1172 }
1173 return best ? best : muted;
1174 }
1175
1176 /* This function must return, 0 when there is nothing to send, < 0 on error and > 0 for bytes sent */
1177 ssize_t rist_retry_dequeue(struct rist_sender *ctx)
1178 {
1179 size_t sender_retry_queue_read_index = (ctx->sender_retry_queue_read_index + 1)& (ctx->sender_retry_queue_size -1);
1180
1181 if (sender_retry_queue_read_index == ctx->sender_retry_queue_write_index) {
1182 return 0;
1183 }
1184
1185 ctx->sender_retry_queue_read_index = sender_retry_queue_read_index;
1186 struct rist_retry *retry = &ctx->sender_retry_queue[ctx->sender_retry_queue_read_index];
1187
1188 /* The peer this retry belongs to may have been destroyed while this
1189 * entry was sitting in the queue. rist_peer_remove() scrubs the slot
1190 * to NULL under peerlist_lock, and we are called with peerlist_lock
1191 * held, so seeing NULL here simply means the retry is stale; drop
1192 * it and let the caller move on to the next entry (returning 0 would
1193 * abort sender_send_nacks() and starve legitimate retries queued
1194 * behind this one). */
1195 if (RIST_UNLIKELY(!retry->peer)) {
1196 retry->active = false;
1197 return -1;
1198 }
1199
1200 /* The peer that will actually receive this retransmission. Its
1201 * negotiated profile (remote_supports_advanced) decides both the
1202 * retransmit framing (rist_send_seq_rtcp) and, for an Advanced sender,
1203 * which sequence domain to resolve the request in. */
1204 struct rist_peer *idx_target = retry->peer->peer_data ? retry->peer->peer_data : retry->peer;
1205 bool main_domain_retx = rist_retx_use_rtp_domain(ctx->common.profile,
1206 idx_target->remote_supports_advanced);
1207
1208 /* Redirect off a muted/stalled leg to a healthy sibling (unchanged when
1209 * none qualifies, so no behaviour change unless a leg was pulled). */
1210 struct rist_peer *egress = idx_target;
1211 if (idx_target->rtt_muted || idx_target->stalled)
1212 egress = rist_retx_healthy_egress(ctx, idx_target);
1213
1214 // If they request a non-sense seq number, we will catch it when we check the seq number against
1215 // the one on that buffer position and it does not match
1216
1217 size_t idx = rist_sender_index_get(ctx, retry->seq, idx_target);
1218 if (RIST_UNLIKELY(ctx->sender_queue[idx] == NULL)) {
1219 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1220 " Couldn't find block %" PRIu32 " (i=%zu/r=%zu/w=%zu/d=%zu/rs=%zu), consider increasing the buffer size\n",
1221 retry->seq, idx, atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire), atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire), ctx->sender_queue_delete_index,
1222 rist_get_sender_retry_queue_size(ctx));
1223 retry->peer->stats_sender_instant.retrans_skip++;
1224 return -1;
1225 } else if (RIST_UNLIKELY(
1226 (ctx->common.profile == RIST_PROFILE_ADVANCED && !main_domain_retx)
1227 ? (retry->seq != ctx->sender_queue[idx]->seq)
1228 : ((uint16_t)retry->seq != ctx->sender_queue[idx]->seq_rtp))) {
1229 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1230 " Couldn't find block %" PRIu32 " (i=%zu/r=%zu/w=%zu/d=%zu/rs=%zu), found an old one instead %" PRIu32 " (%" PRIu64 "), bitrate is too high\n",
1231 retry->seq, idx, atomic_load_explicit(&ctx->sender_queue_read_index, memory_order_acquire), atomic_load_explicit(&ctx->sender_queue_write_index, memory_order_acquire), ctx->sender_queue_delete_index,
1232 rist_get_sender_retry_queue_size(ctx), ctx->sender_queue[idx]->seq, ctx->sender_queue_max);
1233 retry->peer->stats_sender_instant.retrans_skip++;
1234 return -1;
1235 }
1236 /* we're consuming the retry for an existing buffer, set it to false to allow new retries to come in */
1237 ctx->sender_queue[idx]->retry_queued = false;
1238 retry->active = false;
1239
1240 // TODO: re-enable rist_send_data_allowed (cooldown feature)
1241
1242 struct rist_bandwidth_estimation *retry_bw = &retry->peer->retry_bw;
1243 struct rist_bandwidth_estimation *cli_bw = &retry->peer->bw;
1244 if (retry->peer->peer_data)
1245 {
1246 retry_bw = &retry->peer->peer_data->retry_bw;
1247 }
1248 // update bandwidth values
1249 rist_calculate_bitrate(0, cli_bw);
1250 rist_calculate_bitrate(0, retry_bw);
1251
1252 // Make sure we do not flood the network with retries
1253 size_t current_bitrate = 0;
1254 size_t data_bitrate = 0;
1255 size_t retry_bitrate = 0;
1256 if (retry->peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_AGGRESSIVE) {
1257 data_bitrate = cli_bw->eight_times_bitrate_fast / 8;
1258 retry_bitrate = retry_bw->eight_times_bitrate_fast / 8;
1259 } else if (retry->peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_NORMAL) {
1260 data_bitrate = cli_bw->eight_times_bitrate / 8;
1261 retry_bitrate = retry_bw->eight_times_bitrate_fast / 8;
1262 } else {
1263 data_bitrate = cli_bw->eight_times_bitrate / 8;
1264 retry_bitrate = retry_bw->eight_times_bitrate / 8;
1265 }
1266 current_bitrate = data_bitrate + retry_bitrate;
1267 size_t max_bitrate = retry->peer->config.recovery_maxbitrate * 1000;
1268 if (current_bitrate > max_bitrate) {
1269 rist_log_priv(&ctx->common, RIST_LOG_DEBUG, "Max bandwidth exceeded: (%zu + %zu) > %zu, not resending packet %"PRIu64".\n",
1270 data_bitrate, retry_bitrate, max_bitrate, idx);
1271 retry->peer->stats_sender_instant.bandwidth_skip++;
1272 return -2;
1273 }
1274
1275 // Check buffer element age
1276 uint64_t now = timestampNTP_u64();
1277 /* queue_time holds the original insertion time for this seq */
1278 uint64_t data_age = (now - ctx->sender_queue[idx]->time) / RIST_CLOCK;
1279 uint64_t retry_age = (now - retry->insert_time) / RIST_CLOCK;
1280 if (RIST_UNLIKELY(retry_age > retry->peer->config.recovery_length_max)) {
1281 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1282 "Retry-request of element %" PRIu32 " (idx %zu) that was sent %" PRIu64
1283 "ms ago has been in the queue too long to matter: %"PRIu64"ms > %ums\n",
1284 retry->seq, idx, data_age, retry_age, retry->peer->config.recovery_length_max);
1285 retry->peer->stats_sender_instant.retrans_skip++;
1286 return -1;
1287 }
1288
1289 struct rist_buffer *buffer = ctx->sender_queue[idx];
1290 if (ctx->common.debug)
1291 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1292 "Resending %"PRIu32"/%"PRIu32"/%"PRIu16" (idx %zu) after %" PRIu64
1293 "ms of first transmission and %"PRIu64"ms in queue, bitrate is %zu + %zu, %zu\n",
1294 retry->seq, buffer->seq, buffer->seq_rtp, idx, data_age, retry_age, data_bitrate,
1295 retry_bitrate, current_bitrate);
1296
1297 uint8_t *payload = buffer->data;
1298
1299 size_t ret = 0;
1300 if (buffer->transmit_count >= retry->peer->config.max_retries) {
1301 rist_log_priv(&ctx->common, RIST_LOG_ERROR, "Datagram %"PRIu32
1302 " is missing, but nack count is too large (%u), age is %"PRIu64"ms, retry #%lu\n",
1303 retry->seq, buffer->transmit_count, data_age, buffer->transmit_count);
1304 retry->peer->stats_sender_instant.retrans_skip++;
1305 return -1;
1306 }
1307
1308 uint16_t src_port = buffer->src_port;
1309 if (src_port == 0)
1310 src_port = 32768 + egress->adv_peer_id;
1311 uint32_t retry_wire_seq = (ctx->common.profile == RIST_PROFILE_ADVANCED && !main_domain_retx) ? buffer->seq : (uint32_t)buffer->seq_rtp;
1312 ret = rist_send_seq_rtcp(egress, retry_wire_seq, buffer->type, &payload[RIST_MAX_PAYLOAD_OFFSET], buffer->size, buffer->source_time, src_port, (egress->config.virt_dst_port & ~1UL), true, ctx->sender_queue[idx]->ts_null_bytes);
1313 // update bandwidth value
1314 rist_calculate_bitrate(ret, retry_bw);
1315
1316 if ((ret == (size_t)-1) || (!egress->compression && ret < buffer->size)) {
1317 rist_log_priv(&ctx->common, RIST_LOG_ERROR,
1318 "Resending of packet failed %zu != %zu for seq %"PRIu32"\n", ret, buffer->size, retry->seq);
1319 retry->peer->stats_sender_instant.retrans_skip++;
1320 return -1;
1321 }
1322
1323 buffer->transmit_count++;
1324 egress->stats_sender_instant.retrans++;
1325 egress->stats_sender_instant.retransmitted_bytes += (uint64_t)ret;
1326 return ret;
1327 }
1328
1329 void rist_retry_enqueue(struct rist_sender *ctx, uint32_t seq, struct rist_peer *peer)
1330 {
1331 uint64_t now = timestampNTP_u64();
1332 struct rist_peer *idx_target = peer ? (peer->peer_data ? peer->peer_data : peer) : NULL;
1333 size_t idx = rist_sender_index_get(ctx, seq, idx_target);
1334 struct rist_buffer *buffer = ctx->sender_queue[idx];
1335 struct rist_retry *retry;
1336
1337 // Even though all the checks are on the dequeue function, we leave one here
1338 // to prevent the flooding of our fifo .. It is based on the date of the
1339 // last queued item with the same seq for this peer.
1340 // The policy of whether to allow or not allow duplicate inactive seq entries in the retry queue
1341 // is dependent on the bloat_mode.
1342 // No duplicate unhandled (i.e.: still queued) retries are accepted.
1343 // bloat_mode disabled mode = unlimited duplicates
1344 // bloat_mode normal mode = we enforce rtt spacing and allow duplicates
1345 // bloat_mode aggressive mode = we enforce 2*rtt spacing and allow duplicates
1346 // This is a safety check to protect against buggy or non compliant receivers that request the
1347 // same seq number without waiting one RTT.
1348
1349 if (peer->config.recovery_mode == RIST_RECOVERY_MODE_DISABLED) {
1350 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1351 "Nack request for seq %"PRIu32" but nack processing is disabled for this peer\n", seq);
1352 peer->stats_sender_instant.retrans_skip++;
1353 return;
1354 }
1355 else if (!buffer) {
1356 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1357 "Nack request for seq %"PRIu32" but we do not have it in the buffer (%zu ms)\n", seq,
1358 ctx->sender_recover_min_time);
1359 peer->stats_sender_instant.retrans_skip++;
1360 return;
1361 } else {
1362 uint64_t age_ticks = (now - buffer->time);
1363 if (peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_OFF) {
1364 // All duplicates allowed, just report it
1365 if (ctx->common.debug)
1366 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1367 "Nack request for seq %" PRIu32 " with age %" PRIu64 "ms and rtt_min %" PRIu64 " for peer #%d\n",
1368 seq, age_ticks / RIST_CLOCK, peer->config.recovery_rtt_min / RIST_CLOCK, peer->adv_peer_id);
1369 } else if (ctx->peer_lst_len == 1) {
1370 /* there is a retry outstanding for this buffer, no need to add another */
1371 if (buffer->retry_queued)
1372 return;
1373 // Only one peer (faster algorithm with no lookups)
1374 if (buffer->last_retry_request != 0)
1375 {
1376 // This is a safety check to protect against buggy or non compliant receivers that request the
1377 // same seq number without waiting one RTT.
1378 uint64_t delta = (now - buffer->last_retry_request);
1379 if (ctx->common.debug)
1380 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1381 "Nack request for seq %" PRIu32 " with delta %" PRIu64 "ms, age %" PRIu64 "ms and rtt_min %" PRIu64 "\n",
1382 seq, delta /RIST_CLOCK, age_ticks / RIST_CLOCK, peer->config.recovery_rtt_min / RIST_CLOCK);
1383 uint64_t rtt = peer->last_rtt;
1384 if (peer->config.recovery_rtt_min > rtt)
1385 rtt = peer->config.recovery_rtt_min;
1386 if (peer->config.recovery_rtt_max < rtt)
1387 rtt = peer->config.recovery_rtt_max;
1388 if (peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_AGGRESSIVE) {
1389 // Aggressive congestion control only allows every two RTTs
1390 rtt = rtt * 2;
1391 }
1392 if (delta < rtt)
1393 {
1394 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1395 "Nack request for seq %" PRIu32 ", age %"PRIu64"ms, is already queued (too soon to add another one), skipped, %" PRIu64 " < %" PRIu64 " ms\n",
1396 seq, age_ticks / RIST_CLOCK, delta / RIST_CLOCK, rtt);
1397 peer->stats_sender_instant.bloat_skip++;
1398 return;
1399 }
1400 buffer->retry_queued = true;
1401 }
1402 else
1403 {
1404 if (ctx->common.debug)
1405 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1406 "First nack request for seq %"PRIu32", age %"PRIu64"ms\n", seq, age_ticks / RIST_CLOCK);
1407 }
1408 } else {
1409 // Multiple peers, we need to search for other retries in the queue for comparison
1410 uint64_t delta = 0;
1411 //We work backwards from the write index till we either find a retry with same peer & seq
1412 //or it's too old to matter,looking up to 8 RTT's ago (4 in normal mode, 8 in aggressive)
1413 size_t index = (ctx->sender_retry_queue_write_index -1) & (ctx->sender_retry_queue_size -1);
1414 uint64_t rtt = peer->last_rtt;
1415 if (peer->config.recovery_length_min > rtt)
1416 rtt = peer->config.recovery_length_min;
1417 // Aggressive congestion control only allows every two RTTs
1418 if (peer->config.congestion_control_mode == RIST_CONGESTION_CONTROL_MODE_AGGRESSIVE)
1419 rtt *= 2;
1420 struct rist_retry *lookup = NULL;
1421 uint64_t search_period = rtt * 4;
1422 while (index != ctx->sender_retry_queue_write_index) {
1423 lookup = &ctx->sender_retry_queue[index];
1424 if (lookup->seq == seq && lookup->peer == peer)
1425 break;
1426 if (lookup->insert_time < (now - search_period))
1427 break;
1428 index = (index -1 ) & (ctx->sender_retry_queue_size -1);
1429 }
1430 retry = &ctx->sender_retry_queue[index];
1431 if (retry->seq == seq && retry->peer == peer) {
1432 delta = (now - retry->insert_time);
1433 /* this retry hasn't been handled yet, it makes no sense to insert a duplicate */
1434 if (retry->active)
1435 return;
1436 if (delta < rtt)
1437 {
1438 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1439 "Nack request for seq %" PRIu32 " with delta %" PRIu64 "ms (age %"PRIu64"ms) is already queued (too soon to add another one), skipped, peer #%d '%s'\n",
1440 seq, delta / RIST_CLOCK, age_ticks / RIST_CLOCK, peer->adv_peer_id, peer->receiver_name);
1441 peer->stats_sender_instant.bloat_skip++;
1442 return;
1443 }
1444 }
1445 if (ctx->common.debug) {
1446 rist_log_priv(&ctx->common, RIST_LOG_DEBUG,
1447 "Nack request for seq %" PRIu32 " with delta %" PRIu64 "ms (age %"PRIu64"ms) and rtt_min %" PRIu64 " for peer #%"PRIu32" '%s'\n",
1448 seq, delta / RIST_CLOCK, age_ticks / RIST_CLOCK, peer->config.recovery_rtt_min / RIST_CLOCK, peer->adv_peer_id, peer->receiver_name);
1449 }
1450 }
1451 }
1452 // Now insert into the missing queue
1453 buffer->last_retry_request = now;
1454 retry = &ctx->sender_retry_queue[ctx->sender_retry_queue_write_index];
1455 retry->seq = seq;
1456 retry->peer = peer;
1457 retry->insert_time = now;
1458 retry->active = true;
1459 if (++ctx->sender_retry_queue_write_index >= ctx->sender_retry_queue_size) {
1460 ctx->sender_retry_queue_write_index = 0;
1461 }
1462 }
1463
1464 void rist_print_inet_info(char *prefix, struct rist_peer *peer)
1465 {
1466 char ipstr[INET6_ADDRSTRLEN];
1467 uint32_t port;
1468 // deal with both IPv4 and IPv6:
1469 struct sockaddr_in6 *s = (struct sockaddr_in6 *) &peer->u.address;
1470 inet_ntop(peer->address_family, &s->sin6_addr, ipstr, sizeof ipstr);
1471 if (peer->address_family == AF_INET6) {
1472 port = ntohs(s->sin6_port);
1473 } else {
1474 struct sockaddr_in *addr = (void *) &peer->u.address;
1475 port = ntohs(addr->sin_port);
1476 }
1477
1478 struct rist_common_ctx *ctx = get_cctx(peer);
1479 if (ctx->profile == RIST_PROFILE_SIMPLE)
1480 {
1481 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1482 "%sPeer Information, IP:Port => %s:%u (%d), id: %"PRIu32", simple profile\n",
1483 prefix, ipstr, port, peer->listening, peer->adv_peer_id);
1484 }
1485 else
1486 {
1487 rist_log_priv(get_cctx(peer), RIST_LOG_INFO,
1488 "%sPeer Information, IP:Port => %s:%u (%d), id: %"PRIu32", ports: %u->%u\n",
1489 prefix, ipstr, port, peer->listening, peer->adv_peer_id,
1490 peer->local_port, peer->remote_port);
1491 }
1492
1493 }
1494