2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2008, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
22 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
24 * \author Mark Spencer <markster@digium.com>
26 * \note RTP is defined in RFC 3550.
28 * \ingroup rtp_engines
32 <use type="external">pjproject</use>
33 <support_level>core</support_level>
38 ASTERISK_REGISTER_FILE()
44 #ifdef HAVE_OPENSSL_SRTP
45 #include <openssl/ssl.h>
46 #include <openssl/err.h>
47 #include <openssl/bio.h>
52 #include <pjlib-util.h>
56 #include "asterisk/stun.h"
57 #include "asterisk/pbx.h"
58 #include "asterisk/frame.h"
59 #include "asterisk/format_cache.h"
60 #include "asterisk/channel.h"
61 #include "asterisk/acl.h"
62 #include "asterisk/config.h"
63 #include "asterisk/lock.h"
64 #include "asterisk/utils.h"
65 #include "asterisk/cli.h"
66 #include "asterisk/manager.h"
67 #include "asterisk/unaligned.h"
68 #include "asterisk/module.h"
69 #include "asterisk/rtp_engine.h"
70 #include "asterisk/smoother.h"
71 #include "asterisk/test.h"
73 #define MAX_TIMESTAMP_SKEW 640
75 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
76 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
77 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
78 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
80 #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
81 #define DEFAULT_RTP_END 31000 /*!< Default maximum port number to end allocating RTP ports at */
83 #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
84 #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
86 #define DEFAULT_TURN_PORT 3478
88 #define TURN_STATE_WAIT_TIME 2000
90 #define RTCP_PT_FUR 192
91 #define RTCP_PT_SR AST_RTP_RTCP_SR
92 #define RTCP_PT_RR AST_RTP_RTCP_RR
93 #define RTCP_PT_SDES 202
94 #define RTCP_PT_BYE 203
95 #define RTCP_PT_APP 204
96 /* VP8: RTCP Feedback */
97 #define RTCP_PT_PSFB 206
100 #define DTMF_SAMPLE_RATE_MS 8 /*!< DTMF samples per millisecond */
102 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
104 #define ZFONE_PROFILE_ID 0x505a
106 #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
108 #define SRTP_MASTER_KEY_LEN 16
109 #define SRTP_MASTER_SALT_LEN 14
110 #define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
112 enum strict_rtp_state {
113 STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
114 STRICT_RTP_LEARN, /*! Accept next packet as source */
115 STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
118 #define DEFAULT_STRICT_RTP STRICT_RTP_CLOSED
119 #define DEFAULT_ICESUPPORT 1
121 extern struct ast_srtp_res *res_srtp;
122 extern struct ast_srtp_policy_res *res_srtp_policy;
124 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
126 static int rtpstart = DEFAULT_RTP_START; /*!< First port for RTP sessions (set in rtp.conf) */
127 static int rtpend = DEFAULT_RTP_END; /*!< Last port for RTP sessions (set in rtp.conf) */
128 static int rtpdebug; /*!< Are we debugging? */
129 static int rtcpdebug; /*!< Are we debugging RTCP? */
130 static int rtcpstats; /*!< Are we debugging RTCP? */
131 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
132 static struct ast_sockaddr rtpdebugaddr; /*!< Debug packets to/from this host */
133 static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
134 static int rtpdebugport; /*< Debug only RTP packets from IP or IP+Port if port is > 0 */
135 static int rtcpdebugport; /*< Debug only RTCP packets from IP or IP+Port if port is > 0 */
137 static int nochecksums;
139 static int strictrtp = DEFAULT_STRICT_RTP; /*< Only accept RTP frames from a defined source. If we receive an indication of a changing source, enter learning mode. */
140 static int learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL; /*< Number of sequential RTP frames needed from a single source during learning mode to accept new source. */
141 #ifdef HAVE_PJPROJECT
142 static int icesupport = DEFAULT_ICESUPPORT;
143 static struct sockaddr_in stunaddr;
144 static pj_str_t turnaddr;
145 static int turnport = DEFAULT_TURN_PORT;
146 static pj_str_t turnusername;
147 static pj_str_t turnpassword;
149 /*! \brief Pool factory used by pjlib to allocate memory. */
150 static pj_caching_pool cachingpool;
152 /*! \brief Global memory pool for configuration and timers */
153 static pj_pool_t *pool;
155 /*! \brief Global timer heap */
156 static pj_timer_heap_t *timer_heap;
158 /*! \brief Thread executing the timer heap */
159 static pj_thread_t *timer_thread;
161 /*! \brief Used to tell the timer thread to terminate */
162 static int timer_terminate;
164 /*! \brief Structure which contains ioqueue thread information */
165 struct ast_rtp_ioqueue_thread {
166 /*! \brief Pool used by the thread */
168 /*! \brief The thread handling the queue and timer heap */
170 /*! \brief Ioqueue which polls on sockets */
171 pj_ioqueue_t *ioqueue;
172 /*! \brief Timer heap for scheduled items */
173 pj_timer_heap_t *timerheap;
174 /*! \brief Termination request */
176 /*! \brief Current number of descriptors being waited on */
178 /*! \brief Linked list information */
179 AST_LIST_ENTRY(ast_rtp_ioqueue_thread) next;
182 /*! \brief List of ioqueue threads */
183 static AST_LIST_HEAD_STATIC(ioqueues, ast_rtp_ioqueue_thread);
187 #define FLAG_3389_WARNING (1 << 0)
188 #define FLAG_NAT_ACTIVE (3 << 1)
189 #define FLAG_NAT_INACTIVE (0 << 1)
190 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
191 #define FLAG_NEED_MARKER_BIT (1 << 3)
192 #define FLAG_DTMF_COMPENSATE (1 << 4)
194 #define TRANSPORT_SOCKET_RTP 0
195 #define TRANSPORT_SOCKET_RTCP 1
196 #define TRANSPORT_TURN_RTP 2
197 #define TRANSPORT_TURN_RTCP 3
199 /*! \brief RTP learning mode tracking information */
200 struct rtp_learning_info {
201 int max_seq; /*!< The highest sequence number received */
202 int packets; /*!< The number of remaining packets before the source is accepted */
205 #ifdef HAVE_OPENSSL_SRTP
206 struct dtls_details {
207 SSL *ssl; /*!< SSL session */
208 BIO *read_bio; /*!< Memory buffer for reading */
209 BIO *write_bio; /*!< Memory buffer for writing */
210 enum ast_rtp_dtls_setup dtls_setup; /*!< Current setup state */
211 enum ast_rtp_dtls_connection connection; /*!< Whether this is a new or existing connection */
215 /*! \brief RTP session description */
219 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
220 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
221 unsigned int themssrc; /*!< Their SSRC */
224 unsigned int lastrxts;
225 unsigned int lastividtimestamp;
226 unsigned int lastovidtimestamp;
227 unsigned int lastitexttimestamp;
228 unsigned int lastotexttimestamp;
229 unsigned int lasteventseqn;
230 int lastrxseqno; /*!< Last received sequence number */
231 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
232 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
233 unsigned int rxcount; /*!< How many packets have we received? */
234 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
235 unsigned int txcount; /*!< How many packets have we sent? */
236 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
237 unsigned int cycles; /*!< Shifted count of sequence number cycles */
238 double rxjitter; /*!< Interarrival jitter at the moment in seconds */
239 double rxtransit; /*!< Relative transit time for previous packet */
240 struct ast_format *lasttxformat;
241 struct ast_format *lastrxformat;
243 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
244 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
245 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
247 /* DTMF Reception Variables */
248 char resp; /*!< The current digit being processed */
249 unsigned int last_seqno; /*!< The last known sequence number for any DTMF packet */
250 unsigned int last_end_timestamp; /*!< The last known timestamp received from an END packet */
251 unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
252 unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
253 unsigned int dtmfsamples;
254 enum ast_rtp_dtmf_mode dtmfmode; /*!< The current DTMF mode of the RTP stream */
255 /* DTMF Transmission Variables */
256 unsigned int lastdigitts;
257 char sending_digit; /*!< boolean - are we sending digits */
258 char send_digit; /*!< digit we are sending */
262 struct timeval rxcore;
263 struct timeval txcore;
264 double drxcore; /*!< The double representation of the first received packet */
265 struct timeval lastrx; /*!< timeval when we last received a packet */
266 struct timeval dtmfmute;
267 struct ast_smoother *smoother;
269 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
270 unsigned short rxseqno;
271 struct ast_sched_context *sched;
272 struct io_context *io;
274 struct ast_rtcp *rtcp;
275 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
277 enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
278 struct ast_sockaddr strict_rtp_address; /*!< Remote address information for strict RTP purposes */
281 * Learning mode values based on pjmedia's probation mode. Many of these values are redundant to the above,
282 * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
284 struct rtp_learning_info rtp_source_learn; /* Learning mode track for the expected RTP source */
285 struct rtp_learning_info alt_source_learn; /* Learning mode tracking for a new RTP source after one has been chosen */
289 ast_mutex_t lock; /*!< Lock for synchronization purposes */
290 ast_cond_t cond; /*!< Condition for signaling */
292 #ifdef HAVE_PJPROJECT
293 pj_ice_sess *ice; /*!< ICE session */
294 pj_turn_sock *turn_rtp; /*!< RTP TURN relay */
295 pj_turn_sock *turn_rtcp; /*!< RTCP TURN relay */
296 pj_turn_state_t turn_state; /*!< Current state of the TURN relay session */
297 unsigned int passthrough:1; /*!< Bit to indicate that the received packet should be passed through */
298 unsigned int rtp_passthrough:1; /*!< Bit to indicate that TURN RTP should be passed through */
299 unsigned int rtcp_passthrough:1; /*!< Bit to indicate that TURN RTCP should be passed through */
300 unsigned int ice_port; /*!< Port that ICE was started with if it was previously started */
301 struct ast_sockaddr rtp_loop; /*!< Loopback address for forwarding RTP from TURN */
302 struct ast_sockaddr rtcp_loop; /*!< Loopback address for forwarding RTCP from TURN */
304 struct ast_rtp_ioqueue_thread *ioqueue; /*!< The ioqueue thread handling us */
306 char remote_ufrag[256]; /*!< The remote ICE username */
307 char remote_passwd[256]; /*!< The remote ICE password */
309 char local_ufrag[256]; /*!< The local ICE username */
310 char local_passwd[256]; /*!< The local ICE password */
312 struct ao2_container *ice_local_candidates; /*!< The local ICE candidates */
313 struct ao2_container *ice_active_remote_candidates; /*!< The remote ICE candidates */
314 struct ao2_container *ice_proposed_remote_candidates; /*!< Incoming remote ICE candidates for new session */
315 struct ast_sockaddr ice_original_rtp_addr; /*!< rtp address that ICE started on first session */
318 #ifdef HAVE_OPENSSL_SRTP
319 SSL_CTX *ssl_ctx; /*!< SSL context */
320 ast_mutex_t dtls_timer_lock; /*!< Lock for synchronization purposes */
321 enum ast_rtp_dtls_verify dtls_verify; /*!< What to verify */
322 enum ast_srtp_suite suite; /*!< SRTP crypto suite */
323 enum ast_rtp_dtls_hash local_hash; /*!< Local hash used for the fingerprint */
324 char local_fingerprint[160]; /*!< Fingerprint of our certificate */
325 enum ast_rtp_dtls_hash remote_hash; /*!< Remote hash used for the fingerprint */
326 unsigned char remote_fingerprint[EVP_MAX_MD_SIZE]; /*!< Fingerprint of the peer certificate */
327 unsigned int rekey; /*!< Interval at which to renegotiate and rekey */
328 int rekeyid; /*!< Scheduled item id for rekeying */
329 int dtlstimerid; /*!< Scheduled item id for DTLS retransmission for RTP */
330 struct dtls_details dtls; /*!< DTLS state information */
335 * \brief Structure defining an RTCP session.
337 * The concept "RTCP session" is not defined in RFC 3550, but since
338 * this structure is analogous to ast_rtp, which tracks a RTP session,
339 * it is logical to think of this as a RTCP session.
341 * RTCP packet is defined on page 9 of RFC 3550.
346 int s; /*!< Socket */
347 struct ast_sockaddr us; /*!< Socket representation of the local endpoint. */
348 struct ast_sockaddr them; /*!< Socket representation of the remote endpoint. */
349 unsigned int soc; /*!< What they told us */
350 unsigned int spc; /*!< What they told us */
351 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
352 struct timeval rxlsr; /*!< Time when we got their last SR */
353 struct timeval txlsr; /*!< Time when we sent or last SR*/
354 unsigned int expected_prior; /*!< no. packets in previous interval */
355 unsigned int received_prior; /*!< no. packets received in previous interval */
356 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
357 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
358 unsigned int sr_count; /*!< number of SRs we've sent */
359 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
360 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
361 double rtt; /*!< Last reported rtt */
362 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
363 unsigned int reported_lost; /*!< Reported lost packets in their RR */
365 double reported_maxjitter;
366 double reported_minjitter;
367 double reported_normdev_jitter;
368 double reported_stdev_jitter;
369 unsigned int reported_jitter_count;
371 double reported_maxlost;
372 double reported_minlost;
373 double reported_normdev_lost;
374 double reported_stdev_lost;
379 double normdev_rxlost;
381 unsigned int rxlost_count;
385 double normdev_rxjitter;
386 double stdev_rxjitter;
387 unsigned int rxjitter_count;
392 unsigned int rtt_count;
394 /* VP8: sequence number for the RTCP FIR FCI */
397 #ifdef HAVE_OPENSSL_SRTP
398 struct dtls_details dtls; /*!< DTLS state information */
403 struct ast_frame t140; /*!< Primary data */
404 struct ast_frame t140red; /*!< Redundant t140*/
405 unsigned char pt[AST_RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
406 unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
407 unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
408 int num_gen; /*!< Number of generations */
409 int schedid; /*!< Timer id */
410 int ti; /*!< How long to buffer data before send */
411 unsigned char t140red_data[64000];
412 unsigned char buf_data[64000]; /*!< buffered primary data */
417 AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
419 /* Forward Declarations */
420 static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
421 static int ast_rtp_destroy(struct ast_rtp_instance *instance);
422 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
423 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
424 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
425 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
426 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
427 static void ast_rtp_update_source(struct ast_rtp_instance *instance);
428 static void ast_rtp_change_source(struct ast_rtp_instance *instance);
429 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
430 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
431 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
432 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
433 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
434 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
435 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
436 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
437 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
438 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
439 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
440 static void ast_rtp_stop(struct ast_rtp_instance *instance);
441 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
442 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
444 #ifdef HAVE_OPENSSL_SRTP
445 static int ast_rtp_activate(struct ast_rtp_instance *instance);
446 static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp);
449 static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *ice, int use_srtp);
451 #ifdef HAVE_PJPROJECT
452 /*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
453 static void update_address_with_ice_candidate(struct ast_rtp *rtp, enum ast_rtp_ice_component_type component,
454 struct ast_sockaddr *cand_address)
456 char address[PJ_INET6_ADDRSTRLEN];
458 if (!rtp->ice || (component < 1) || !rtp->ice->comp[component - 1].valid_check) {
462 ast_sockaddr_parse(cand_address, pj_sockaddr_print(&rtp->ice->comp[component - 1].valid_check->rcand->addr, address, sizeof(address), 0), 0);
463 ast_sockaddr_set_port(cand_address, pj_sockaddr_get_port(&rtp->ice->comp[component - 1].valid_check->rcand->addr));
466 /*! \brief Destructor for locally created ICE candidates */
467 static void ast_rtp_ice_candidate_destroy(void *obj)
469 struct ast_rtp_engine_ice_candidate *candidate = obj;
471 if (candidate->foundation) {
472 ast_free(candidate->foundation);
475 if (candidate->transport) {
476 ast_free(candidate->transport);
480 static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
482 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
484 if (!ast_strlen_zero(ufrag)) {
485 ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
488 if (!ast_strlen_zero(password)) {
489 ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
493 static int ice_candidate_cmp(void *obj, void *arg, int flags)
495 struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
497 if (strcmp(candidate1->foundation, candidate2->foundation) ||
498 candidate1->id != candidate2->id ||
499 ast_sockaddr_cmp(&candidate1->address, &candidate2->address) ||
500 candidate1->type != candidate1->type) {
504 return CMP_MATCH | CMP_STOP;
507 static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
509 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
510 struct ast_rtp_engine_ice_candidate *remote_candidate;
512 /* ICE sessions only support UDP candidates */
513 if (strcasecmp(candidate->transport, "udp")) {
517 if (!rtp->ice_proposed_remote_candidates &&
518 !(rtp->ice_proposed_remote_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
522 /* If this is going to exceed the maximum number of ICE candidates don't even add it */
523 if (ao2_container_count(rtp->ice_proposed_remote_candidates) == PJ_ICE_MAX_CAND) {
527 if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
531 remote_candidate->foundation = ast_strdup(candidate->foundation);
532 remote_candidate->id = candidate->id;
533 remote_candidate->transport = ast_strdup(candidate->transport);
534 remote_candidate->priority = candidate->priority;
535 ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
536 ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
537 remote_candidate->type = candidate->type;
539 ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
540 ao2_ref(remote_candidate, -1);
543 AST_THREADSTORAGE(pj_thread_storage);
545 /*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
546 static void pj_thread_register_check(void)
548 pj_thread_desc *desc;
551 if (pj_thread_is_registered() == PJ_TRUE) {
555 desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
557 ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
560 pj_bzero(*desc, sizeof(*desc));
562 if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
563 ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
568 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
569 int port, int replace);
571 static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
573 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
579 pj_thread_register_check();
581 pj_ice_sess_destroy(rtp->ice);
585 static int ice_reset_session(struct ast_rtp_instance *instance)
587 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
588 pj_ice_sess_role role = rtp->ice->role;
591 if (!rtp->ice->is_nominating && !rtp->ice->is_complete) {
595 ast_rtp_ice_stop(instance);
597 res = ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
599 /* Preserve the role that the old ICE session used */
600 pj_ice_sess_change_role(rtp->ice, role);
606 static int ice_candidates_compare(struct ao2_container *left, struct ao2_container *right)
608 struct ao2_iterator i;
609 struct ast_rtp_engine_ice_candidate *right_candidate;
611 if (ao2_container_count(left) != ao2_container_count(right)) {
615 i = ao2_iterator_init(right, 0);
616 while ((right_candidate = ao2_iterator_next(&i))) {
617 struct ast_rtp_engine_ice_candidate *left_candidate = ao2_find(left, right_candidate, OBJ_POINTER);
619 if (!left_candidate) {
620 ao2_ref(right_candidate, -1);
621 ao2_iterator_destroy(&i);
625 ao2_ref(left_candidate, -1);
626 ao2_ref(right_candidate, -1);
628 ao2_iterator_destroy(&i);
633 static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
635 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
636 pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
637 pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
638 struct ao2_iterator i;
639 struct ast_rtp_engine_ice_candidate *candidate;
640 int cand_cnt = 0, has_rtp = 0, has_rtcp = 0;
642 if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
646 /* Check for equivalence in the lists */
647 if (rtp->ice_active_remote_candidates &&
648 !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
649 ao2_cleanup(rtp->ice_proposed_remote_candidates);
650 rtp->ice_proposed_remote_candidates = NULL;
654 /* Out with the old, in with the new */
655 ao2_cleanup(rtp->ice_active_remote_candidates);
656 rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
657 rtp->ice_proposed_remote_candidates = NULL;
659 /* Reset the ICE session. Is this going to work? */
660 if (ice_reset_session(instance)) {
661 ast_log(LOG_NOTICE, "Failed to create replacement ICE session\n");
665 pj_thread_register_check();
667 i = ao2_iterator_init(rtp->ice_active_remote_candidates, 0);
669 while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
672 /* there needs to be at least one rtp and rtcp candidate in the list */
673 has_rtp |= candidate->id == AST_RTP_ICE_COMPONENT_RTP;
674 has_rtcp |= candidate->id == AST_RTP_ICE_COMPONENT_RTCP;
676 pj_strdup2(rtp->ice->pool, &candidates[cand_cnt].foundation, candidate->foundation);
677 candidates[cand_cnt].comp_id = candidate->id;
678 candidates[cand_cnt].prio = candidate->priority;
680 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
682 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
683 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
686 if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
687 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
688 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
689 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
690 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
691 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
694 if (candidate->id == AST_RTP_ICE_COMPONENT_RTP && rtp->turn_rtp) {
695 pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
696 } else if (candidate->id == AST_RTP_ICE_COMPONENT_RTCP && rtp->turn_rtcp) {
697 pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
701 ao2_ref(candidate, -1);
704 ao2_iterator_destroy(&i);
706 if (has_rtp && has_rtcp &&
707 pj_ice_sess_create_check_list(rtp->ice, &ufrag, &passwd, ao2_container_count(
708 rtp->ice_active_remote_candidates), &candidates[0]) == PJ_SUCCESS) {
709 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: SUCCESS");
710 pj_ice_sess_start_check(rtp->ice);
711 pj_timer_heap_poll(timer_heap, NULL);
712 rtp->strict_rtp_state = STRICT_RTP_OPEN;
716 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: FAILURE");
718 /* even though create check list failed don't stop ice as
719 it might still work */
720 ast_debug(1, "Failed to create ICE session check list\n");
721 /* however we do need to reset remote candidates since
722 this function may be re-entered */
723 ao2_ref(rtp->ice_active_remote_candidates, -1);
724 rtp->ice_active_remote_candidates = NULL;
725 rtp->ice->rcand_cnt = rtp->ice->clist.count = 0;
728 static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
730 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
732 return rtp->local_ufrag;
735 static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
737 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
739 return rtp->local_passwd;
742 static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
744 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
746 if (rtp->ice_local_candidates) {
747 ao2_ref(rtp->ice_local_candidates, +1);
750 return rtp->ice_local_candidates;
753 static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
755 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
761 pj_thread_register_check();
763 pj_ice_sess_change_role(rtp->ice, PJ_ICE_SESS_ROLE_CONTROLLING);
766 static void ast_rtp_ice_set_role(struct ast_rtp_instance *instance, enum ast_rtp_ice_role role)
768 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
774 pj_thread_register_check();
776 pj_ice_sess_change_role(rtp->ice, role == AST_RTP_ICE_ROLE_CONTROLLED ?
777 PJ_ICE_SESS_ROLE_CONTROLLED : PJ_ICE_SESS_ROLE_CONTROLLING);
780 static void ast_rtp_ice_add_cand(struct ast_rtp *rtp, unsigned comp_id, unsigned transport_id, pj_ice_cand_type type, pj_uint16_t local_pref,
781 const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr, int addr_len)
784 struct ast_rtp_engine_ice_candidate *candidate, *existing;
785 char address[PJ_INET6_ADDRSTRLEN];
787 pj_thread_register_check();
789 pj_ice_calc_foundation(rtp->ice->pool, &foundation, type, addr);
791 if (!rtp->ice_local_candidates && !(rtp->ice_local_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
795 if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
799 candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
800 candidate->id = comp_id;
801 candidate->transport = ast_strdup("UDP");
803 ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
804 ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
807 ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
808 ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
811 if (type == PJ_ICE_CAND_TYPE_HOST) {
812 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
813 } else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
814 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
815 } else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
816 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
819 if ((existing = ao2_find(rtp->ice_local_candidates, candidate, OBJ_POINTER))) {
820 ao2_ref(existing, -1);
821 ao2_ref(candidate, -1);
825 if (pj_ice_sess_add_cand(rtp->ice, comp_id, transport_id, type, local_pref, &foundation, addr, base_addr, rel_addr, addr_len, NULL) != PJ_SUCCESS) {
826 ao2_ref(candidate, -1);
830 /* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
831 candidate->priority = rtp->ice->lcand[rtp->ice->lcand_cnt - 1].prio;
833 ao2_link(rtp->ice_local_candidates, candidate);
834 ao2_ref(candidate, -1);
837 static void ast_rtp_on_turn_rx_rtp_data(pj_turn_sock *turn_sock, void *pkt, unsigned pkt_len, const pj_sockaddr_t *peer_addr, unsigned addr_len)
839 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
840 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
843 status = pj_ice_sess_on_rx_pkt(rtp->ice, AST_RTP_ICE_COMPONENT_RTP, TRANSPORT_TURN_RTP, pkt, pkt_len, peer_addr,
845 if (status != PJ_SUCCESS) {
848 pj_strerror(status, buf, sizeof(buf));
849 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
853 if (!rtp->rtp_passthrough) {
856 rtp->rtp_passthrough = 0;
858 ast_sendto(rtp->s, pkt, pkt_len, 0, &rtp->rtp_loop);
861 static void ast_rtp_on_turn_rtp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
863 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
866 /* If this is a leftover from an already notified RTP instance just ignore the state change */
871 rtp = ast_rtp_instance_get_data(instance);
873 /* We store the new state so the other thread can actually handle it */
874 ast_mutex_lock(&rtp->lock);
875 rtp->turn_state = new_state;
876 ast_cond_signal(&rtp->cond);
878 if (new_state == PJ_TURN_STATE_DESTROYING) {
879 pj_turn_sock_set_user_data(rtp->turn_rtp, NULL);
880 rtp->turn_rtp = NULL;
883 ast_mutex_unlock(&rtp->lock);
886 /* RTP TURN Socket interface declaration */
887 static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
888 .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
889 .on_state = ast_rtp_on_turn_rtp_state,
892 static void ast_rtp_on_turn_rx_rtcp_data(pj_turn_sock *turn_sock, void *pkt, unsigned pkt_len, const pj_sockaddr_t *peer_addr, unsigned addr_len)
894 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
895 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
898 status = pj_ice_sess_on_rx_pkt(rtp->ice, AST_RTP_ICE_COMPONENT_RTCP, TRANSPORT_TURN_RTCP, pkt, pkt_len, peer_addr,
900 if (status != PJ_SUCCESS) {
903 pj_strerror(status, buf, sizeof(buf));
904 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
908 if (!rtp->rtcp_passthrough) {
911 rtp->rtcp_passthrough = 0;
913 ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp_loop);
916 static void ast_rtp_on_turn_rtcp_state(pj_turn_sock *turn_sock, pj_turn_state_t old_state, pj_turn_state_t new_state)
918 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
919 struct ast_rtp *rtp = NULL;
921 /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
926 rtp = ast_rtp_instance_get_data(instance);
928 /* We store the new state so the other thread can actually handle it */
929 ast_mutex_lock(&rtp->lock);
930 rtp->turn_state = new_state;
931 ast_cond_signal(&rtp->cond);
933 if (new_state == PJ_TURN_STATE_DESTROYING) {
934 pj_turn_sock_set_user_data(rtp->turn_rtcp, NULL);
935 rtp->turn_rtcp = NULL;
938 ast_mutex_unlock(&rtp->lock);
941 /* RTCP TURN Socket interface declaration */
942 static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
943 .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
944 .on_state = ast_rtp_on_turn_rtcp_state,
947 /*! \brief Worker thread for ioqueue and timerheap */
948 static int ioqueue_worker_thread(void *data)
950 struct ast_rtp_ioqueue_thread *ioqueue = data;
952 while (!ioqueue->terminate) {
953 const pj_time_val delay = {0, 10};
955 pj_ioqueue_poll(ioqueue->ioqueue, &delay);
957 pj_timer_heap_poll(ioqueue->timerheap, NULL);
963 /*! \brief Destroyer for ioqueue thread */
964 static void rtp_ioqueue_thread_destroy(struct ast_rtp_ioqueue_thread *ioqueue)
966 if (ioqueue->thread) {
967 ioqueue->terminate = 1;
968 pj_thread_join(ioqueue->thread);
969 pj_thread_destroy(ioqueue->thread);
972 pj_pool_release(ioqueue->pool);
976 /*! \brief Removal function for ioqueue thread, determines if it should be terminated and destroyed */
977 static void rtp_ioqueue_thread_remove(struct ast_rtp_ioqueue_thread *ioqueue)
981 /* If nothing is using this ioqueue thread destroy it */
982 AST_LIST_LOCK(&ioqueues);
983 if ((ioqueue->count - 2) == 0) {
985 AST_LIST_REMOVE(&ioqueues, ioqueue, next);
987 AST_LIST_UNLOCK(&ioqueues);
993 rtp_ioqueue_thread_destroy(ioqueue);
996 /*! \brief Finder and allocator for an ioqueue thread */
997 static struct ast_rtp_ioqueue_thread *rtp_ioqueue_thread_get_or_create(void)
999 struct ast_rtp_ioqueue_thread *ioqueue;
1002 AST_LIST_LOCK(&ioqueues);
1004 /* See if an ioqueue thread exists that can handle more */
1005 AST_LIST_TRAVERSE(&ioqueues, ioqueue, next) {
1006 if ((ioqueue->count + 2) < PJ_IOQUEUE_MAX_HANDLES) {
1011 /* If we found one bump it up and return it */
1013 ioqueue->count += 2;
1017 ioqueue = ast_calloc(1, sizeof(*ioqueue));
1022 ioqueue->pool = pj_pool_create(&cachingpool.factory, "rtp", 512, 512, NULL);
1024 /* We use a timer on the ioqueue thread for TURN so that two threads aren't operating
1025 * on a session at the same time
1027 if (pj_timer_heap_create(ioqueue->pool, 4, &ioqueue->timerheap) != PJ_SUCCESS) {
1031 if (pj_lock_create_recursive_mutex(ioqueue->pool, "rtp%p", &lock) != PJ_SUCCESS) {
1035 pj_timer_heap_set_lock(ioqueue->timerheap, lock, PJ_TRUE);
1037 if (pj_ioqueue_create(ioqueue->pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue->ioqueue) != PJ_SUCCESS) {
1041 if (pj_thread_create(ioqueue->pool, "ice", &ioqueue_worker_thread, ioqueue, 0, 0, &ioqueue->thread) != PJ_SUCCESS) {
1045 AST_LIST_INSERT_HEAD(&ioqueues, ioqueue, next);
1047 /* Since this is being returned to an active session the count always starts at 2 */
1053 rtp_ioqueue_thread_destroy(ioqueue);
1057 AST_LIST_UNLOCK(&ioqueues);
1061 static void ast_rtp_ice_turn_request(struct ast_rtp_instance *instance, enum ast_rtp_ice_component_type component,
1062 enum ast_transport transport, const char *server, unsigned int port, const char *username, const char *password)
1064 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1065 pj_turn_sock **turn_sock;
1066 const pj_turn_sock_cb *turn_cb;
1067 pj_turn_tp_type conn_type;
1069 pj_stun_auth_cred cred = { 0, };
1071 struct ast_sockaddr addr = { { 0, } };
1072 pj_stun_config stun_config;
1073 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
1074 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1075 pj_turn_session_info info;
1076 struct ast_sockaddr local, loop;
1078 ast_rtp_instance_get_local_address(instance, &local);
1079 if (ast_sockaddr_is_ipv4(&local)) {
1080 ast_sockaddr_parse(&loop, "127.0.0.1", PARSE_PORT_FORBID);
1082 ast_sockaddr_parse(&loop, "::1", PARSE_PORT_FORBID);
1085 /* Determine what component we are requesting a TURN session for */
1086 if (component == AST_RTP_ICE_COMPONENT_RTP) {
1087 turn_sock = &rtp->turn_rtp;
1088 turn_cb = &ast_rtp_turn_rtp_sock_cb;
1089 conn_transport = TRANSPORT_TURN_RTP;
1090 ast_sockaddr_set_port(&loop, ast_sockaddr_port(&local));
1091 } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1092 turn_sock = &rtp->turn_rtcp;
1093 turn_cb = &ast_rtp_turn_rtcp_sock_cb;
1094 conn_transport = TRANSPORT_TURN_RTCP;
1095 ast_sockaddr_set_port(&loop, ast_sockaddr_port(&rtp->rtcp->us));
1100 if (transport == AST_TRANSPORT_UDP) {
1101 conn_type = PJ_TURN_TP_UDP;
1102 } else if (transport == AST_TRANSPORT_TCP) {
1103 conn_type = PJ_TURN_TP_TCP;
1109 ast_sockaddr_parse(&addr, server, PARSE_PORT_FORBID);
1111 ast_mutex_lock(&rtp->lock);
1113 pj_turn_sock_destroy(*turn_sock);
1114 rtp->turn_state = PJ_TURN_STATE_NULL;
1115 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
1116 ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
1119 ast_mutex_unlock(&rtp->lock);
1121 if (component == AST_RTP_ICE_COMPONENT_RTP && !rtp->ioqueue) {
1122 rtp->ioqueue = rtp_ioqueue_thread_get_or_create();
1123 if (!rtp->ioqueue) {
1128 pj_stun_config_init(&stun_config, &cachingpool.factory, 0, rtp->ioqueue->ioqueue, rtp->ioqueue->timerheap);
1130 if (pj_turn_sock_create(&stun_config, ast_sockaddr_is_ipv4(&addr) ? pj_AF_INET() : pj_AF_INET6(), conn_type,
1131 turn_cb, NULL, instance, turn_sock) != PJ_SUCCESS) {
1132 ast_log(LOG_WARNING, "Could not create a TURN client socket\n");
1136 cred.type = PJ_STUN_AUTH_CRED_STATIC;
1137 pj_strset2(&cred.data.static_cred.username, (char*)username);
1138 cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
1139 pj_strset2(&cred.data.static_cred.data, (char*)password);
1141 /* Because the TURN socket is asynchronous but we are synchronous we need to wait until it is done */
1142 ast_mutex_lock(&rtp->lock);
1143 pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port, NULL, &cred, NULL);
1144 while (rtp->turn_state < PJ_TURN_STATE_READY) {
1145 ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
1147 ast_mutex_unlock(&rtp->lock);
1149 /* If a TURN session was allocated add it as a candidate */
1150 if (rtp->turn_state != PJ_TURN_STATE_READY) {
1154 pj_turn_sock_get_info(*turn_sock, &info);
1156 ast_rtp_ice_add_cand(rtp, component, conn_transport, PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr,
1157 &info.relay_addr, &info.mapped_addr, pj_sockaddr_get_len(&info.relay_addr));
1159 if (component == AST_RTP_ICE_COMPONENT_RTP) {
1160 ast_sockaddr_copy(&rtp->rtp_loop, &loop);
1161 } else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1162 ast_sockaddr_copy(&rtp->rtcp_loop, &loop);
1166 static char *generate_random_string(char *buf, size_t size)
1171 for (x=0; x<4; x++) {
1172 val[x] = ast_random();
1174 snprintf(buf, size, "%08lx%08lx%08lx%08lx", (long unsigned)val[0], (long unsigned)val[1], (long unsigned)val[2], (long unsigned)val[3]);
1179 /* ICE RTP Engine interface declaration */
1180 static struct ast_rtp_engine_ice ast_rtp_ice = {
1181 .set_authentication = ast_rtp_ice_set_authentication,
1182 .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
1183 .start = ast_rtp_ice_start,
1184 .stop = ast_rtp_ice_stop,
1185 .get_ufrag = ast_rtp_ice_get_ufrag,
1186 .get_password = ast_rtp_ice_get_password,
1187 .get_local_candidates = ast_rtp_ice_get_local_candidates,
1188 .ice_lite = ast_rtp_ice_lite,
1189 .set_role = ast_rtp_ice_set_role,
1190 .turn_request = ast_rtp_ice_turn_request,
1194 #ifdef HAVE_OPENSSL_SRTP
1195 static int dtls_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
1197 /* We don't want to actually verify the certificate so just accept what they have provided */
1201 static int dtls_details_initialize(struct dtls_details *dtls, SSL_CTX *ssl_ctx,
1202 enum ast_rtp_dtls_setup setup)
1204 dtls->dtls_setup = setup;
1206 if (!(dtls->ssl = SSL_new(ssl_ctx))) {
1207 ast_log(LOG_ERROR, "Failed to allocate memory for SSL\n");
1211 if (!(dtls->read_bio = BIO_new(BIO_s_mem()))) {
1212 ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic\n");
1215 BIO_set_mem_eof_return(dtls->read_bio, -1);
1217 if (!(dtls->write_bio = BIO_new(BIO_s_mem()))) {
1218 ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic\n");
1221 BIO_set_mem_eof_return(dtls->write_bio, -1);
1223 SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
1225 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1226 SSL_set_accept_state(dtls->ssl);
1228 SSL_set_connect_state(dtls->ssl);
1230 dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
1235 if (dtls->read_bio) {
1236 BIO_free(dtls->read_bio);
1237 dtls->read_bio = NULL;
1240 if (dtls->write_bio) {
1241 BIO_free(dtls->write_bio);
1242 dtls->write_bio = NULL;
1246 SSL_free(dtls->ssl);
1252 static int dtls_setup_rtcp(struct ast_rtp_instance *instance)
1254 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1256 if (!rtp->ssl_ctx || !rtp->rtcp) {
1260 return dtls_details_initialize(&rtp->rtcp->dtls, rtp->ssl_ctx, rtp->dtls.dtls_setup);
1263 static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
1265 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1268 if (!dtls_cfg->enabled) {
1272 if (!ast_rtp_engine_srtp_is_registered()) {
1273 ast_log(LOG_ERROR, "SRTP support module is not loaded or available. Try loading res_srtp.so.\n");
1281 if (!(rtp->ssl_ctx = SSL_CTX_new(DTLSv1_method()))) {
1285 SSL_CTX_set_read_ahead(rtp->ssl_ctx, 1);
1287 rtp->dtls_verify = dtls_cfg->verify;
1289 SSL_CTX_set_verify(rtp->ssl_ctx, (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) || (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
1290 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, !(rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) ?
1291 dtls_verify_callback : NULL);
1293 if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
1294 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
1295 } else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
1296 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
1298 ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
1302 rtp->local_hash = dtls_cfg->hash;
1304 if (!ast_strlen_zero(dtls_cfg->certfile)) {
1305 char *private = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
1309 unsigned int size, i;
1310 unsigned char fingerprint[EVP_MAX_MD_SIZE];
1311 char *local_fingerprint = rtp->local_fingerprint;
1313 if (!SSL_CTX_use_certificate_file(rtp->ssl_ctx, dtls_cfg->certfile, SSL_FILETYPE_PEM)) {
1314 ast_log(LOG_ERROR, "Specified certificate file '%s' for RTP instance '%p' could not be used\n",
1315 dtls_cfg->certfile, instance);
1319 if (!SSL_CTX_use_PrivateKey_file(rtp->ssl_ctx, private, SSL_FILETYPE_PEM) ||
1320 !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
1321 ast_log(LOG_ERROR, "Specified private key file '%s' for RTP instance '%p' could not be used\n",
1326 if (!(certbio = BIO_new(BIO_s_file()))) {
1327 ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
1332 if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA1) {
1334 } else if (rtp->local_hash == AST_RTP_DTLS_HASH_SHA256) {
1335 type = EVP_sha256();
1337 ast_log(LOG_ERROR, "Unsupported fingerprint hash type on RTP instance '%p'\n",
1342 if (!BIO_read_filename(certbio, dtls_cfg->certfile) ||
1343 !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL)) ||
1344 !X509_digest(cert, type, fingerprint, &size) ||
1346 ast_log(LOG_ERROR, "Could not produce fingerprint from certificate '%s' for RTP instance '%p'\n",
1347 dtls_cfg->certfile, instance);
1348 BIO_free_all(certbio);
1352 for (i = 0; i < size; i++) {
1353 sprintf(local_fingerprint, "%02hhX:", fingerprint[i]);
1354 local_fingerprint += 3;
1357 *(local_fingerprint-1) = 0;
1359 BIO_free_all(certbio);
1362 if (!ast_strlen_zero(dtls_cfg->cipher)) {
1363 if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
1364 ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
1365 dtls_cfg->cipher, instance);
1370 if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
1371 if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
1372 ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
1373 S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
1378 rtp->rekey = dtls_cfg->rekey;
1379 rtp->suite = dtls_cfg->suite;
1381 res = dtls_details_initialize(&rtp->dtls, rtp->ssl_ctx, dtls_cfg->default_setup);
1383 dtls_setup_rtcp(instance);
1389 static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
1391 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1393 return !rtp->ssl_ctx ? 0 : 1;
1396 static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
1398 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1401 SSL_CTX_free(rtp->ssl_ctx);
1402 rtp->ssl_ctx = NULL;
1405 if (rtp->dtls.ssl) {
1406 SSL_free(rtp->dtls.ssl);
1407 rtp->dtls.ssl = NULL;
1410 if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
1411 SSL_free(rtp->rtcp->dtls.ssl);
1412 rtp->rtcp->dtls.ssl = NULL;
1416 static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
1418 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1420 if (SSL_is_init_finished(rtp->dtls.ssl)) {
1421 SSL_shutdown(rtp->dtls.ssl);
1422 rtp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
1425 if (rtp->rtcp && SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
1426 SSL_shutdown(rtp->rtcp->dtls.ssl);
1427 rtp->rtcp->dtls.connection = AST_RTP_DTLS_CONNECTION_NEW;
1431 static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
1433 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1435 return rtp->dtls.connection;
1438 static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
1440 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1442 return rtp->dtls.dtls_setup;
1445 static void dtls_set_setup(enum ast_rtp_dtls_setup *dtls_setup, enum ast_rtp_dtls_setup setup, SSL *ssl)
1447 enum ast_rtp_dtls_setup old = *dtls_setup;
1450 case AST_RTP_DTLS_SETUP_ACTIVE:
1451 *dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
1453 case AST_RTP_DTLS_SETUP_PASSIVE:
1454 *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
1456 case AST_RTP_DTLS_SETUP_ACTPASS:
1457 /* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
1458 if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
1459 *dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
1462 case AST_RTP_DTLS_SETUP_HOLDCONN:
1463 *dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
1466 /* This should never occur... if it does exit early as we don't know what state things are in */
1470 /* If the setup state did not change we go on as if nothing happened */
1471 if (old == *dtls_setup) {
1475 /* If they don't want us to establish a connection wait until later */
1476 if (*dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
1480 if (*dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
1481 SSL_set_connect_state(ssl);
1482 } else if (*dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1483 SSL_set_accept_state(ssl);
1489 static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
1491 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1493 if (rtp->dtls.ssl) {
1494 dtls_set_setup(&rtp->dtls.dtls_setup, setup, rtp->dtls.ssl);
1497 if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
1498 dtls_set_setup(&rtp->rtcp->dtls.dtls_setup, setup, rtp->rtcp->dtls.ssl);
1502 static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
1504 char *tmp = ast_strdupa(fingerprint), *value;
1506 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1508 if (hash != AST_RTP_DTLS_HASH_SHA1 && hash != AST_RTP_DTLS_HASH_SHA256) {
1512 rtp->remote_hash = hash;
1514 while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
1515 sscanf(value, "%02hhx", &rtp->remote_fingerprint[pos++]);
1519 static enum ast_rtp_dtls_hash ast_rtp_dtls_get_fingerprint_hash(struct ast_rtp_instance *instance)
1521 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1523 return rtp->local_hash;
1526 static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance)
1528 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1530 return rtp->local_fingerprint;
1533 /* DTLS RTP Engine interface declaration */
1534 static struct ast_rtp_engine_dtls ast_rtp_dtls = {
1535 .set_configuration = ast_rtp_dtls_set_configuration,
1536 .active = ast_rtp_dtls_active,
1537 .stop = ast_rtp_dtls_stop,
1538 .reset = ast_rtp_dtls_reset,
1539 .get_connection = ast_rtp_dtls_get_connection,
1540 .get_setup = ast_rtp_dtls_get_setup,
1541 .set_setup = ast_rtp_dtls_set_setup,
1542 .set_fingerprint = ast_rtp_dtls_set_fingerprint,
1543 .get_fingerprint_hash = ast_rtp_dtls_get_fingerprint_hash,
1544 .get_fingerprint = ast_rtp_dtls_get_fingerprint,
1549 /* RTP Engine Declaration */
1550 static struct ast_rtp_engine asterisk_rtp_engine = {
1553 .destroy = ast_rtp_destroy,
1554 .dtmf_begin = ast_rtp_dtmf_begin,
1555 .dtmf_end = ast_rtp_dtmf_end,
1556 .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
1557 .dtmf_mode_set = ast_rtp_dtmf_mode_set,
1558 .dtmf_mode_get = ast_rtp_dtmf_mode_get,
1559 .update_source = ast_rtp_update_source,
1560 .change_source = ast_rtp_change_source,
1561 .write = ast_rtp_write,
1562 .read = ast_rtp_read,
1563 .prop_set = ast_rtp_prop_set,
1565 .remote_address_set = ast_rtp_remote_address_set,
1566 .red_init = rtp_red_init,
1567 .red_buffer = rtp_red_buffer,
1568 .local_bridge = ast_rtp_local_bridge,
1569 .get_stat = ast_rtp_get_stat,
1570 .dtmf_compatible = ast_rtp_dtmf_compatible,
1571 .stun_request = ast_rtp_stun_request,
1572 .stop = ast_rtp_stop,
1573 .qos = ast_rtp_qos_set,
1574 .sendcng = ast_rtp_sendcng,
1575 #ifdef HAVE_PJPROJECT
1576 .ice = &ast_rtp_ice,
1578 #ifdef HAVE_OPENSSL_SRTP
1579 .dtls = &ast_rtp_dtls,
1580 .activate = ast_rtp_activate,
1584 #ifdef HAVE_OPENSSL_SRTP
1585 static void dtls_perform_handshake(struct ast_rtp_instance *instance, struct dtls_details *dtls, int rtcp)
1587 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1593 if (SSL_is_init_finished(dtls->ssl)) {
1594 SSL_clear(dtls->ssl);
1595 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1596 SSL_set_accept_state(dtls->ssl);
1598 SSL_set_connect_state(dtls->ssl);
1600 dtls->connection = AST_RTP_DTLS_CONNECTION_NEW;
1602 SSL_do_handshake(dtls->ssl);
1603 dtls_srtp_check_pending(instance, rtp, rtcp);
1607 #ifdef HAVE_PJPROJECT
1608 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq);
1610 static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
1612 struct ast_rtp_instance *instance = ice->user_data;
1613 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1615 if (status == PJ_SUCCESS) {
1616 struct ast_sockaddr remote_address;
1618 /* Symmetric RTP must be disabled for the remote address to not get overwritten */
1619 ast_rtp_instance_set_prop(instance, AST_RTP_PROPERTY_NAT, 0);
1621 update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
1622 ast_rtp_instance_set_remote_address(instance, &remote_address);
1625 update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTCP, &rtp->rtcp->them);
1629 #ifdef HAVE_OPENSSL_SRTP
1630 dtls_perform_handshake(instance, &rtp->dtls, 0);
1633 dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
1641 rtp->strict_rtp_state = STRICT_RTP_LEARN;
1642 rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
1645 static void ast_rtp_on_ice_rx_data(pj_ice_sess *ice, unsigned comp_id, unsigned transport_id, void *pkt, pj_size_t size, const pj_sockaddr_t *src_addr, unsigned src_addr_len)
1647 struct ast_rtp_instance *instance = ice->user_data;
1648 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1650 /* Instead of handling the packet here (which really doesn't work with our architecture) we set a bit to indicate that it should be handled after pj_ice_sess_on_rx_pkt
1652 if (transport_id == TRANSPORT_SOCKET_RTP || transport_id == TRANSPORT_SOCKET_RTCP) {
1653 rtp->passthrough = 1;
1654 } else if (transport_id == TRANSPORT_TURN_RTP) {
1655 rtp->rtp_passthrough = 1;
1656 } else if (transport_id == TRANSPORT_TURN_RTCP) {
1657 rtp->rtcp_passthrough = 1;
1661 static pj_status_t ast_rtp_on_ice_tx_pkt(pj_ice_sess *ice, unsigned comp_id, unsigned transport_id, const void *pkt, pj_size_t size, const pj_sockaddr_t *dst_addr, unsigned dst_addr_len)
1663 struct ast_rtp_instance *instance = ice->user_data;
1664 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1665 pj_status_t status = PJ_EINVALIDOP;
1666 pj_ssize_t _size = (pj_ssize_t)size;
1668 if (transport_id == TRANSPORT_SOCKET_RTP) {
1669 /* Traffic is destined to go right out the RTP socket we already have */
1670 status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
1671 /* sendto on a connectionless socket should send all the data, or none at all */
1672 ast_assert(_size == size || status != PJ_SUCCESS);
1673 } else if (transport_id == TRANSPORT_SOCKET_RTCP) {
1674 /* Traffic is destined to go right out the RTCP socket we already have */
1676 status = pj_sock_sendto(rtp->rtcp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
1677 /* sendto on a connectionless socket should send all the data, or none at all */
1678 ast_assert(_size == size || status != PJ_SUCCESS);
1680 status = PJ_SUCCESS;
1682 } else if (transport_id == TRANSPORT_TURN_RTP) {
1683 /* Traffic is going through the RTP TURN relay */
1684 if (rtp->turn_rtp) {
1685 status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
1687 } else if (transport_id == TRANSPORT_TURN_RTCP) {
1688 /* Traffic is going through the RTCP TURN relay */
1689 if (rtp->turn_rtcp) {
1690 status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
1697 /* ICE Session interface declaration */
1698 static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
1699 .on_ice_complete = ast_rtp_on_ice_complete,
1700 .on_rx_data = ast_rtp_on_ice_rx_data,
1701 .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
1704 /*! \brief Worker thread for timerheap */
1705 static int timer_worker_thread(void *data)
1707 pj_ioqueue_t *ioqueue;
1709 if (pj_ioqueue_create(pool, 1, &ioqueue) != PJ_SUCCESS) {
1713 while (!timer_terminate) {
1714 const pj_time_val delay = {0, 10};
1716 pj_timer_heap_poll(timer_heap, NULL);
1717 pj_ioqueue_poll(ioqueue, &delay);
1724 static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
1729 if (!ast_sockaddr_isnull(&rtpdebugaddr)) {
1731 return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
1733 return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
1740 static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
1745 if (!ast_sockaddr_isnull(&rtcpdebugaddr)) {
1746 if (rtcpdebugport) {
1747 return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
1749 return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
1756 #ifdef HAVE_OPENSSL_SRTP
1758 static int dtls_srtp_handle_timeout(const void *data)
1760 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
1761 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1768 ast_mutex_lock(&rtp->dtls_timer_lock);
1769 if (rtp->dtlstimerid == -1)
1771 ast_mutex_unlock(&rtp->dtls_timer_lock);
1772 ao2_ref(instance, -1);
1776 rtp->dtlstimerid = -1;
1777 ast_mutex_unlock(&rtp->dtls_timer_lock);
1779 if (rtp->dtls.ssl && !SSL_is_init_finished(rtp->dtls.ssl)) {
1780 DTLSv1_handle_timeout(rtp->dtls.ssl);
1782 dtls_srtp_check_pending(instance, rtp, 0);
1784 if (rtp->rtcp && rtp->rtcp->dtls.ssl && !SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
1785 DTLSv1_handle_timeout(rtp->rtcp->dtls.ssl);
1787 dtls_srtp_check_pending(instance, rtp, 1);
1789 ao2_ref(instance, -1);
1794 static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp, int rtcp)
1796 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
1798 struct timeval dtls_timeout; /* timeout on DTLS */
1800 if (!dtls->ssl || !dtls->write_bio) {
1804 pending = BIO_ctrl_pending(dtls->write_bio);
1807 char outgoing[pending];
1809 struct ast_sockaddr remote_address = { {0, } };
1813 ast_rtp_instance_get_remote_address(instance, &remote_address);
1815 ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
1818 /* If we do not yet know an address to send this to defer it until we do */
1819 if (ast_sockaddr_isnull(&remote_address)) {
1823 out = BIO_read(dtls->write_bio, outgoing, sizeof(outgoing));
1825 /* Stop existing DTLS timer if running */
1826 ast_mutex_lock(&rtp->dtls_timer_lock);
1827 if (rtp->dtlstimerid > -1) {
1828 AST_SCHED_DEL_UNREF(rtp->sched, rtp->dtlstimerid, ao2_ref(instance, -1));
1829 rtp->dtlstimerid = -1;
1832 if (DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
1833 int timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
1834 ao2_ref(instance, +1);
1835 if ((rtp->dtlstimerid = ast_sched_add(rtp->sched, timeout, dtls_srtp_handle_timeout, instance)) < 0) {
1836 ao2_ref(instance, -1);
1837 ast_log(LOG_WARNING, "scheduling DTLS retransmission for RTP instance [%p] failed.\n", instance);
1840 ast_mutex_unlock(&rtp->dtls_timer_lock);
1842 __rtp_sendto(instance, outgoing, out, 0, &remote_address, rtcp, &ice, 0);
1846 static int dtls_srtp_renegotiate(const void *data)
1848 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
1849 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1851 SSL_renegotiate(rtp->dtls.ssl);
1852 SSL_do_handshake(rtp->dtls.ssl);
1853 dtls_srtp_check_pending(instance, rtp, 0);
1855 if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
1856 SSL_renegotiate(rtp->rtcp->dtls.ssl);
1857 SSL_do_handshake(rtp->rtcp->dtls.ssl);
1858 dtls_srtp_check_pending(instance, rtp, 1);
1862 ao2_ref(instance, -1);
1867 static int dtls_srtp_setup(struct ast_rtp *rtp, struct ast_srtp *srtp, struct ast_rtp_instance *instance)
1869 unsigned char material[SRTP_MASTER_LEN * 2];
1870 unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
1871 struct ast_srtp_policy *local_policy, *remote_policy = NULL;
1872 struct ast_rtp_instance_stats stats = { 0, };
1875 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
1876 if (rtp->dtls_verify & AST_RTP_DTLS_VERIFY_FINGERPRINT) {
1879 if (!(certificate = SSL_get_peer_certificate(rtp->dtls.ssl))) {
1880 ast_log(LOG_WARNING, "No certificate was provided by the peer on RTP instance '%p'\n", instance);
1884 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
1885 if (rtp->remote_fingerprint[0]) {
1887 unsigned char fingerprint[EVP_MAX_MD_SIZE];
1890 if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA1) {
1892 } else if (rtp->remote_hash == AST_RTP_DTLS_HASH_SHA256) {
1893 type = EVP_sha256();
1895 ast_log(LOG_WARNING, "Unsupported fingerprint hash type on RTP instance '%p'\n", instance);
1899 if (!X509_digest(certificate, type, fingerprint, &size) ||
1901 memcmp(fingerprint, rtp->remote_fingerprint, size)) {
1902 X509_free(certificate);
1903 ast_log(LOG_WARNING, "Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
1909 X509_free(certificate);
1912 /* Ensure that certificate verification was successful */
1913 if ((rtp->dtls_verify & AST_RTP_DTLS_VERIFY_CERTIFICATE) && SSL_get_verify_result(rtp->dtls.ssl) != X509_V_OK) {
1914 ast_log(LOG_WARNING, "Peer certificate on RTP instance '%p' failed verification test\n",
1919 /* Produce key information and set up SRTP */
1920 if (!SSL_export_keying_material(rtp->dtls.ssl, material, SRTP_MASTER_LEN * 2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
1921 ast_log(LOG_WARNING, "Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
1926 /* Whether we are acting as a server or client determines where the keys/salts are */
1927 if (rtp->dtls.dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
1928 local_key = material;
1929 remote_key = local_key + SRTP_MASTER_KEY_LEN;
1930 local_salt = remote_key + SRTP_MASTER_KEY_LEN;
1931 remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
1933 remote_key = material;
1934 local_key = remote_key + SRTP_MASTER_KEY_LEN;
1935 remote_salt = local_key + SRTP_MASTER_KEY_LEN;
1936 local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
1939 if (!(local_policy = res_srtp_policy->alloc())) {
1943 if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
1944 ast_log(LOG_WARNING, "Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
1948 if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
1949 ast_log(LOG_WARNING, "Could not set suite to '%u' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
1953 if (ast_rtp_instance_get_stats(instance, &stats, AST_RTP_INSTANCE_STAT_LOCAL_SSRC)) {
1957 res_srtp_policy->set_ssrc(local_policy, stats.local_ssrc, 0);
1959 if (!(remote_policy = res_srtp_policy->alloc())) {
1963 if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
1964 ast_log(LOG_WARNING, "Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
1968 if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
1969 ast_log(LOG_WARNING, "Could not set suite to '%u' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
1973 res_srtp_policy->set_ssrc(remote_policy, 0, 1);
1975 if (ast_rtp_instance_add_srtp_policy(instance, remote_policy, local_policy)) {
1976 ast_log(LOG_WARNING, "Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
1981 ao2_ref(instance, +1);
1982 if ((rtp->rekeyid = ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
1983 ao2_ref(instance, -1);
1991 /* policy->destroy() called even on success to release local reference to these resources */
1992 res_srtp_policy->destroy(local_policy);
1994 if (remote_policy) {
1995 res_srtp_policy->destroy(remote_policy);
2002 static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
2005 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2006 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
2008 #ifdef HAVE_PJPROJECT
2009 struct ast_sockaddr *loop = rtcp ? &rtp->rtcp_loop : &rtp->rtp_loop;
2012 if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
2016 #ifdef HAVE_OPENSSL_SRTP
2017 dtls_srtp_check_pending(instance, rtp, rtcp);
2019 /* If this is an SSL packet pass it to OpenSSL for processing. RFC section for first byte value:
2020 * https://tools.ietf.org/html/rfc5764#section-5.1.2 */
2021 if ((*in >= 20) && (*in <= 63)) {
2022 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2025 /* If no SSL session actually exists terminate things */
2027 ast_log(LOG_ERROR, "Received SSL traffic on RTP instance '%p' without an SSL session\n",
2032 /* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
2033 if (dtls->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
2034 dtls->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
2035 SSL_set_accept_state(dtls->ssl);
2038 dtls_srtp_check_pending(instance, rtp, rtcp);
2040 BIO_write(dtls->read_bio, buf, len);
2042 len = SSL_read(dtls->ssl, buf, len);
2044 if ((len < 0) && (SSL_get_error(dtls->ssl, len) == SSL_ERROR_SSL)) {
2045 unsigned long error = ERR_get_error();
2046 ast_log(LOG_ERROR, "DTLS failure occurred on RTP instance '%p' due to reason '%s', terminating\n",
2047 instance, ERR_reason_error_string(error));
2051 dtls_srtp_check_pending(instance, rtp, rtcp);
2053 if (SSL_is_init_finished(dtls->ssl)) {
2054 /* Any further connections will be existing since this is now established */
2055 dtls->connection = AST_RTP_DTLS_CONNECTION_EXISTING;
2057 /* Use the keying material to set up key/salt information */
2058 res = dtls_srtp_setup(rtp, srtp, instance);
2066 #ifdef HAVE_PJPROJECT
2067 if (!ast_sockaddr_isnull(loop) && !ast_sockaddr_cmp(loop, sa)) {
2068 /* ICE traffic will have been handled in the TURN callback, so skip it but update the address
2069 * so it reflects the actual source and not the loopback
2072 ast_sockaddr_copy(sa, &rtp->rtcp->them);
2074 ast_rtp_instance_get_remote_address(instance, sa);
2076 } else if (rtp->ice) {
2077 pj_str_t combined = pj_str(ast_sockaddr_stringify(sa));
2078 pj_sockaddr address;
2081 pj_thread_register_check();
2083 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
2085 status = pj_ice_sess_on_rx_pkt(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP,
2086 rtcp ? TRANSPORT_SOCKET_RTCP : TRANSPORT_SOCKET_RTP, buf, len, &address,
2087 pj_sockaddr_get_len(&address));
2088 if (status != PJ_SUCCESS) {
2091 pj_strerror(status, buf, sizeof(buf));
2092 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
2096 if (!rtp->passthrough) {
2099 rtp->passthrough = 0;
2103 if ((*in & 0xC0) && res_srtp && srtp && res_srtp->unprotect(srtp, buf, &len, rtcp) < 0) {
2110 static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
2112 return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
2115 static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
2117 return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
2120 static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *ice, int use_srtp)
2124 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2125 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
2129 if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
2133 #ifdef HAVE_PJPROJECT
2135 pj_thread_register_check();
2137 if (pj_ice_sess_send_data(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP, temp, len) == PJ_SUCCESS) {
2144 return ast_sendto(rtcp ? rtp->rtcp->s : rtp->s, temp, len, flags, sa);
2147 static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
2149 return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
2152 static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
2154 return __rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1);
2157 static int rtp_get_rate(struct ast_format *format)
2159 /* For those wondering: due to a fluke in RFC publication, G.722 is advertised
2160 * as having a sample rate of 8kHz, while implementations must know that its
2161 * real rate is 16kHz. Seriously.
2163 return (ast_format_cmp(format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) ? 8000 : (int)ast_format_get_sample_rate(format);
2166 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
2168 unsigned int interval;
2169 /*! \todo XXX Do a more reasonable calculation on this one
2170 * Look in RFC 3550 Section A.7 for an example*/
2171 interval = rtcpinterval;
2175 /*! \brief Calculate normal deviation */
2176 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
2178 normdev = normdev * sample_count + sample;
2181 return normdev / sample_count;
2184 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
2187 for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
2188 return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
2189 we can compute the sigma^2 and that way we would have to do the sqrt only 1 time at the end and would save another pow 2 compute
2192 #define SQUARE(x) ((x) * (x))
2194 stddev = sample_count * stddev;
2198 ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
2199 ( SQUARE(sample - normdev_curent) / sample_count );
2204 static int create_new_socket(const char *type, int af)
2206 int sock = socket(af, SOCK_DGRAM, 0);
2212 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
2214 long flags = fcntl(sock, F_GETFL);
2215 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
2218 setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
2228 * \brief Initializes sequence values and probation for learning mode.
2229 * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
2231 * \param info The learning information to track
2232 * \param seq sequence number read from the rtp header to initialize the information with
2234 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
2236 info->max_seq = seq - 1;
2237 info->packets = learning_min_sequential;
2242 * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
2243 * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
2245 * \param info Structure tracking the learning progress of some address
2246 * \param seq sequence number read from the rtp header
2247 * \retval 0 if probation mode should exit for this address
2248 * \retval non-zero if probation mode should continue
2250 static int rtp_learning_rtp_seq_update(struct rtp_learning_info *info, uint16_t seq)
2252 if (seq == info->max_seq + 1) {
2253 /* packet is in sequence */
2256 /* Sequence discontinuity; reset */
2257 info->packets = learning_min_sequential - 1;
2259 info->max_seq = seq;
2261 return (info->packets == 0);
2264 #ifdef HAVE_PJPROJECT
2265 static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component,
2268 pj_sockaddr address[16];
2269 unsigned int count = PJ_ARRAY_SIZE(address), pos = 0;
2271 /* Add all the local interface IP addresses */
2272 if (ast_sockaddr_is_ipv4(addr)) {
2273 pj_enum_ip_interface(pj_AF_INET(), &count, address);
2274 } else if (ast_sockaddr_is_any(addr)) {
2275 pj_enum_ip_interface(pj_AF_UNSPEC(), &count, address);
2277 pj_enum_ip_interface(pj_AF_INET6(), &count, address);
2280 for (pos = 0; pos < count; pos++) {
2281 pj_sockaddr_set_port(&address[pos], port);
2282 ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_HOST, 65535, &address[pos], &address[pos], NULL,
2283 pj_sockaddr_get_len(&address[pos]));
2286 /* If configured to use a STUN server to get our external mapped address do so */
2287 if (stunaddr.sin_addr.s_addr && ast_sockaddr_is_ipv4(addr) && count) {
2288 struct sockaddr_in answer;
2290 if (!ast_stun_request(component == AST_RTP_ICE_COMPONENT_RTCP ? rtp->rtcp->s : rtp->s, &stunaddr, NULL, &answer)) {
2292 pj_str_t mapped = pj_str(ast_strdupa(ast_inet_ntoa(answer.sin_addr)));
2294 /* Use the first local host candidate as the base */
2295 pj_sockaddr_cp(&base, &address[0]);
2297 pj_sockaddr_init(pj_AF_INET(), &address[0], &mapped, ntohs(answer.sin_port));
2299 ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_SRFLX, 65535, &address[0], &base,
2300 &base, pj_sockaddr_get_len(&address[0]));
2304 /* If configured to use a TURN relay create a session and allocate */
2305 if (pj_strlen(&turnaddr)) {
2306 ast_rtp_ice_turn_request(instance, component, AST_TRANSPORT_TCP, pj_strbuf(&turnaddr), turnport,
2307 pj_strbuf(&turnusername), pj_strbuf(&turnpassword));
2314 * \brief Calculates the elapsed time from issue of the first tx packet in an
2315 * rtp session and a specified time
2317 * \param rtp pointer to the rtp struct with the transmitted rtp packet
2318 * \param delivery time of delivery - if NULL or zero value, will be ast_tvnow()
2320 * \return time elapsed in milliseconds
2322 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2327 if (ast_tvzero(rtp->txcore)) {
2328 rtp->txcore = ast_tvnow();
2329 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2332 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2333 if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
2338 return (unsigned int) ms;
2341 #ifdef HAVE_PJPROJECT
2344 * \brief Creates an ICE session. Can be used to replace a destroyed ICE session.
2346 * \param instance RTP instance for which the ICE session is being replaced
2347 * \param addr ast_sockaddr to use for adding RTP candidates to the ICE session
2348 * \param port port to use for adding RTP candidates to the ICE session
2349 * \param replace 0 when creating a new session, 1 when replacing a destroyed session
2351 * \retval 0 on success
2352 * \retval -1 on failure
2354 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
2355 int port, int replace)
2357 pj_stun_config stun_config;
2358 pj_str_t ufrag, passwd;
2359 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2361 ao2_cleanup(rtp->ice_local_candidates);
2362 rtp->ice_local_candidates = NULL;
2364 pj_thread_register_check();
2366 pj_stun_config_init(&stun_config, &cachingpool.factory, 0, NULL, timer_heap);
2368 ufrag = pj_str(rtp->local_ufrag);
2369 passwd = pj_str(rtp->local_passwd);
2371 /* Create an ICE session for ICE negotiation */
2372 if (pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN, 2,
2373 &ast_rtp_ice_sess_cb, &ufrag, &passwd, NULL, &rtp->ice) == PJ_SUCCESS) {
2374 /* Make this available for the callbacks */
2375 rtp->ice->user_data = instance;
2377 /* Add all of the available candidates to the ICE session */
2378 rtp_add_candidates_to_ice(instance, rtp, addr, port, AST_RTP_ICE_COMPONENT_RTP,
2379 TRANSPORT_SOCKET_RTP);
2381 /* Only add the RTCP candidates to ICE when replacing the session. New sessions
2382 * handle this in a separate part of the setup phase */
2383 if (replace && rtp->rtcp) {
2384 rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us,
2385 ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP,
2386 TRANSPORT_SOCKET_RTCP);
2397 static int ast_rtp_new(struct ast_rtp_instance *instance,
2398 struct ast_sched_context *sched, struct ast_sockaddr *addr,
2401 struct ast_rtp *rtp = NULL;
2404 /* Create a new RTP structure to hold all of our data */
2405 if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
2409 /* Initialize synchronization aspects */
2410 ast_mutex_init(&rtp->lock);
2411 ast_cond_init(&rtp->cond, NULL);
2413 /* Set default parameters on the newly created RTP structure */
2414 rtp->ssrc = ast_random();
2415 rtp->seqno = ast_random() & 0xffff;
2416 rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
2418 rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
2419 rtp_learning_seq_init(&rtp->alt_source_learn, (uint16_t)rtp->seqno);
2422 /* Create a new socket for us to listen on and use */
2424 create_new_socket("RTP",
2425 ast_sockaddr_is_ipv4(addr) ? AF_INET :
2426 ast_sockaddr_is_ipv6(addr) ? AF_INET6 : -1)) < 0) {
2427 ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
2432 /* Now actually find a free RTP port to use */
2433 x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
2438 ast_sockaddr_set_port(addr, x);
2439 /* Try to bind, this will tell us whether the port is available or not */
2440 if (!ast_bind(rtp->s, addr)) {
2441 ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
2442 ast_rtp_instance_set_local_address(instance, addr);
2448 x = (rtpstart + 1) & ~1;
2451 /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
2452 if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
2453 ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
2460 #ifdef HAVE_PJPROJECT
2461 generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
2462 generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
2464 ast_rtp_instance_set_data(instance, rtp);
2465 #ifdef HAVE_PJPROJECT
2466 /* Create an ICE session for ICE negotiation */
2468 if (ice_create(instance, addr, x, 0)) {
2469 ast_log(LOG_NOTICE, "Failed to start ICE session\n");
2472 ast_sockaddr_copy(&rtp->ice_original_rtp_addr, addr);
2477 /* Record any information we may need */
2480 #ifdef HAVE_OPENSSL_SRTP
2482 rtp->dtlstimerid = -1;
2485 rtp->f.subclass.format = ao2_bump(ast_format_none);
2486 rtp->lastrxformat = ao2_bump(ast_format_none);
2487 rtp->lasttxformat = ao2_bump(ast_format_none);
2492 static int ast_rtp_destroy(struct ast_rtp_instance *instance)
2494 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2495 #ifdef HAVE_PJPROJECT
2496 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_STATE_WAIT_TIME, 1000));
2497 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
2500 /* Destroy the smoother that was smoothing out audio if present */
2501 if (rtp->smoother) {
2502 ast_smoother_free(rtp->smoother);
2505 /* Close our own socket so we no longer get packets */
2510 /* Destroy RTCP if it was being used */
2513 * It is not possible for there to be an active RTCP scheduler
2514 * entry at this point since it holds a reference to the
2515 * RTP instance while it's active.
2517 close(rtp->rtcp->s);
2518 #ifdef HAVE_OPENSSL_SRTP
2519 if (rtp->rtcp->dtls.ssl) {
2520 SSL_free(rtp->rtcp->dtls.ssl);
2523 ast_free(rtp->rtcp);
2526 /* Destroy RED if it was being used */
2528 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
2532 #ifdef HAVE_PJPROJECT
2533 pj_thread_register_check();
2535 /* Destroy the RTP TURN relay if being used */
2536 ast_mutex_lock(&rtp->lock);
2537 if (rtp->turn_rtp) {
2538 pj_turn_sock_destroy(rtp->turn_rtp);
2539 rtp->turn_state = PJ_TURN_STATE_NULL;
2540 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
2541 ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
2545 /* Destroy the RTCP TURN relay if being used */
2546 if (rtp->turn_rtcp) {
2547 pj_turn_sock_destroy(rtp->turn_rtcp);
2548 rtp->turn_state = PJ_TURN_STATE_NULL;
2549 while (rtp->turn_state != PJ_TURN_STATE_DESTROYING) {
2550 ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
2553 ast_mutex_unlock(&rtp->lock);
2556 rtp_ioqueue_thread_remove(rtp->ioqueue);
2559 /* Destroy the ICE session if being used */
2561 pj_ice_sess_destroy(rtp->ice);
2564 /* Destroy any candidates */
2565 if (rtp->ice_local_candidates) {
2566 ao2_ref(rtp->ice_local_candidates, -1);
2569 if (rtp->ice_active_remote_candidates) {
2570 ao2_ref(rtp->ice_active_remote_candidates, -1);
2574 #ifdef HAVE_OPENSSL_SRTP
2575 /* Destroy the SSL context if present */
2577 SSL_CTX_free(rtp->ssl_ctx);
2580 /* Destroy the SSL session if present */
2581 if (rtp->dtls.ssl) {
2582 SSL_free(rtp->dtls.ssl);
2586 ao2_cleanup(rtp->lasttxformat);
2587 ao2_cleanup(rtp->lastrxformat);
2588 ao2_cleanup(rtp->f.subclass.format);
2590 /* Destroy synchronization items */
2591 ast_mutex_destroy(&rtp->lock);
2592 ast_cond_destroy(&rtp->cond);
2594 /* Finally destroy ourselves */
2600 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
2602 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2603 rtp->dtmfmode = dtmf_mode;
2607 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
2609 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2610 return rtp->dtmfmode;
2613 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
2615 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2616 struct ast_sockaddr remote_address = { {0,} };
2617 int hdrlen = 12, res = 0, i = 0, payload = 101;
2619 unsigned int *rtpheader = (unsigned int*)data;
2621 ast_rtp_instance_get_remote_address(instance, &remote_address);
2623 /* If we have no remote address information bail out now */
2624 if (ast_sockaddr_isnull(&remote_address)) {
2628 /* Convert given digit into what we want to transmit */
2629 if ((digit <= '9') && (digit >= '0')) {
2631 } else if (digit == '*') {
2633 } else if (digit == '#') {
2635 } else if ((digit >= 'A') && (digit <= 'D')) {
2636 digit = digit - 'A' + 12;
2637 } else if ((digit >= 'a') && (digit <= 'd')) {
2638 digit = digit - 'a' + 12;
2640 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2644 /* Grab the payload that they expect the RFC2833 packet to be received in */
2645 payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_DTMF);
2647 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2648 rtp->send_duration = 160;
2649 rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2650 rtp->lastdigitts = rtp->lastts + rtp->send_duration;
2652 /* Create the actual packet that we will be sending */
2653 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2654 rtpheader[1] = htonl(rtp->lastdigitts);
2655 rtpheader[2] = htonl(rtp->ssrc);
2657 /* Actually send the packet */
2658 for (i = 0; i < 2; i++) {
2661 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2662 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2664 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2665 ast_sockaddr_stringify(&remote_address),
2668 if (rtp_debug_test_addr(&remote_address)) {
2669 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
2670 ast_sockaddr_stringify(&remote_address),
2671 ice ? " (via ICE)" : "",
2672 payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2675 rtp->send_duration += 160;
2676 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2679 /* Record that we are in the process of sending a digit and information needed to continue doing so */
2680 rtp->sending_digit = 1;
2681 rtp->send_digit = digit;
2682 rtp->send_payload = payload;
2687 static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
2689 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2690 struct ast_sockaddr remote_address = { {0,} };
2691 int hdrlen = 12, res = 0;
2693 unsigned int *rtpheader = (unsigned int*)data;
2696 ast_rtp_instance_get_remote_address(instance, &remote_address);
2698 /* Make sure we know where the other side is so we can send them the packet */
2699 if (ast_sockaddr_isnull(&remote_address)) {
2703 /* Actually create the packet we will be sending */
2704 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2705 rtpheader[1] = htonl(rtp->lastdigitts);
2706 rtpheader[2] = htonl(rtp->ssrc);
2707 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2709 /* Boom, send it on out */
2710 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2712 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2713 ast_sockaddr_stringify(&remote_address),
2717 if (rtp_debug_test_addr(&remote_address)) {
2718 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
2719 ast_sockaddr_stringify(&remote_address),
2720 ice ? " (via ICE)" : "",
2721 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2724 /* And now we increment some values for the next time we swing by */
2726 rtp->send_duration += 160;
2727 rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2732 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
2734 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2735 struct ast_sockaddr remote_address = { {0,} };
2736 int hdrlen = 12, res = -1, i = 0;
2738 unsigned int *rtpheader = (unsigned int*)data;
2739 unsigned int measured_samples;
2741 ast_rtp_instance_get_remote_address(instance, &remote_address);
2743 /* Make sure we know where the remote side is so we can send them the packet we construct */
2744 if (ast_sockaddr_isnull(&remote_address)) {
2748 /* Convert the given digit to the one we are going to send */
2749 if ((digit <= '9') && (digit >= '0')) {
2751 } else if (digit == '*') {
2753 } else if (digit == '#') {
2755 } else if ((digit >= 'A') && (digit <= 'D')) {
2756 digit = digit - 'A' + 12;
2757 } else if ((digit >= 'a') && (digit <= 'd')) {
2758 digit = digit - 'a' + 12;
2760 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2764 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2766 if (duration > 0 && (measured_samples = duration * rtp_get_rate(rtp->f.subclass.format) / 1000) > rtp->send_duration) {
2767 ast_debug(2, "Adjusting final end duration from %d to %u\n", rtp->send_duration, measured_samples);
2768 rtp->send_duration = measured_samples;
2771 /* Construct the packet we are going to send */
2772 rtpheader[1] = htonl(rtp->lastdigitts);
2773 rtpheader[2] = htonl(rtp->ssrc);
2774 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2775 rtpheader[3] |= htonl((1 << 23));
2777 /* Send it 3 times, that's the magical number */
2778 for (i = 0; i < 3; i++) {
2781 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2783 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2786 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2787 ast_sockaddr_stringify(&remote_address),
2791 if (rtp_debug_test_addr(&remote_address)) {
2792 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
2793 ast_sockaddr_stringify(&remote_address),
2794 ice ? " (via ICE)" : "",
2795 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2802 /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
2803 rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2805 rtp->sending_digit = 0;
2806 rtp->send_digit = 0;
2811 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
2813 return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
2816 static void ast_rtp_update_source(struct ast_rtp_instance *instance)
2818 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2820 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
2821 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2822 ast_debug(3, "Setting the marker bit due to a source update\n");
2827 static void ast_rtp_change_source(struct ast_rtp_instance *instance)
2829 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2830 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
2831 unsigned int ssrc = ast_random();
2834 ast_debug(3, "Not changing SSRC since we haven't sent any RTP yet\n");
2838 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
2839 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2841 ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
2844 ast_debug(3, "Changing ssrc for SRTP from %u to %u\n", rtp->ssrc, ssrc);
2845 res_srtp->change_source(srtp, rtp->ssrc, ssrc);
2853 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
2855 unsigned int sec, usec, frac;
2856 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
2858 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
2863 static void ntp2timeval(unsigned int msw, unsigned int lsw, struct timeval *tv)
2865 tv->tv_sec = msw - 2208988800u;
2866 tv->tv_usec = ((lsw << 6) / 3650) - (lsw >> 12) - (lsw >> 8);
2869 static void calculate_lost_packet_statistics(struct ast_rtp *rtp,
2870 unsigned int *lost_packets,
2873 unsigned int extended_seq_no;
2874 unsigned int expected_packets;
2875 unsigned int expected_interval;
2876 unsigned int received_interval;
2877 double rxlost_current;
2880 /* Compute statistics */
2881 extended_seq_no = rtp->cycles + rtp->lastrxseqno;
2882 expected_packets = extended_seq_no - rtp->seedrxseqno + 1;
2883 if (rtp->rxcount > expected_packets) {
2884 expected_packets += rtp->rxcount - expected_packets;
2886 *lost_packets = expected_packets - rtp->rxcount;
2887 expected_interval = expected_packets - rtp->rtcp->expected_prior;
2888 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2889 lost_interval = expected_interval - received_interval;
2890 if (expected_interval == 0 || lost_interval <= 0) {
2893 *fraction_lost = (lost_interval << 8) / expected_interval;
2896 /* Update RTCP statistics */
2897 rtp->rtcp->received_prior = rtp->rxcount;
2898 rtp->rtcp->expected_prior = expected_packets;
2899 if (lost_interval <= 0) {
2900 rtp->rtcp->rxlost = 0;
2902 rtp->rtcp->rxlost = lost_interval;
2904 if (rtp->rtcp->rxlost_count == 0) {
2905 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
2907 if (lost_interval < rtp->rtcp->minrxlost) {
2908 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
2910 if (lost_interval > rtp->rtcp->maxrxlost) {
2911 rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
2913 rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost,
2915 rtp->rtcp->rxlost_count);
2916 rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost,
2918 rtp->rtcp->normdev_rxlost,
2920 rtp->rtcp->rxlost_count);
2921 rtp->rtcp->normdev_rxlost = rxlost_current;
2922 rtp->rtcp->rxlost_count++;
2925 /*! \brief Send RTCP SR or RR report */
2926 static int ast_rtcp_write_report(struct ast_rtp_instance *instance, int sr)
2928 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2929 RAII_VAR(struct ast_json *, message_blob, NULL, ast_json_unref);
2933 unsigned int now_lsw;
2934 unsigned int now_msw;
2935 unsigned int *rtcpheader;
2936 unsigned int lost_packets;
2938 struct timeval dlsr = { 0, };
2940 int rate = rtp_get_rate(rtp->f.subclass.format);
2942 int header_offset = 0;
2943 char *str_remote_address;
2944 char *str_local_address;
2945 struct ast_sockaddr remote_address = { { 0, } };
2946 struct ast_sockaddr local_address = { { 0, } };
2947 struct ast_sockaddr real_remote_address = { { 0, } };
2948 struct ast_sockaddr real_local_address = { { 0, } };
2949 struct ast_rtp_rtcp_report_block *report_block = NULL;
2950 RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report,
2951 ast_rtp_rtcp_report_alloc(rtp->themssrc ? 1 : 0),
2954 if (!rtp || !rtp->rtcp) {
2958 if (ast_sockaddr_isnull(&rtp->rtcp->them)) { /* This'll stop rtcp for this rtp session */
2959 /* RTCP was stopped. */
2967 /* Compute statistics */
2968 calculate_lost_packet_statistics(rtp, &lost_packets, &fraction_lost);
2970 gettimeofday(&now, NULL);
2971 rtcp_report->reception_report_count = rtp->themssrc ? 1 : 0;
2972 rtcp_report->ssrc = rtp->ssrc;
2973 rtcp_report->type = sr ? RTCP_PT_SR : RTCP_PT_RR;
2975 rtcp_report->sender_information.ntp_timestamp = now;
2976 rtcp_report->sender_information.rtp_timestamp = rtp->lastts;
2977 rtcp_report->sender_information.packet_count = rtp->txcount;
2978 rtcp_report->sender_information.octet_count = rtp->txoctetcount;
2981 if (rtp->themssrc) {
2982 report_block = ast_calloc(1, sizeof(*report_block));
2983 if (!report_block) {
2987 rtcp_report->report_block[0] = report_block;
2988 report_block->source_ssrc = rtp->themssrc;
2989 report_block->lost_count.fraction = (fraction_lost & 0xff);
2990 report_block->lost_count.packets = (lost_packets & 0xffffff);
2991 report_block->highest_seq_no = (rtp->cycles | (rtp->lastrxseqno & 0xffff));
2992 report_block->ia_jitter = (unsigned int)(rtp->rxjitter * rate);
2993 report_block->lsr = rtp->rtcp->themrxlsr;
2994 /* If we haven't received an SR report, DLSR should be 0 */
2995 if (!ast_tvzero(rtp->rtcp->rxlsr)) {
2996 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2997 report_block->dlsr = (((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000;
3000 timeval2ntp(rtcp_report->sender_information.ntp_timestamp, &now_msw, &now_lsw);
3001 rtcpheader = (unsigned int *)bdata;
3002 rtcpheader[1] = htonl(rtcp_report->ssrc); /* Our SSRC */
3006 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
3007 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
3008 rtcpheader[4] = htonl(rtcp_report->sender_information.rtp_timestamp);
3009 rtcpheader[5] = htonl(rtcp_report->sender_information.packet_count);
3010 rtcpheader[6] = htonl(rtcp_report->sender_information.octet_count);
3014 rtcpheader[2 + header_offset] = htonl(report_block->source_ssrc); /* Their SSRC */
3015 rtcpheader[3 + header_offset] = htonl((report_block->lost_count.fraction << 24) | report_block->lost_count.packets);
3016 rtcpheader[4 + header_offset] = htonl(report_block->highest_seq_no);
3017 rtcpheader[5 + header_offset] = htonl(report_block->ia_jitter);
3018 rtcpheader[6 + header_offset] = htonl(report_block->lsr);
3019 rtcpheader[7 + header_offset] = htonl(report_block->dlsr);
3022 rtcpheader[0] = htonl((2 << 30) | (rtcp_report->reception_report_count << 24)
3023 | ((sr ? RTCP_PT_SR : RTCP_PT_RR) << 16) | ((len/4)-1));
3025 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
3026 /* it can change mid call, and SDES can't) */
3027 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
3028 rtcpheader[(len/4)+1] = htonl(rtcp_report->ssrc);
3029 rtcpheader[(len/4)+2] = htonl(0x01 << 24);
3032 ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
3033 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &remote_address, &ice);
3035 ast_log(LOG_ERROR, "RTCP %s transmission error to %s, rtcp halted %s\n",
3037 ast_sockaddr_stringify(&rtp->rtcp->them),
3042 /* Update RTCP SR/RR statistics */
3044 rtp->rtcp->txlsr = rtcp_report->sender_information.ntp_timestamp;
3045 rtp->rtcp->sr_count++;
3046 rtp->rtcp->lastsrtxcount = rtp->txcount;
3048 rtp->rtcp->rr_count++;
3051 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
3052 ast_verbose("* Sent RTCP %s to %s%s\n", sr ? "SR" : "RR",
3053 ast_sockaddr_stringify(&remote_address), ice ? " (via ICE)" : "");
3054 ast_verbose(" Our SSRC: %u\n", rtcp_report->ssrc);
3056 ast_verbose(" Sent(NTP): %u.%010u\n",
3057 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
3058 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec * 4096);
3059 ast_verbose(" Sent(RTP): %u\n", rtcp_report->sender_information.rtp_timestamp);
3060 ast_verbose(" Sent packets: %u\n", rtcp_report->sender_information.packet_count);
3061 ast_verbose(" Sent octets: %u\n", rtcp_report->sender_information.octet_count);
3064 ast_verbose(" Report block:\n");
3065 ast_verbose(" Their SSRC: %u\n", report_block->source_ssrc);
3066 ast_verbose(" Fraction lost: %d\n", report_block->lost_count.fraction);
3067 ast_verbose(" Cumulative loss: %u\n", report_block->lost_count.packets);
3068 ast_verbose(" Highest seq no: %u\n", report_block->highest_seq_no);
3069 ast_verbose(" IA jitter: %.4f\n", (double)report_block->ia_jitter / rate);
3070 ast_verbose(" Their last SR: %u\n", report_block->lsr);
3071 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(report_block->dlsr / 65536.0));
3075 ast_rtp_instance_get_local_address(instance, &local_address);
3076 if (!ast_find_ourip(&real_local_address, &local_address, 0)) {
3077 str_local_address = ast_strdupa(ast_sockaddr_stringify(&real_local_address));
3079 str_local_address = ast_strdupa(ast_sockaddr_stringify(&local_address));
3082 if (!ast_find_ourip(&real_remote_address, &remote_address, 0)) {
3083 str_remote_address = ast_strdupa(ast_sockaddr_stringify(&real_remote_address));
3085 str_remote_address = ast_strdupa(ast_sockaddr_stringify(&remote_address));
3088 message_blob = ast_json_pack("{s: s, s: s}",
3089 "to", str_remote_address,
3090 "from", str_local_address);
3091 ast_rtp_publish_rtcp_message(instance, ast_rtp_rtcp_sent_type(),
3097 /*! \brief Write and RTCP packet to the far end
3098 * \note Decide if we are going to send an SR (with Reception Block) or RR
3099 * RR is sent if we have not sent any rtp packets in the previous interval */
3100 static int ast_rtcp_write(const void *data)
3102 struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
3103 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3106 if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
3107 ao2_ref(instance, -1);
3111 if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
3113 res = ast_rtcp_write_report(instance, 1);
3116 res = ast_rtcp_write_report(instance, 0);
3121 * Not being rescheduled.
3123 ao2_ref(instance, -1);
3124 rtp->rtcp->schedid = -1;
3130 static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
3132 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3134 unsigned int ms = calc_txstamp(rtp, &frame->delivery);
3135 struct ast_sockaddr remote_address = { {0,} };
3136 int rate = rtp_get_rate(frame->subclass.format) / 1000;
3138 if (ast_format_cmp(frame->subclass.format, ast_format_g722) == AST_FORMAT_CMP_EQUAL) {
3139 frame->samples /= 2;
3142 if (rtp->sending_digit) {
3146 if (frame->frametype == AST_FRAME_VOICE) {
3147 pred = rtp->lastts + frame->samples;
3149 /* Re-calculate last TS */
3150 rtp->lastts = rtp->lastts + ms * rate;
3151 if (ast_tvzero(frame->delivery)) {
3152 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
3153 and if so, go with our prediction */
3154 if (abs((int)rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
3157 ast_debug(3, "Difference is %d, ms is %u\n", abs((int)rtp->lastts - pred), ms);
3161 } else if (frame->frametype == AST_FRAME_VIDEO) {
3162 mark = frame->subclass.frame_ending;
3163 pred = rtp->lastovidtimestamp + frame->samples;
3164 /* Re-calculate last TS */
3165 rtp->lastts = rtp->lastts + ms * 90;
3166 /* If it's close to our prediction, go for it */
3167 if (ast_tvzero(frame->delivery)) {
3168 if (abs((int)rtp->lastts - pred) < 7200) {
3170 rtp->lastovidtimestamp += frame->samples;
3172 ast_debug(3, "Difference is %d, ms is %u (%u), pred/ts/samples %u/%d/%d\n", abs((int)rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
3173 rtp->lastovidtimestamp = rtp->lastts;
3177 pred = rtp->lastotexttimestamp + frame->samples;
3178 /* Re-calculate last TS */
3179 rtp->lastts = rtp->lastts + ms;
3180 /* If it's close to our prediction, go for it */
3181 if (ast_tvzero(frame->delivery)) {
3182 if (abs((int)rtp->lastts - pred) < 7200) {
3184 rtp->lastotexttimestamp += frame->samples;
3186 ast_debug(3, "Difference is %d, ms is %u, pred/ts/samples %u/%d/%d\n", abs((int)rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
3187 rtp->lastotexttimestamp = rtp->lastts;
3192 /* If we have been explicitly told to set the marker bit then do so */
3193 if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
3195 ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
3198 /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
3199 if (rtp->lastts > rtp->lastdigitts) {
3200 rtp->lastdigitts = rtp->lastts;
3203 if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
3204 rtp->lastts = frame->ts * rate;
3207 ast_rtp_instance_get_remote_address(instance, &remote_address);
3209 /* If we know the remote address construct a packet and send it out */
3210 if (!ast_sockaddr_isnull(&remote_address)) {
3211 int hdrlen = 12, res, ice;
3212 unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
3214 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
3215 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
3216 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
3218 if ((res = rtp_sendto(instance, (void *)rtpheader, frame->datalen + hdrlen, 0, &remote_address, &ice)) < 0) {
3219 if (!ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
3220 ast_debug(1, "RTP Transmission error of packet %d to %s: %s\n",
3222 ast_sockaddr_stringify(&remote_address),
3224 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
3225 /* Only give this error message once if we are not RTP debugging */