Debian Codegraph @

src/rist-private.h

raw symbols SCIP
1 /* librist. Copyright © 2019-2020 SipRadius LLC. All right reserved.
2 * Author: Kuldeep Singh Dhaka <[email protected]>
3 * Author: Sergio Ammirata, Ph.D. <[email protected]>
4 *
5 * SPDX-License-Identifier: BSD-2-Clause
6 */
7
8 #ifndef RIST_RIST_PRIVATE_H
9 #define RIST_RIST_PRIVATE_H
10
11 #include "common/attributes.h"
12
13 #include <stdint.h>
14 #include <stdlib.h>
15 #include <sys/types.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include <stdbool.h>
19 #include "stdio-shim.h"
20 #include <fcntl.h>
21 #include <inttypes.h>
22 #include <stddef.h>
23 #include "time-shim.h"
24 #include "pthread-shim.h"
25 #include "socket-shim.h"
26 #include "rist_pacer.h"
27 #include "libevsocket.h"
28 #include "librist.h"
29 #include "librist/transport.h"
30 #include "udpsocket.h"
31 #include "crypto/psk.h"
32 #include <errno.h>
33 #include <stdatomic.h>
34 #include "librist/logging.h"
35 #include "proto/gre.h"
36 #include "proto/adv.h"
37 #include "rist-adv-ts.h"
38 #include "rist-reanchor.h"
39 #include "rist-send-grace.h"
40 #include "rist-bandwidth-guard.h"
41 #include "rist-rtt-mute.h"
42
43 struct cJSON;
44
45 #undef RIST_DEPRECATED
46
47 #define UINT16_SIZE (UINT16_MAX + 1)
48
49 /* Forward sequence-number gap. short_seq (Simple/Main) flows wrap at 16 bits;
50 * full 32-bit (Advanced) flows use the true difference so a genuine >64k gap is
51 * not truncated. Inputs are modular counters, so the subtraction is unsigned
52 * (well-defined wrap) before the optional 16-bit mask. */
53 static inline uint32_t rist_seq_gap(uint32_t current, uint32_t last,
54 bool short_seq)
55 {
56 uint32_t gap = current - last;
57 return short_seq ? (gap & UINT16_MAX) : gap;
58 }
59
60 /* Next expected sequence number after `last`. short_seq (Simple/Main) flows
61 * wrap at 16 bits; 32-bit (Advanced) flows use the natural successor. */
62 static inline uint32_t rist_seq_next(uint32_t last, bool short_seq)
63 {
64 uint32_t next = last + 1;
65 return short_seq ? (next & UINT16_MAX) : next;
66 }
67
68 // These control the memory footprint and buffer capacity of the lib
69 // They MUST be a power of two or wrap-around index calculations will break
70 // RIST_SERVER_QUEUE_BUFFERS is the DEFAULT Advanced-profile recovery-ring
71 // capacity (in packets), == UINT16_SIZE << RIST_RECOVERY_DEPTH_DEFAULT (8x).
72 // The ring is heap-allocated per flow/sender and can be resized at runtime to
73 // UINT16_SIZE << depth via rist_recovery_depth_set() / ?recovery-depth=, up to
74 // RIST_RECOVERY_QUEUE_MAX (depth 16, the full 32-bit space). Large depths are
75 // limited by available RAM. Simple/Main are always UINT16_SIZE.
76 #define RIST_SERVER_QUEUE_BUFFERS ((UINT16_SIZE) * 8)
77 #define RIST_RECOVERY_QUEUE_MAX ((uint64_t)(UINT16_SIZE) << 16)
78 #define RIST_RETRY_QUEUE_BUFFERS ((UINT16_SIZE) * 4)
79 #define RIST_OOB_QUEUE_BUFFERS ((UINT16_SIZE) * 2)
80 #define RIST_DATAOUT_QUEUE_BUFFERS (1024)
81 // This will restrict the use of the library to the configured maximum packet size
82 #define RIST_MAX_PACKET_SIZE (10000)
83 #define RIST_RTT_MIN (3)
84
85 /* nack requests are sent every time a data packet is received. */
86 /* this timer will be triggered to ensure we output nacks even when there is no data coming in */
87 #define RIST_MAX_JITTER (5) /* In milliseconds */
88
89 /* Bounds on the output loop's wake interval when CBR pacing is on, trading CPU
90 * against spacing: residual burst is ceil(floor / datagram interval). The working
91 * floor tracks the measured interval and is clamped to these. */
92 #define RIST_CBR_OUTPUT_MIN_US_DEFAULT (250)
93 #define RIST_CBR_OUTPUT_MIN_US_FLOOR (20)
94 /* Pacing gives way once a packet is this far past its release deadline, so it can
95 * never age a packet out of the recovery buffer. A floor: the working value has to
96 * cover a burst's drain time, which the output jitter ceiling bounds. */
97 #define RIST_CBR_MAX_HOLD_US (1000)
98 #define RIST_CBR_HOLD_JITTER_MULT (2)
99
100 static inline uint32_t rist_cbr_hold_us(uint32_t max_output_jitter_ms)
101 {
102 uint32_t hold = RIST_CBR_HOLD_JITTER_MULT * max_output_jitter_ms * 1000;
103 return hold > RIST_CBR_MAX_HOLD_US ? hold : RIST_CBR_MAX_HOLD_US;
104 }
105 #define RIST_PING_INTERVAL (100) /* In milliseconds, how long to space ping requests */
106 /* Missed RTCP/ping intervals before a bonded leg is pulled from the rotation
107 * (fast, reversible); kept well under the liveness timeout, the real teardown. */
108 #define RIST_STALL_MUTE_PINGS (3)
109 /* Floor for the per-peer liveness timeout, in missed RTCP/ping intervals. */
110 #define RIST_LIVENESS_MIN_PINGS (4)
111 /* How much better a sibling must measure before it takes the sole-carrier role
112 * from the incumbent, as a divisor of the incumbent's smoothed RTT. */
113 #define RIST_SOLE_CARRIER_MARGIN (2)
114 #define RIST_PBKDF2_HMAC_SHA256_ITERATIONS (1024)
115 #define RIST_AES_KEY_REUSE_TIMES UINT32_MAX
116 #define RIST_MAX_HOSTNAME (128)
117 #define RTCP_FB_FCI_GENERIC_NACK_SIZE (4)
118 #define RIST_MAX_NACKS (200)
119 #define RIST_MAX_NACKS_BYTES RIST_MAX_NACKS*RTCP_FB_FCI_GENERIC_NACK_SIZE
120 // Maximum offset before the payload that the code can use to put in headers
121 //#define RIST_MAX_PAYLOAD_OFFSET (sizeof(struct rist_gre_key_seq) + sizeof(struct rist_protocol_hdr))
122 #define RIST_MAX_HEADER_SIZE 32
123 #define CHECK_BIT(var,pos) !!((var) & (1<<(pos)))
124
125 #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
126 #define BYTE_TO_BINARY(byte) \
127 (byte & 0x80 ? '1' : '0'), \
128 (byte & 0x40 ? '1' : '0'), \
129 (byte & 0x20 ? '1' : '0'), \
130 (byte & 0x10 ? '1' : '0'), \
131 (byte & 0x08 ? '1' : '0'), \
132 (byte & 0x04 ? '1' : '0'), \
133 (byte & 0x02 ? '1' : '0'), \
134 (byte & 0x01 ? '1' : '0')
135
136 #define STALE_FLOW_TIME (60L * 1000L * RIST_CLOCK) /* in milliseconds */
137
138 enum rist_peer_state {
139 RIST_PEER_STATE_IDLE = 0,
140 RIST_PEER_STATE_PING = 1,
141 RIST_PEER_STATE_CONNECT = 2
142 };
143 struct rist_buffer {
144 void *data;
145 size_t size;
146 uint8_t type;
147 uint16_t src_port;
148 uint16_t dst_port;
149 uint64_t source_time;
150 int8_t use_seq;
151 uint32_t seq;
152 uint16_t seq_rtp;
153
154 uint64_t time;//Time we received the packet
155 uint64_t packet_time;//Timestamp based on the RTP time of the packet
156 uint64_t target_output_time;//packet_time + buffer
157
158 uint8_t fragment_number;
159 uint8_t fragment_final;
160 // TODO: These four are only used by sender ... do I split buffer into sender and receiver?
161 uint64_t last_retry_request;
162 uint8_t transmit_count;
163 uint16_t ts_null_bytes;
164 struct rist_peer *peer;
165
166 struct rist_buffer *next_free;
167 size_t alloc_size;
168 bool free;
169 bool retry_queued;
170 };
171
172 /* Largest recovery depth whose ring (UINT16_SIZE << depth packets) is
173 * addressable as size_t: the two parallel index arrays cost
174 * sizeof(ptr) + sizeof(uint32_t) per slot. Depth 16 (2^32) only fits a 64-bit
175 * size_t; on a 32-bit size_t the exponent is reduced until it fits. Shared with
176 * the recovery-depth unit test. */
177 static inline int rist_recovery_depth_platform_max(void)
178 {
179 const uint64_t per = (uint64_t)sizeof(struct rist_buffer *) + sizeof(uint32_t);
180 const uint64_t limit = (uint64_t)SIZE_MAX / per;
181 int depth = RIST_RECOVERY_DEPTH_MAX;
182 while (depth > RIST_RECOVERY_DEPTH_MIN &&
183 ((uint64_t)UINT16_SIZE << depth) > limit)
184 depth--;
185 return depth;
186 }
187
188 struct rist_missing_buffer {
189 uint32_t seq;
190 uint64_t next_nack;
191 uint64_t insertion_time;
192 uint32_t nack_count;
193 struct rist_peer *peer;
194 struct rist_missing_buffer *next;
195 };
196
197 struct rist_bandwidth_estimation {
198 size_t bytes;
199 size_t bytes_fast;
200 uint64_t last_bitrate_calctime;
201 uint64_t last_bitrate_calctime_fast;
202 size_t eight_times_bitrate_fast;
203 size_t eight_times_bitrate;
204 size_t bitrate;
205 size_t bitrate_fast;
206 };
207
208 struct rist_peer_flow_stats {
209 uint32_t lost;
210 uint32_t received;
211 uint32_t dupe;
212 uint32_t dropped_full;
213 uint32_t dropped_late;
214 size_t buffer_duration_count;
215 uint32_t buffer_duration[2048];
216
217 uint32_t missing;
218 uint32_t retries;
219 uint32_t recovered;
220 uint32_t reordered;
221 uint32_t dups;
222 uint32_t recovered_0nack;
223 uint32_t recovered_1nack;
224 uint32_t recovered_2nack;
225 uint32_t recovered_3nack;
226 uint32_t recovered_morenack;
227 uint32_t recovered_sum;
228 uint32_t recovered_average;
229 int32_t recovered_slope;
230 uint32_t recovered_slope_inverted;
231
232 /* Inter-packet spacing */
233 uint64_t min_ips;
234 uint64_t max_ips;
235 uint64_t cur_ips;
236 uint32_t avg_count;
237 uint64_t total_ips;
238
239 /* Per-byte counters */
240 uint64_t received_bytes;
241 };
242
243 struct rist_peer_sender_stats {
244 uint64_t sent;
245 uint32_t received;
246 uint32_t retrans;
247 uint32_t bloat_skip;
248 uint32_t bandwidth_skip;
249 uint32_t retrans_skip;
250 uint64_t ts_null;
251 uint64_t sent_bytes;
252 uint64_t retransmitted_bytes;
253 };
254
255 struct rist_peer_receiver_stats {
256 uint32_t sent_rtcp;
257 uint32_t received_rtcp;
258 uint64_t received;
259 uint64_t ts_null;
260 uint64_t received_bytes;
261 };
262
263 struct nacks {
264 uint32_t array[RIST_MAX_NACKS];
265 size_t counter;
266 };
267
268 struct rist_flow {
269 atomic_int shutdown;
270 int max_output_jitter;
271
272 struct rist_buffer **receiver_queue; /* output queue, heap-allocated to receiver_queue_max */
273
274 pthread_rwlock_t queue_lock;
275
276 bool receiver_queue_has_items;
277 bool flow_auto_buffer_scaling;
278 bool currently_scaling_buffer;
279 atomic_ulong receiver_queue_size; /* size in bytes */
280 uint64_t recovery_buffer_ticks; /* size in ticks */
281 uint64_t stats_report_time; /* in ticks */
282 atomic_ulong receiver_queue_output_idx; /* next packet to output */
283 size_t receiver_queue_max;
284 bool flag_flow_buffer_start;
285
286 /* Constant-bitrate output pacing; see rist_pacer.h. cbr_arrived_bytes is
287 * written by the receive threads and drained by the output thread: the
288 * estimate must come from arrivals, since measuring the paced output would
289 * make the rate an output of itself. */
290 bool cbr_output;
291 uint32_t cbr_output_min_us;
292 atomic_uint_least64_t cbr_arrived_bytes;
293 uint64_t cbr_arrived_seen;
294 struct rist_pacer_rate cbr_rate;
295 struct rist_pacer cbr_pacer;
296 uint64_t cbr_overdue_releases; /* pacer yielded to the buffer deadline */
297 uint32_t cbr_max_hold_us; /* longest a paced packet may wait */
298 bool cbr_paced_hold; /* last output pass stopped on the pacer */
299 uint64_t cbr_interval_ns; /* last paced interval, sizes the wake floor */
300
301 /* Missing incoming packets, waiting for retransmission */
302 struct rist_missing_buffer *missing;
303 struct rist_missing_buffer *missing_tail;
304 uint32_t missing_counter;
305
306 struct rist_peer_flow_stats stats_instant;
307 struct rist_peer_flow_stats stats_total;//TODO: use the total stats!
308 struct rist_bandwidth_estimation bw;
309 struct rist_bandwidth_estimation bw_tsnull;
310 struct rist_bandwidth_estimation bw_rejected;
311 struct rist_bandwidth_estimation bw_retries;
312 uint64_t stats_next_time;
313 uint64_t checks_next_time;
314
315 /* Missing queue max size */
316 uint32_t missing_counter_max;
317
318 uint32_t flow_id;
319 uint32_t flow_id_actual;
320 int dead;
321 struct rist_flow *next;
322 struct rist_peer **peer_lst;
323 size_t peer_lst_len;
324 uint32_t last_seq_output;
325 uint64_t last_seq_output_source_time;
326 uint32_t last_seq_found;
327 intptr_t receiver_id;
328 intptr_t sender_id;
329 uint64_t last_ipstats_time;
330 uint64_t last_output_time;
331 uint64_t max_source_time;
332 uint64_t too_late_ctr;
333 /* When we started holding off a re-anchor for want of a current packet.
334 * Zero while not holding off. */
335 uint64_t reanchor_wait_since;
336
337 size_t offset_recalc_sample_count;
338 uint64_t offset_recalc_samples[2048];
339
340 int64_t time_offset;//Current offset between our clock and RTP packets.
341 int64_t time_offset_old;//Old offset between our clock and RTP packets.
342 uint64_t time_offset_changed_ts;//Timestamp the RTP counter last wrapped
343 uint64_t last_packet_ts;//Last packet time
344 bool rtc_timing_mode;
345
346 bool authenticated;
347
348 /* Receiver thread variables */
349 pthread_t receiver_thread;
350 bool receiver_thread_running;
351 /* data out thread signaling */
352 pthread_cond_t condition;
353 pthread_mutex_t mutex;
354
355 /* variable used for seq number length (16bit or 32bit) */
356 bool short_seq;
357
358 /* Scope-B merge auto-detection: set by keepalive L bit */
359 bool merge_auto_enabled;
360
361 /* Session timeouts variables */
362 uint64_t session_timeout;
363 uint64_t flow_timeout;
364 uint64_t last_recv_ts;
365
366 /* Receiver timed async data output */
367 struct rist_data_block **dataout_fifo_queue;
368 size_t dataout_fifo_queue_bytesize;
369 atomic_ulong dataout_fifo_queue_read_index;
370 atomic_ulong dataout_fifo_queue_write_index;
371 atomic_bool fifo_overflow;
372
373 /* Temporary buffer for grouping and sending nacks */
374 struct nacks nacks;
375 struct rist_logging_settings *logging_settings;
376 };
377
378 struct rist_retry {
379 struct rist_peer *peer;
380 uint64_t insert_time;
381 uint32_t seq;
382 bool active;//signal whether this retry has been consumed (false) or not
383 };
384
385 struct rist_common_ctx {
386 atomic_int shutdown;
387 atomic_bool startup_complete;
388
389 /* Used by logging */
390 intptr_t sender_id;
391 intptr_t receiver_id;
392 struct rist_logging_settings *logging_settings;
393
394
395 /* Flows */
396 struct rist_flow *FLOWS;
397 pthread_mutex_t flows_lock;
398
399 /* evsocket */
400 struct evsocket_ctx *evctx;
401
402 /* Timers */
403 int rist_max_jitter;
404 /* CBR output pacing, per context: a flow's legs share one output, so this is
405 * not a per-peer property. */
406 bool cbr_output;
407 bool cbr_output_set; /* a value was stated; later conflicts refused */
408 uint32_t cbr_output_min_us;
409
410 /* Recovery buffer RTT multiplier (default 7, per RIST spec) */
411 int recovery_rtt_multiplier;
412
413 /* Advanced-profile recovery-ring capacity in packets (power of two).
414 * Default RIST_SERVER_QUEUE_BUFFERS; tunable before rist_start() via
415 * rist_recovery_depth_set(). Simple/Main ignore this and use
416 * UINT16_SIZE. */
417 size_t recovery_queue_max;
418
419 /* Peer list sync - RW locks */
420 struct rist_peer *PEERS;
421 pthread_mutex_t peerlist_lock;
422
423 /* buffers */
424 /* these are pre-allocated buffers, not pre-allocated aligned stack */
425 struct {
426 uint8_t enc[RIST_MAX_PACKET_SIZE];
427 uint8_t dec[RIST_MAX_PACKET_SIZE];
428 uint8_t recv[RIST_MAX_PACKET_SIZE];
429 uint8_t recv_npd[RIST_MAX_PACKET_SIZE];
430 uint8_t rtcp[RIST_MAX_PACKET_SIZE];
431 } buf;
432 struct rist_buffer *rist_free_buffer;
433 pthread_mutex_t rist_free_buffer_mutex;
434 uint64_t rist_free_buffer_count;
435
436 /* timers */
437 uint64_t nacks_next_time;
438 uint64_t stats_report_time;
439
440 enum rist_profile profile;
441 /* Set by rist_*_start() and by rist_peer_create() once a peer with
442 * a definite profile has been inserted. When set, rist_peer_create
443 * refuses any peer whose ?profile= disagrees with cctx->profile. */
444 atomic_bool profile_locked;
445 uint8_t cname[RIST_MAX_HOSTNAME];
446
447 /* seq variables */
448 uint32_t seq;
449 uint16_t seq_rtp;
450
451 /* Advanced Profile (TR-06-3) state */
452 uint32_t adv_ssrc_base; /* Even SSRC for Protected flow */
453 uint32_t adv_seq_protected; /* 32-bit seq counter for even SSRC */
454 uint32_t adv_seq_unprotected; /* 32-bit seq counter for odd SSRC */
455
456 /* Peer counter (only the ones created by the API) */
457 uint32_t peer_counter;
458
459 /* Auth callback variables */
460 struct {
461 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);
462 int (*disconn_cb)(void *arg, struct rist_peer *peer);
463 void *arg;
464 } auth;
465
466 /* Out-of-band data variables */
467 int (*oob_data_callback)(void *arg, const struct rist_oob_block *oob_block);
468 void *oob_data_callback_argument;
469 bool oob_data_enabled;
470 struct rist_peer *oob_current_peer;
471
472 int (*stats_callback)(void *arg, const struct rist_stats *stats_container);
473 void *stats_callback_argument;
474 pthread_mutex_t stats_lock;
475
476 pthread_rwlock_t oob_queue_lock;
477 struct rist_buffer *oob_queue[RIST_OOB_QUEUE_BUFFERS]; /* oob transmit queue */
478 size_t oob_queue_bytesize;
479 uint16_t oob_queue_read_index;
480 uint16_t oob_queue_write_index;
481
482 /* oob receive fifo: populated by the protocol thread when oob is
483 * enabled but no callback is set, drained by rist_oob_read(). */
484 struct rist_buffer *oob_rx_queue[RIST_OOB_QUEUE_BUFFERS];
485 uint16_t oob_rx_queue_read_index;
486 uint16_t oob_rx_queue_write_index;
487 struct rist_buffer *oob_rx_current; /* backs the block handed out by the last rist_oob_read */
488 struct rist_oob_block oob_rx_block; /* borrowed view returned to the caller */
489
490 bool debug;
491 uint32_t birthtime_rtp_offset;
492
493 /* Pluggable transport (default: POSIX sockets) */
494 struct rist_transport_ops transport;
495 bool transport_active;
496
497 /* Connection status callback */
498 connection_status_callback_t connection_status_callback;
499 void *connection_status_callback_argument;
500
501 rist_thread_callback_func_t thread_callback;
502 void *thread_callback_arg;
503 };
504
505 struct rist_receiver {
506 /* data out thread signaling for fifo */
507 pthread_cond_t condition;
508 pthread_mutex_t mutex;
509
510 /* Receiver data callback */
511 receiver_data_callback2_t receiver_data_callback;
512 void *receiver_data_callback_argument;
513 int receiver_data_ready_notify_fd;
514
515 /* Data fd output (tunnel mode) — write received data directly to fd */
516 int receiver_data_fd;
517 uint32_t receiver_data_fd_flags;
518 atomic_uint_fast64_t data_fd_rx_packets;
519 atomic_uint_fast64_t data_fd_rx_bytes;
520
521 /* Receiver session timeout callback */
522 receiver_session_timeout_callback_t receiver_session_timeout_callback;
523 void *receiver_session_timeout_callback_argument;
524
525 /* Receiver flow attribute callback (Advanced Profile CI=0x8001) */
526 receiver_flow_attr_callback_t receiver_flow_attr_callback;
527 void *receiver_flow_attr_callback_argument;
528
529 /* Receiver thread variables */
530 bool protocol_running;
531 pthread_t receiver_thread;
532
533 /* Reporting id */
534 intptr_t id;
535
536 /* Common stuff */
537 struct rist_common_ctx common;
538
539 enum rist_nack_type nack_type;
540
541 bool simulate_loss;
542 uint16_t loss_percentage;
543 uint32_t fifo_queue_size;
544
545 uint32_t merge_mode;
546 uint64_t stats_pairs_merged;
547 uint64_t stats_orphan_first_delivered;
548 uint64_t stats_orphan_last_delivered;
549 };
550
551 struct rist_sender {
552 /* Advertised flow for this context */
553 uint32_t adv_flow_id;
554
555 /* max bitrate of all sender peers (sets the buffer size on sender queue) */
556 uint32_t recovery_maxbitrate_max;
557 uint32_t max_nacksperloop;
558 bool null_packet_suppression;
559
560 uint32_t split_mode;
561 uint64_t stats_pairs_emitted;
562 uint64_t stats_split_fallback_not_ts;
563
564 /* Sender thread variables */
565 bool protocol_running;
566 pthread_t sender_thread;
567 /* data/nacks out thread signaling */
568 pthread_cond_t condition;
569 pthread_mutex_t mutex;
570
571 bool sender_initialized;
572 uint32_t total_weight;
573 struct rist_buffer **sender_queue; /* input queue, heap-allocated to sender_queue_max */
574 size_t sender_queue_bytesize;
575 size_t sender_queue_size;
576 size_t sender_queue_timelength;
577 size_t sender_buffer_size; /* dynamic buffer size for retry window */
578 size_t sender_queue_delete_index;
579 atomic_ulong sender_queue_read_index;
580 atomic_ulong sender_queue_write_index;
581 size_t sender_queue_max;
582 int weight_counter;
583 uint64_t last_datagram_time;
584 bool simulate_loss;
585 uint16_t loss_percentage;
586 uint64_t stats_next_time;
587 uint64_t checks_next_time;
588 uint32_t session_timeout;
589
590 /* retry queue */
591 struct rist_retry *sender_retry_queue;
592 size_t sender_retry_queue_write_index;
593 size_t sender_retry_queue_read_index;
594 size_t sender_retry_queue_size;
595 uint64_t cooldown_time;
596 int cooldown_mode;
597
598 /* Recovery - heap-allocated to sender_queue_max so Advanced Profile
599 * can index with the full 32-bit seq space (seq & (queue_max - 1)). */
600 uint32_t *seq_index;
601 /* Parallel 16-bit-RTP index (65536 entries), allocated only for an
602 * Advanced-context sender. A peer that negotiated down to Main NACKs in
603 * the 16-bit RTP sequence domain (nack_seq_msb = 0), which never matches
604 * the 32-bit advanced seq_index; this lets the Advanced sender still find
605 * and retransmit the requested packet for that peer. NULL on Main/Simple
606 * senders (their primary seq_index is already the 16-bit domain). */
607 uint32_t *seq_rtp_index;
608 size_t sender_recover_min_time;
609 size_t sender_queue_buffer_size;
610
611 /* Reporting id */
612 intptr_t id;
613
614 /* flow_id time-related */
615 struct timeval time;
616
617 /* Common stuff */
618 struct rist_common_ctx common;
619
620 /* Peer tracking */
621 struct rist_peer **peer_lst;
622 size_t peer_lst_len;
623
624 /* Queue lock for fifo buffer */
625 pthread_mutex_t queue_lock;
626
627 /* sender stats callback */
628 int (*sender_stats_callback)(void *arg, uint16_t version, char *stats_json, uint32_t json_size);
629 void *sender_stats_callback_argument;
630 uint64_t stats_report_time; /* in ticks */
631
632 /* Data fd input (tunnel mode) — read from fd and send as RIST data */
633 int data_fd;
634 size_t data_fd_max_packet_size;
635 uint32_t data_fd_flags;
636 pthread_t data_fd_thread;
637 bool data_fd_thread_started;
638 atomic_uint_fast64_t data_fd_tx_packets;
639 atomic_uint_fast64_t data_fd_tx_bytes;
640 };
641
642 enum rist_ctx_mode {
643 RIST_SENDER_MODE,
644 RIST_RECEIVER_MODE
645 };
646
647 struct rist_ctx {
648 enum rist_ctx_mode mode;
649 struct rist_sender *sender_ctx;
650 struct rist_receiver *receiver_ctx;
651 };
652
653 struct rist_peer {
654 /* linked list */
655 pthread_mutex_t peer_lock;//Currently only used for setting password & in sending/receiving
656 struct rist_peer *next;
657 struct rist_peer *prev;
658
659 /* For simple profile authentication chain (data and rtcp on different ports) */
660 struct rist_peer *peer_rtcp;
661 struct rist_peer *peer_data;
662 bool handled_first;
663 bool is_rtcp;
664 bool is_data;
665 /* sender only: peer is known to respond to echo requests use those to calculate RTT instead */
666 bool echo_enabled;
667
668 /* For keeping track of the connection that initiated a peer */
669 struct rist_peer *parent;
670 struct rist_peer *sibling_prev;
671 struct rist_peer *sibling_next;
672 struct rist_peer *child;
673 uint32_t child_alive_count;
674
675 /* Flow for incoming traffic */
676 struct rist_flow *flow;
677
678 /* Advertised flow id to force peer selection */
679 uint32_t adv_flow_id;
680
681 /* Identifiers for multipeer links */
682 uint32_t adv_peer_id;
683 uint32_t peer_ssrc;
684
685 char receiver_name[RIST_MAX_HOSTNAME];
686
687 /* Config */
688 struct rist_peer_config config;
689 uint64_t sender_max_buffer_ticks;
690 uint64_t recovery_buffer_ticks;
691
692 bool buffer_bloat_active;
693
694 bool receiver_mode;
695
696 int sd;
697
698 /* State */
699 bool authenticated;
700
701 /* Data sending */
702 uint32_t seq;
703 uint64_t eight_times_rtt;
704 uint32_t w_count; /* Counter for weight in distributed send */
705
706 /* RTT statistics */
707 uint64_t last_rtt;
708
709 /* Dynamic RTT-based muting (sender bonding, ?rtt-drop=). When muted the
710 * leg is skipped in the weighted payload rotation but its connection and
711 * RTCP probing continue so RTT keeps updating for the restore decision. */
712 bool rtt_muted;
713 struct rist_rtt_mute_state rtt_mute_state;
714 uint32_t rtt_trickle_counter; /* 1-in-N counter for redundant trickle sends */
715 uint32_t rtt_mute_count; /* cumulative count of RTT-triggered mute events */
716 /* Elected to keep carrying while every leg wants mute. Sticky: held until
717 * the leg recovers or a sibling is clearly better, so the payload path
718 * does not ping-pong between two equally bad legs. */
719 bool rtt_sole_carrier;
720 uint64_t rtt_sole_since;
721 /* Start of the post-restore weight ramp. A leg that was muted for high RTT
722 * has an empty queue, so it measures well until it is loaded again;
723 * rejoining at full share re-floods it. Zero when no ramp is in progress. */
724 uint64_t rtt_ramp_start;
725
726 /* Last time this peer was warned that its payload rate leaves no
727 * retransmission budget under its bandwidth ceiling; 0 if never. */
728 uint64_t bandwidth_warn_ts;
729
730 /* Briefly-silent bonded leg: skipped in the payload rotation but kept
731 * authenticated, so it resumes without re-auth if it returns before the
732 * liveness timeout (rist_sender_stall_check / rist_peer_liveness_timeout). */
733 bool stalled;
734
735 /* Missing queue max size */
736 uint32_t missing_counter_max;
737
738 /* Encryption */
739 bool supports_otf_passphrase_change;
740 struct rist_key key_tx; // used for transmitted packets
741 struct rist_key key_rx; // used for received packets
742 bool key_rx_odd_active;
743 bool key_tx_odd_active;
744 struct rist_key key_tx_odd; // used for transmitted packets
745 struct rist_key key_rx_odd; // used for received packets
746 bool rolling_over_passphrase;
747 struct eapsrp_ctx *eap_ctx;
748 int eap_authentication_state;
749 uint8_t rist_gre_version;
750
751 /* Advanced Profile (TR-06-3) peer state */
752 bool is_advanced; /* Peer operating in Advanced Profile mode */
753 bool remote_supports_advanced; /* Remote advertised I=1 in keep-alive */
754 struct rist_adv_ts_state rx_adv_ts; /* receive-side 1 MHz source-clock rebuild */
755
756 /* compression flag (sender only) */
757 bool compression;
758
759 /* Addressing */
760 uint16_t local_port;
761 uint16_t remote_port;
762 union {
763 struct sockaddr address;
764 struct sockaddr_in inaddr;
765 struct sockaddr_in6 inaddr6;
766 struct sockaddr_storage storage;
767 } u;
768 socklen_t address_len;
769 uint16_t address_family;
770 uint16_t state;
771 char miface[128];
772
773 /* Events */
774 struct timeval expire;
775 bool send_keepalive;
776 struct evsocket_event *event_recv;
777
778 /* listening mode with @ */
779 bool listening;
780 /* multicast */
781 bool multicast_sender;
782 bool multicast_receiver;
783
784 /* rist ctx */
785 struct rist_sender *sender_ctx;
786 struct rist_receiver *receiver_ctx;
787
788 /* Reflector role flags */
789 bool is_reflector_publisher;
790
791 /* rist buffer bloating counteract */
792 uint64_t cooldown_time;
793
794 /* Statistics Sender */
795 struct rist_peer_sender_stats stats_sender_instant;
796 struct rist_peer_sender_stats stats_sender_total;
797
798
799 /* Statistics Receiver */
800 struct rist_peer_receiver_stats stats_receiver_instant;
801 struct rist_peer_receiver_stats stats_receiver_total;
802
803 int dead;
804 int timed_out;
805 uint64_t dead_since;
806 /* Caller-side socket rebind bookkeeping. */
807 uint64_t last_rebind_time;
808 uint32_t rebind_attempts;
809 uint64_t birthtime_peer;
810 uint64_t birthtime_local;
811
812 /* bw estimation */
813 struct rist_bandwidth_estimation bw;
814 struct rist_bandwidth_estimation retry_bw;
815 struct rist_bandwidth_estimation ts_nulls_bw;
816
817 /* shutting down flag */
818 atomic_bool shutdown;
819
820 /* Timers */
821 uint32_t rtcp_keepalive_interval;
822 uint64_t next_periodic_rtcp;
823 uint64_t next_keepalive_packet;
824 uint64_t next_flow_attr;
825 uint64_t session_timeout;
826 uint64_t last_pkt_received;
827 uint64_t last_sender_report_time;
828 uint64_t last_sender_report_ts;
829 uint64_t ts_null_bytes;
830
831 char *url;
832 char cname[RIST_MAX_HOSTNAME];
833 uint8_t mac_addr[6];
834 bool send_first_connection_event;
835
836 /* Rate-limit for EMSGSIZE/PMTU-too-large send errors so a flow of
837 * oversized packets doesn't drown the log. Holds the last log time
838 * in NTP ticks. */
839 uint64_t last_pmtu_error_log;
840
841 uint64_t log_repeat_timer;
842
843 uint8_t data[SIZEOF_GRE_KEEPALIVE];
844
845 };
846
847 static inline struct rist_common_ctx *rist_struct_get_common(struct rist_ctx *ctx) {
848 if (RIST_UNLIKELY(!ctx))
849 return NULL;
850 if (ctx->mode == RIST_SENDER_MODE && ctx->sender_ctx)
851 return &ctx->sender_ctx->common;
852 else if (ctx->mode == RIST_RECEIVER_MODE && ctx->receiver_ctx)
853 return &ctx->receiver_ctx->common;
854 else
855 return NULL;
856 }
857
858 /* defined in flow.c */
859 RIST_PRIV void rist_receiver_flow_statistics(struct rist_receiver *ctx, struct rist_flow *flow);
860 RIST_PRIV struct cJSON *rist_sender_peer_statistics(struct rist_peer *peer);
861 RIST_PRIV void rist_sender_flow_statistics(struct rist_sender *ctx);
862 RIST_PRIV void rist_delete_flow(struct rist_receiver *ctx, struct rist_flow *f);
863 RIST_PRIV void rist_receiver_missing(struct rist_flow *f, struct rist_peer *peer,uint64_t nack_time, uint32_t seq, uint64_t rtt);
864 RIST_PRIV int rist_receiver_associate_flow(struct rist_peer *p, uint32_t flow_id);
865 RIST_PRIV size_t rist_best_rtt_index(struct rist_flow *f);
866 RIST_PRIV 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);
867 RIST_PRIV void free_rist_buffer(struct rist_common_ctx *ctx, struct rist_buffer *b);
868 RIST_PRIV void rist_calculate_bitrate(size_t len, struct rist_bandwidth_estimation *bw);
869 RIST_PRIV void rist_refresh_flow_bitrate(struct rist_bandwidth_estimation *bw);
870 RIST_PRIV void empty_receiver_queue(struct rist_flow *f, struct rist_common_ctx *ctx);
871 RIST_PRIV void rist_flush_missing_flow_queue(struct rist_flow *flow);
872
873 /* defined in rist-common.c */
874 RIST_PRIV void rist_peer_authenticate(struct rist_peer *peer);
875 RIST_PRIV void rist_shutdown_peer(struct rist_peer *peer);
876 RIST_PRIV void rist_print_inet_info(char *prefix, struct rist_peer *peer);
877 RIST_PRIV void rist_peer_rtcp(struct evsocket_ctx *ctx, void *arg);
878 RIST_PRIV void rist_populate_cname(struct rist_peer *peer);
879 RIST_PRIV void free_data_block(struct rist_data_block **const block);
880
881 /* needed after splitting up */
882 RIST_PRIV PTHREAD_START_FUNC(sender_pthread_protocol, arg);
883 RIST_PRIV PTHREAD_START_FUNC(receiver_pthread_protocol, arg);
884 RIST_PRIV int rist_max_jitter_set(struct rist_common_ctx *ctx, int t);
885 RIST_PRIV int rist_recovery_rtt_multiplier_set_internal(struct rist_common_ctx *ctx, int multiplier);
886 RIST_PRIV int parse_url_options(const char *url, struct rist_peer_config *output_peer_config);
887 RIST_PRIV int parse_url_udp_options(const char *url, struct rist_udp_config *output_udp_config);
888 RIST_PRIV struct rist_peer *rist_receiver_peer_insert_local(struct rist_receiver *ctx,
889 const struct rist_peer_config *config);
890 RIST_PRIV void rist_sender_destroy_local(struct rist_sender *ctx);
891 RIST_PRIV void rist_receiver_destroy_local(struct rist_receiver *ctx);
892 RIST_PRIV struct rist_peer *rist_sender_peer_insert_local(struct rist_sender *ctx,
893 const struct rist_peer_config *config, bool b_rtcp);
894 RIST_PRIV void rist_fsm_init_comm(struct rist_peer *peer);
895 RIST_PRIV int rist_oob_enqueue(struct rist_common_ctx *ctx, struct rist_peer *peer, const void *buf, size_t len);
896
897 RIST_PRIV int rist_oob_dequeue_rx(struct rist_common_ctx *ctx, const struct rist_oob_block **oob_block);
898 RIST_PRIV int init_common_ctx(struct rist_common_ctx *ctx, enum rist_profile profile);
899 RIST_PRIV void init_advanced_state(struct rist_common_ctx *ctx);
900 RIST_PRIV int rist_peer_remove(struct rist_common_ctx *ctx, struct rist_peer *peer, struct rist_peer **next);
901 RIST_PRIV int rist_auth_handler(struct rist_common_ctx *ctx,
902 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),
903 int (*disconn_cb)(void *arg, struct rist_peer *peer),
904 void *arg);
905 RIST_PRIV void sender_peer_append(struct rist_sender *ctx, struct rist_peer *peer);
906
907 /* Get common context */
908 RIST_PRIV struct rist_common_ctx *get_cctx(struct rist_peer *peer);
909
910 /* Fold a fresh RTT measurement into the peer's 8-tap smoothed average. RTT is
911 * measured on whichever peer object receives the response, so mirror it onto
912 * the data leg: that is where the balancer and the stats read it from. */
913 static inline void rist_peer_rtt_update(struct rist_peer *peer, uint64_t rtt)
914 {
915 peer->last_rtt = rtt;
916 peer->eight_times_rtt -= peer->eight_times_rtt / 8;
917 peer->eight_times_rtt += peer->last_rtt;
918 if (peer->peer_data && peer->peer_data != peer)
919 {
920 peer->peer_data->last_rtt = peer->last_rtt;
921 peer->peer_data->eight_times_rtt = peer->eight_times_rtt;
922 }
923 }
924
925 /*static inline in header file */
926 static inline void peer_append(struct rist_peer *p)
927 {
928 struct rist_common_ctx *cctx = get_cctx(p);
929 struct rist_peer **PEERS = &cctx->PEERS;
930 struct rist_peer *plist = *PEERS;
931 if (!plist)
932 {
933 *PEERS = p;
934 return;
935 }
936 if (p->parent)
937 {
938 struct rist_peer *peer = p->parent;
939 if (!peer->child) {
940 peer->child = p;
941 if (peer->sender_ctx)
942 peer->sender_ctx->total_weight += p->config.weight;
943 }
944 else
945 {
946 struct rist_peer *child = peer->child;
947 while (child)
948 {
949 if (!child->sibling_next)
950 {
951 child->sibling_next = p;
952 p->sibling_prev = child;
953 break;
954 }
955 child = child->sibling_next;
956 }
957 }
958 ++peer->child_alive_count;
959 }
960 while (plist)
961 {
962 if (!plist->next)
963 {
964 p->prev = plist;
965 plist->next = p;
966 return;
967 }
968 plist = plist->next;
969 }
970 }
971
972 #endif