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_FILE_VERSION(__FILE__, "$Revision$")
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/channel.h"
60 #include "asterisk/acl.h"
61 #include "asterisk/config.h"
62 #include "asterisk/lock.h"
63 #include "asterisk/utils.h"
64 #include "asterisk/cli.h"
65 #include "asterisk/manager.h"
66 #include "asterisk/unaligned.h"
67 #include "asterisk/module.h"
68 #include "asterisk/rtp_engine.h"
69 #include "asterisk/test.h"
71 #define MAX_TIMESTAMP_SKEW 640
73 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
74 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
75 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
76 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
78 #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
79 #define DEFAULT_RTP_END 31000 /*!< Default maximum port number to end allocating RTP ports at */
81 #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
82 #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
84 #define DEFAULT_TURN_PORT 34780
86 #define TURN_ALLOCATION_WAIT_TIME 2000
88 #define RTCP_PT_FUR 192
89 #define RTCP_PT_SR AST_RTP_RTCP_SR
90 #define RTCP_PT_RR AST_RTP_RTCP_RR
91 #define RTCP_PT_SDES 202
92 #define RTCP_PT_BYE 203
93 #define RTCP_PT_APP 204
94 /* VP8: RTCP Feedback */
95 #define RTCP_PT_PSFB 206
98 #define DTMF_SAMPLE_RATE_MS 8 /*!< DTMF samples per millisecond */
100 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
102 #define ZFONE_PROFILE_ID 0x505a
104 #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
106 #define SRTP_MASTER_KEY_LEN 16
107 #define SRTP_MASTER_SALT_LEN 14
108 #define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
110 enum strict_rtp_state {
111 STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
112 STRICT_RTP_LEARN, /*! Accept next packet as source */
113 STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
116 #define DEFAULT_STRICT_RTP STRICT_RTP_CLOSED
117 #define DEFAULT_ICESUPPORT 1
119 extern struct ast_srtp_res *res_srtp;
120 extern struct ast_srtp_policy_res *res_srtp_policy;
122 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
124 static int rtpstart = DEFAULT_RTP_START; /*!< First port for RTP sessions (set in rtp.conf) */
125 static int rtpend = DEFAULT_RTP_END; /*!< Last port for RTP sessions (set in rtp.conf) */
126 static int rtpdebug; /*!< Are we debugging? */
127 static int rtcpdebug; /*!< Are we debugging RTCP? */
128 static int rtcpstats; /*!< Are we debugging RTCP? */
129 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
130 static struct ast_sockaddr rtpdebugaddr; /*!< Debug packets to/from this host */
131 static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
132 static int rtpdebugport; /*< Debug only RTP packets from IP or IP+Port if port is > 0 */
133 static int rtcpdebugport; /*< Debug only RTCP packets from IP or IP+Port if port is > 0 */
135 static int nochecksums;
137 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. */
138 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. */
139 #ifdef HAVE_PJPROJECT
140 static int icesupport = DEFAULT_ICESUPPORT;
141 static struct sockaddr_in stunaddr;
142 static pj_str_t turnaddr;
143 static int turnport = DEFAULT_TURN_PORT;
144 static pj_str_t turnusername;
145 static pj_str_t turnpassword;
147 /*! \brief Pool factory used by pjlib to allocate memory. */
148 static pj_caching_pool cachingpool;
150 /*! \brief Pool used by pjlib functions which require memory allocation. */
151 static pj_pool_t *pool;
153 /*! \brief I/O queue for TURN relay traffic */
154 static pj_ioqueue_t *ioqueue;
156 /*! \brief Timer heap for ICE and TURN stuff */
157 static pj_timer_heap_t *timerheap;
159 /*! \brief Worker thread for ICE/TURN */
160 static pj_thread_t *thread;
162 /*! \brief Notification that the ICE/TURN worker thread should stop */
163 static int worker_terminate;
166 #define FLAG_3389_WARNING (1 << 0)
167 #define FLAG_NAT_ACTIVE (3 << 1)
168 #define FLAG_NAT_INACTIVE (0 << 1)
169 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
170 #define FLAG_NEED_MARKER_BIT (1 << 3)
171 #define FLAG_DTMF_COMPENSATE (1 << 4)
173 #define TRANSPORT_SOCKET_RTP 1
174 #define TRANSPORT_SOCKET_RTCP 2
175 #define TRANSPORT_TURN_RTP 3
176 #define TRANSPORT_TURN_RTCP 4
178 /*! \brief RTP learning mode tracking information */
179 struct rtp_learning_info {
180 int max_seq; /*!< The highest sequence number received */
181 int packets; /*!< The number of remaining packets before the source is accepted */
184 /*! \brief RTP session description */
188 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
189 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
190 unsigned int themssrc; /*!< Their SSRC */
193 unsigned int lastrxts;
194 unsigned int lastividtimestamp;
195 unsigned int lastovidtimestamp;
196 unsigned int lastitexttimestamp;
197 unsigned int lastotexttimestamp;
198 unsigned int lasteventseqn;
199 int lastrxseqno; /*!< Last received sequence number */
200 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
201 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
202 unsigned int rxcount; /*!< How many packets have we received? */
203 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
204 unsigned int txcount; /*!< How many packets have we sent? */
205 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
206 unsigned int cycles; /*!< Shifted count of sequence number cycles */
207 double rxjitter; /*!< Interarrival jitter at the moment in seconds */
208 double rxtransit; /*!< Relative transit time for previous packet */
209 struct ast_format lasttxformat;
210 struct ast_format lastrxformat;
212 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
213 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
214 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
216 /* DTMF Reception Variables */
217 char resp; /*!< The current digit being processed */
218 unsigned int last_seqno; /*!< The last known sequence number for any DTMF packet */
219 unsigned int last_end_timestamp; /*!< The last known timestamp received from an END packet */
220 unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
221 unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
222 unsigned int dtmfsamples;
223 enum ast_rtp_dtmf_mode dtmfmode; /*!< The current DTMF mode of the RTP stream */
224 /* DTMF Transmission Variables */
225 unsigned int lastdigitts;
226 char sending_digit; /*!< boolean - are we sending digits */
227 char send_digit; /*!< digit we are sending */
231 struct timeval rxcore;
232 struct timeval txcore;
233 double drxcore; /*!< The double representation of the first received packet */
234 struct timeval lastrx; /*!< timeval when we last received a packet */
235 struct timeval dtmfmute;
236 struct ast_smoother *smoother;
238 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
239 unsigned short rxseqno;
240 struct ast_sched_context *sched;
241 struct io_context *io;
243 struct ast_rtcp *rtcp;
244 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
246 enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
247 struct ast_sockaddr strict_rtp_address; /*!< Remote address information for strict RTP purposes */
250 * Learning mode values based on pjmedia's probation mode. Many of these values are redundant to the above,
251 * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
253 struct rtp_learning_info rtp_source_learn; /* Learning mode track for the expected RTP source */
254 struct rtp_learning_info alt_source_learn; /* Learning mode tracking for a new RTP source after one has been chosen */
258 ast_mutex_t lock; /*!< Lock for synchronization purposes */
259 ast_cond_t cond; /*!< Condition for signaling */
261 #ifdef HAVE_PJPROJECT
262 pj_ice_sess *ice; /*!< ICE session */
263 pj_turn_sock *turn_rtp; /*!< RTP TURN relay */
264 pj_turn_sock *turn_rtcp; /*!< RTCP TURN relay */
265 pj_turn_state_t turn_state; /*!< Current state of the TURN relay session */
266 unsigned int passthrough:1; /*!< Bit to indicate that the received packet should be passed through */
267 unsigned int ice_port; /*!< Port that ICE was started with if it was previously started */
269 char remote_ufrag[256]; /*!< The remote ICE username */
270 char remote_passwd[256]; /*!< The remote ICE password */
272 char local_ufrag[256]; /*!< The local ICE username */
273 char local_passwd[256]; /*!< The local ICE password */
275 struct ao2_container *ice_local_candidates; /*!< The local ICE candidates */
276 struct ao2_container *ice_active_remote_candidates; /*!< The remote ICE candidates */
277 struct ao2_container *ice_proposed_remote_candidates; /*!< Incoming remote ICE candidates for new session */
278 struct ast_sockaddr ice_original_rtp_addr; /*!< rtp address that ICE started on first session */
281 #ifdef HAVE_OPENSSL_SRTP
282 SSL_CTX *ssl_ctx; /*!< SSL context */
283 SSL *ssl; /*!< SSL session */
284 BIO *read_bio; /*!< Memory buffer for reading */
285 BIO *write_bio; /*!< Memory buffer for writing */
286 ast_mutex_t dtls_timer_lock; /*!< Lock for synchronization purposes */
287 enum ast_rtp_dtls_setup dtls_setup; /*!< Current setup state */
288 enum ast_srtp_suite suite; /*!< SRTP crypto suite */
289 char local_fingerprint[160]; /*!< Fingerprint of our certificate */
290 unsigned char remote_fingerprint[EVP_MAX_MD_SIZE]; /*!< Fingerprint of the peer certificate */
291 enum ast_rtp_dtls_connection connection; /*!< Whether this is a new or existing connection */
292 unsigned int dtls_failure:1; /*!< Failure occurred during DTLS negotiation */
293 unsigned int rekey; /*!< Interval at which to renegotiate and rekey */
294 int rekeyid; /*!< Scheduled item id for rekeying */
295 int dtlstimerid; /*!< Scheduled item id for DTLS retransmission for RTP */
300 * \brief Structure defining an RTCP session.
302 * The concept "RTCP session" is not defined in RFC 3550, but since
303 * this structure is analogous to ast_rtp, which tracks a RTP session,
304 * it is logical to think of this as a RTCP session.
306 * RTCP packet is defined on page 9 of RFC 3550.
311 int s; /*!< Socket */
312 struct ast_sockaddr us; /*!< Socket representation of the local endpoint. */
313 struct ast_sockaddr them; /*!< Socket representation of the remote endpoint. */
314 unsigned int soc; /*!< What they told us */
315 unsigned int spc; /*!< What they told us */
316 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
317 struct timeval rxlsr; /*!< Time when we got their last SR */
318 struct timeval txlsr; /*!< Time when we sent or last SR*/
319 unsigned int expected_prior; /*!< no. packets in previous interval */
320 unsigned int received_prior; /*!< no. packets received in previous interval */
321 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
322 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
323 unsigned int sr_count; /*!< number of SRs we've sent */
324 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
325 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
326 double rtt; /*!< Last reported rtt */
327 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
328 unsigned int reported_lost; /*!< Reported lost packets in their RR */
330 double reported_maxjitter;
331 double reported_minjitter;
332 double reported_normdev_jitter;
333 double reported_stdev_jitter;
334 unsigned int reported_jitter_count;
336 double reported_maxlost;
337 double reported_minlost;
338 double reported_normdev_lost;
339 double reported_stdev_lost;
344 double normdev_rxlost;
346 unsigned int rxlost_count;
350 double normdev_rxjitter;
351 double stdev_rxjitter;
352 unsigned int rxjitter_count;
357 unsigned int rtt_count;
359 /* VP8: sequence number for the RTCP FIR FCI */
364 struct ast_frame t140; /*!< Primary data */
365 struct ast_frame t140red; /*!< Redundant t140*/
366 unsigned char pt[AST_RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
367 unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
368 unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
369 int num_gen; /*!< Number of generations */
370 int schedid; /*!< Timer id */
371 int ti; /*!< How long to buffer data before send */
372 unsigned char t140red_data[64000];
373 unsigned char buf_data[64000]; /*!< buffered primary data */
378 AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
380 /* Forward Declarations */
381 static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
382 static int ast_rtp_destroy(struct ast_rtp_instance *instance);
383 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
384 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
385 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
386 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
387 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
388 static void ast_rtp_update_source(struct ast_rtp_instance *instance);
389 static void ast_rtp_change_source(struct ast_rtp_instance *instance);
390 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
391 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
392 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
393 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
394 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
395 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
396 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
397 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
398 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
399 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
400 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
401 static void ast_rtp_stop(struct ast_rtp_instance *instance);
402 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
403 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
405 #ifdef HAVE_OPENSSL_SRTP
406 static int ast_rtp_activate(struct ast_rtp_instance *instance);
407 static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp);
410 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);
412 /*! \brief Helper function which updates an ast_sockaddr with the candidate used for the component */
413 static void update_address_with_ice_candidate(struct ast_rtp *rtp, int component, struct ast_sockaddr *cand_address)
415 #ifdef HAVE_PJPROJECT
416 char address[PJ_INET6_ADDRSTRLEN];
418 if (!rtp->ice || (component < 1) || !rtp->ice->comp[component - 1].valid_check) {
422 ast_sockaddr_parse(cand_address, pj_sockaddr_print(&rtp->ice->comp[component - 1].valid_check->rcand->addr, address, sizeof(address), 0), 0);
423 ast_sockaddr_set_port(cand_address, pj_sockaddr_get_port(&rtp->ice->comp[component - 1].valid_check->rcand->addr));
427 #ifdef HAVE_PJPROJECT
428 /*! \brief Destructor for locally created ICE candidates */
429 static void ast_rtp_ice_candidate_destroy(void *obj)
431 struct ast_rtp_engine_ice_candidate *candidate = obj;
433 if (candidate->foundation) {
434 ast_free(candidate->foundation);
437 if (candidate->transport) {
438 ast_free(candidate->transport);
442 static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
444 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
446 if (!ast_strlen_zero(ufrag)) {
447 ast_copy_string(rtp->remote_ufrag, ufrag, sizeof(rtp->remote_ufrag));
450 if (!ast_strlen_zero(password)) {
451 ast_copy_string(rtp->remote_passwd, password, sizeof(rtp->remote_passwd));
455 static int ice_candidate_cmp(void *obj, void *arg, int flags)
457 struct ast_rtp_engine_ice_candidate *candidate1 = obj, *candidate2 = arg;
459 if (strcmp(candidate1->foundation, candidate2->foundation) ||
460 candidate1->id != candidate2->id ||
461 ast_sockaddr_cmp(&candidate1->address, &candidate2->address) ||
462 candidate1->type != candidate1->type) {
466 return CMP_MATCH | CMP_STOP;
469 static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
471 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
472 struct ast_rtp_engine_ice_candidate *remote_candidate;
474 if (!rtp->ice_proposed_remote_candidates &&
475 !(rtp->ice_proposed_remote_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
479 /* If this is going to exceed the maximum number of ICE candidates don't even add it */
480 if (ao2_container_count(rtp->ice_proposed_remote_candidates) == PJ_ICE_MAX_CAND) {
484 if (!(remote_candidate = ao2_alloc(sizeof(*remote_candidate), ast_rtp_ice_candidate_destroy))) {
488 remote_candidate->foundation = ast_strdup(candidate->foundation);
489 remote_candidate->id = candidate->id;
490 remote_candidate->transport = ast_strdup(candidate->transport);
491 remote_candidate->priority = candidate->priority;
492 ast_sockaddr_copy(&remote_candidate->address, &candidate->address);
493 ast_sockaddr_copy(&remote_candidate->relay_address, &candidate->relay_address);
494 remote_candidate->type = candidate->type;
496 ao2_link(rtp->ice_proposed_remote_candidates, remote_candidate);
497 ao2_ref(remote_candidate, -1);
500 AST_THREADSTORAGE(pj_thread_storage);
502 /*! \brief Function used to check if the calling thread is registered with pjlib. If it is not it will be registered. */
503 static void pj_thread_register_check(void)
505 pj_thread_desc *desc;
508 if (pj_thread_is_registered() == PJ_TRUE) {
512 desc = ast_threadstorage_get(&pj_thread_storage, sizeof(pj_thread_desc));
514 ast_log(LOG_ERROR, "Could not get thread desc from thread-local storage. Expect awful things to occur\n");
517 pj_bzero(*desc, sizeof(*desc));
519 if (pj_thread_register("Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
520 ast_log(LOG_ERROR, "Coudln't register thread with PJLIB.\n");
525 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
526 int port, int replace);
528 static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
530 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
536 pj_thread_register_check();
538 pj_ice_sess_destroy(rtp->ice);
542 static int ice_reset_session(struct ast_rtp_instance *instance)
544 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
546 ast_rtp_ice_stop(instance);
547 return ice_create(instance, &rtp->ice_original_rtp_addr, rtp->ice_port, 1);
550 static int ice_candidates_compare(struct ao2_container *left, struct ao2_container *right)
552 struct ao2_iterator i;
553 struct ast_rtp_engine_ice_candidate *right_candidate;
555 if (ao2_container_count(left) != ao2_container_count(right)) {
559 i = ao2_iterator_init(right, 0);
560 while ((right_candidate = ao2_iterator_next(&i))) {
561 struct ast_rtp_engine_ice_candidate *left_candidate = ao2_find(left, right_candidate, OBJ_POINTER);
563 if (!left_candidate) {
564 ao2_ref(right_candidate, -1);
565 ao2_iterator_destroy(&i);
569 ao2_ref(left_candidate, -1);
570 ao2_ref(right_candidate, -1);
572 ao2_iterator_destroy(&i);
577 static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
579 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
580 pj_str_t ufrag = pj_str(rtp->remote_ufrag), passwd = pj_str(rtp->remote_passwd);
581 pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
582 struct ao2_iterator i;
583 struct ast_rtp_engine_ice_candidate *candidate;
586 if (!rtp->ice || !rtp->ice_proposed_remote_candidates) {
590 /* Check for equivalence in the lists */
591 if (rtp->ice_active_remote_candidates &&
592 !ice_candidates_compare(rtp->ice_proposed_remote_candidates, rtp->ice_active_remote_candidates)) {
593 ao2_cleanup(rtp->ice_proposed_remote_candidates);
594 rtp->ice_proposed_remote_candidates = NULL;
598 /* Out with the old, in with the new */
599 ao2_cleanup(rtp->ice_active_remote_candidates);
600 rtp->ice_active_remote_candidates = rtp->ice_proposed_remote_candidates;
601 rtp->ice_proposed_remote_candidates = NULL;
603 /* Reset the ICE session. Is this going to work? */
604 if (ice_reset_session(instance)) {
605 ast_log(LOG_NOTICE, "Failed to create replacement ICE session\n");
609 pj_thread_register_check();
611 i = ao2_iterator_init(rtp->ice_active_remote_candidates, 0);
613 while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
616 pj_strdup2(rtp->ice->pool, &candidates[cand_cnt].foundation, candidate->foundation);
617 candidates[cand_cnt].comp_id = candidate->id;
618 candidates[cand_cnt].prio = candidate->priority;
620 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->address)), &candidates[cand_cnt].addr);
622 if (!ast_sockaddr_isnull(&candidate->relay_address)) {
623 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, pj_cstr(&address, ast_sockaddr_stringify(&candidate->relay_address)), &candidates[cand_cnt].rel_addr);
626 if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
627 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
628 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
629 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
630 } else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
631 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
634 if (candidate->id == AST_RTP_ICE_COMPONENT_RTP && rtp->turn_rtp) {
635 pj_turn_sock_set_perm(rtp->turn_rtp, 1, &candidates[cand_cnt].addr, 1);
636 } else if (candidate->id == AST_RTP_ICE_COMPONENT_RTCP && rtp->turn_rtcp) {
637 pj_turn_sock_set_perm(rtp->turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
641 ao2_ref(candidate, -1);
644 ao2_iterator_destroy(&i);
646 if (pj_ice_sess_create_check_list(rtp->ice, &ufrag, &passwd, ao2_container_count(rtp->ice_active_remote_candidates), &candidates[0]) == PJ_SUCCESS) {
647 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: SUCCESS");
648 pj_ice_sess_start_check(rtp->ice);
649 pj_timer_heap_poll(timerheap, NULL);
650 rtp->strict_rtp_state = STRICT_RTP_OPEN;
654 ast_test_suite_event_notify("ICECHECKLISTCREATE", "Result: FAILURE");
656 /* even though create check list failed don't stop ice as
657 it might still work */
658 ast_debug(1, "Failed to create ICE session check list\n");
659 /* however we do need to reset remote candidates since
660 this function may be re-entered */
661 ao2_ref(rtp->ice_active_remote_candidates, -1);
662 rtp->ice_active_remote_candidates = NULL;
663 rtp->ice->rcand_cnt = rtp->ice->clist.count = 0;
666 static const char *ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
668 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
670 return rtp->local_ufrag;
673 static const char *ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
675 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
677 return rtp->local_passwd;
680 static struct ao2_container *ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
682 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
684 if (rtp->ice_local_candidates) {
685 ao2_ref(rtp->ice_local_candidates, +1);
688 return rtp->ice_local_candidates;
691 static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
693 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
699 pj_thread_register_check();
701 pj_ice_sess_change_role(rtp->ice, PJ_ICE_SESS_ROLE_CONTROLLING);
704 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,
705 const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr, int addr_len)
708 struct ast_rtp_engine_ice_candidate *candidate, *existing;
709 char address[PJ_INET6_ADDRSTRLEN];
711 pj_thread_register_check();
713 pj_ice_calc_foundation(rtp->ice->pool, &foundation, type, addr);
715 if (!rtp->ice_local_candidates && !(rtp->ice_local_candidates = ao2_container_alloc(1, NULL, ice_candidate_cmp))) {
719 if (!(candidate = ao2_alloc(sizeof(*candidate), ast_rtp_ice_candidate_destroy))) {
723 candidate->foundation = ast_strndup(pj_strbuf(&foundation), pj_strlen(&foundation));
724 candidate->id = comp_id;
725 candidate->transport = ast_strdup("UDP");
727 ast_sockaddr_parse(&candidate->address, pj_sockaddr_print(addr, address, sizeof(address), 0), 0);
728 ast_sockaddr_set_port(&candidate->address, pj_sockaddr_get_port(addr));
731 ast_sockaddr_parse(&candidate->relay_address, pj_sockaddr_print(rel_addr, address, sizeof(address), 0), 0);
732 ast_sockaddr_set_port(&candidate->relay_address, pj_sockaddr_get_port(rel_addr));
735 if (type == PJ_ICE_CAND_TYPE_HOST) {
736 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_HOST;
737 } else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
738 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_SRFLX;
739 } else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
740 candidate->type = AST_RTP_ICE_CANDIDATE_TYPE_RELAYED;
743 if ((existing = ao2_find(rtp->ice_local_candidates, candidate, OBJ_POINTER))) {
744 ao2_ref(existing, -1);
745 ao2_ref(candidate, -1);
749 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) {
750 ao2_ref(candidate, -1);
754 /* By placing the candidate into the ICE session it will have produced the priority, so update the local candidate with it */
755 candidate->priority = rtp->ice->lcand[rtp->ice->lcand_cnt - 1].prio;
757 ao2_link(rtp->ice_local_candidates, candidate);
758 ao2_ref(candidate, -1);
761 static char *generate_random_string(char *buf, size_t size)
766 for (x=0; x<4; x++) {
767 val[x] = ast_random();
769 snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
774 /* ICE RTP Engine interface declaration */
775 static struct ast_rtp_engine_ice ast_rtp_ice = {
776 .set_authentication = ast_rtp_ice_set_authentication,
777 .add_remote_candidate = ast_rtp_ice_add_remote_candidate,
778 .start = ast_rtp_ice_start,
779 .stop = ast_rtp_ice_stop,
780 .get_ufrag = ast_rtp_ice_get_ufrag,
781 .get_password = ast_rtp_ice_get_password,
782 .get_local_candidates = ast_rtp_ice_get_local_candidates,
783 .ice_lite = ast_rtp_ice_lite,
787 #ifdef HAVE_OPENSSL_SRTP
788 static void dtls_info_callback(const SSL *ssl, int where, int ret)
790 struct ast_rtp *rtp = SSL_get_ex_data(ssl, 0);
792 /* We only care about alerts */
793 if (!(where & SSL_CB_ALERT)) {
797 rtp->dtls_failure = 1;
800 static int ast_rtp_dtls_set_configuration(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
802 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
804 if (!dtls_cfg->enabled) {
808 if (!ast_rtp_engine_srtp_is_registered()) {
812 if (!(rtp->ssl_ctx = SSL_CTX_new(DTLSv1_method()))) {
816 SSL_CTX_set_verify(rtp->ssl_ctx, dtls_cfg->verify ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT : SSL_VERIFY_NONE, NULL);
818 if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_80) {
819 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_80");
820 } else if (dtls_cfg->suite == AST_AES_CM_128_HMAC_SHA1_32) {
821 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx, "SRTP_AES128_CM_SHA1_32");
823 ast_log(LOG_ERROR, "Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
827 if (!ast_strlen_zero(dtls_cfg->certfile)) {
828 char *private = ast_strlen_zero(dtls_cfg->pvtfile) ? dtls_cfg->certfile : dtls_cfg->pvtfile;
831 unsigned int size, i;
832 unsigned char fingerprint[EVP_MAX_MD_SIZE];
833 char *local_fingerprint = rtp->local_fingerprint;
835 if (!SSL_CTX_use_certificate_file(rtp->ssl_ctx, dtls_cfg->certfile, SSL_FILETYPE_PEM)) {
836 ast_log(LOG_ERROR, "Specified certificate file '%s' for RTP instance '%p' could not be used\n",
837 dtls_cfg->certfile, instance);
841 if (!SSL_CTX_use_PrivateKey_file(rtp->ssl_ctx, private, SSL_FILETYPE_PEM) ||
842 !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
843 ast_log(LOG_ERROR, "Specified private key file '%s' for RTP instance '%p' could not be used\n",
848 if (!(certbio = BIO_new(BIO_s_file()))) {
849 ast_log(LOG_ERROR, "Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
854 if (!BIO_read_filename(certbio, dtls_cfg->certfile) ||
855 !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL)) ||
856 !X509_digest(cert, EVP_sha1(), fingerprint, &size) ||
858 ast_log(LOG_ERROR, "Could not produce fingerprint from certificate '%s' for RTP instance '%p'\n",
859 dtls_cfg->certfile, instance);
860 BIO_free_all(certbio);
864 for (i = 0; i < size; i++) {
865 sprintf(local_fingerprint, "%.2X:", fingerprint[i]);
866 local_fingerprint += 3;
869 *(local_fingerprint-1) = 0;
871 BIO_free_all(certbio);
874 if (!ast_strlen_zero(dtls_cfg->cipher)) {
875 if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->cipher)) {
876 ast_log(LOG_ERROR, "Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
877 dtls_cfg->cipher, instance);
882 if (!ast_strlen_zero(dtls_cfg->cafile) || !ast_strlen_zero(dtls_cfg->capath)) {
883 if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx, S_OR(dtls_cfg->cafile, NULL), S_OR(dtls_cfg->capath, NULL))) {
884 ast_log(LOG_ERROR, "Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
885 S_OR(dtls_cfg->cafile, ""), S_OR(dtls_cfg->capath, ""), instance);
890 rtp->rekey = dtls_cfg->rekey;
891 rtp->dtls_setup = dtls_cfg->default_setup;
892 rtp->suite = dtls_cfg->suite;
894 if (!(rtp->ssl = SSL_new(rtp->ssl_ctx))) {
895 ast_log(LOG_ERROR, "Failed to allocate memory for SSL context on RTP instance '%p'\n",
900 SSL_set_ex_data(rtp->ssl, 0, rtp);
901 SSL_set_info_callback(rtp->ssl, dtls_info_callback);
903 if (!(rtp->read_bio = BIO_new(BIO_s_mem()))) {
904 ast_log(LOG_ERROR, "Failed to allocate memory for inbound SSL traffic on RTP instance '%p'\n",
908 BIO_set_mem_eof_return(rtp->read_bio, -1);
910 if (!(rtp->write_bio = BIO_new(BIO_s_mem()))) {
911 ast_log(LOG_ERROR, "Failed to allocate memory for outbound SSL traffic on RTP instance '%p'\n",
915 BIO_set_mem_eof_return(rtp->write_bio, -1);
917 SSL_set_bio(rtp->ssl, rtp->read_bio, rtp->write_bio);
919 if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
920 SSL_set_accept_state(rtp->ssl);
922 SSL_set_connect_state(rtp->ssl);
925 rtp->connection = AST_RTP_DTLS_CONNECTION_NEW;
931 BIO_free(rtp->read_bio);
932 rtp->read_bio = NULL;
935 if (rtp->write_bio) {
936 BIO_free(rtp->write_bio);
937 rtp->write_bio = NULL;
945 SSL_CTX_free(rtp->ssl_ctx);
951 static int ast_rtp_dtls_active(struct ast_rtp_instance *instance)
953 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
955 return !rtp->ssl_ctx ? 0 : 1;
958 static void ast_rtp_dtls_stop(struct ast_rtp_instance *instance)
960 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
963 SSL_CTX_free(rtp->ssl_ctx);
973 static void ast_rtp_dtls_reset(struct ast_rtp_instance *instance)
975 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
977 /* If the SSL session is not yet finalized don't bother resetting */
978 if (!SSL_is_init_finished(rtp->ssl)) {
982 SSL_shutdown(rtp->ssl);
983 rtp->connection = AST_RTP_DTLS_CONNECTION_NEW;
986 static enum ast_rtp_dtls_connection ast_rtp_dtls_get_connection(struct ast_rtp_instance *instance)
988 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
990 return rtp->connection;
993 static enum ast_rtp_dtls_setup ast_rtp_dtls_get_setup(struct ast_rtp_instance *instance)
995 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
997 return rtp->dtls_setup;
1000 static void ast_rtp_dtls_set_setup(struct ast_rtp_instance *instance, enum ast_rtp_dtls_setup setup)
1002 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1003 enum ast_rtp_dtls_setup old = rtp->dtls_setup;
1006 case AST_RTP_DTLS_SETUP_ACTIVE:
1007 rtp->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
1009 case AST_RTP_DTLS_SETUP_PASSIVE:
1010 rtp->dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
1012 case AST_RTP_DTLS_SETUP_ACTPASS:
1013 /* We can't respond to an actpass setup with actpass ourselves... so respond with active, as we can initiate connections */
1014 if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
1015 rtp->dtls_setup = AST_RTP_DTLS_SETUP_ACTIVE;
1018 case AST_RTP_DTLS_SETUP_HOLDCONN:
1019 rtp->dtls_setup = AST_RTP_DTLS_SETUP_HOLDCONN;
1022 /* This should never occur... if it does exit early as we don't know what state things are in */
1026 /* If the setup state did not change we go on as if nothing happened */
1027 if (old == rtp->dtls_setup) {
1031 /* If they don't want us to establish a connection wait until later */
1032 if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_HOLDCONN) {
1036 if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
1037 SSL_set_connect_state(rtp->ssl);
1038 } else if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_PASSIVE) {
1039 SSL_set_accept_state(rtp->ssl);
1045 static void ast_rtp_dtls_set_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash, const char *fingerprint)
1047 char *tmp = ast_strdupa(fingerprint), *value;
1049 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1051 if (hash != AST_RTP_DTLS_HASH_SHA1) {
1055 while ((value = strsep(&tmp, ":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
1056 sscanf(value, "%02x", (unsigned int*)&rtp->remote_fingerprint[pos++]);
1060 static const char *ast_rtp_dtls_get_fingerprint(struct ast_rtp_instance *instance, enum ast_rtp_dtls_hash hash)
1062 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1064 if (hash != AST_RTP_DTLS_HASH_SHA1) {
1068 return rtp->local_fingerprint;
1071 /* DTLS RTP Engine interface declaration */
1072 static struct ast_rtp_engine_dtls ast_rtp_dtls = {
1073 .set_configuration = ast_rtp_dtls_set_configuration,
1074 .active = ast_rtp_dtls_active,
1075 .stop = ast_rtp_dtls_stop,
1076 .reset = ast_rtp_dtls_reset,
1077 .get_connection = ast_rtp_dtls_get_connection,
1078 .get_setup = ast_rtp_dtls_get_setup,
1079 .set_setup = ast_rtp_dtls_set_setup,
1080 .set_fingerprint = ast_rtp_dtls_set_fingerprint,
1081 .get_fingerprint = ast_rtp_dtls_get_fingerprint,
1086 /* RTP Engine Declaration */
1087 static struct ast_rtp_engine asterisk_rtp_engine = {
1090 .destroy = ast_rtp_destroy,
1091 .dtmf_begin = ast_rtp_dtmf_begin,
1092 .dtmf_end = ast_rtp_dtmf_end,
1093 .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
1094 .dtmf_mode_set = ast_rtp_dtmf_mode_set,
1095 .dtmf_mode_get = ast_rtp_dtmf_mode_get,
1096 .update_source = ast_rtp_update_source,
1097 .change_source = ast_rtp_change_source,
1098 .write = ast_rtp_write,
1099 .read = ast_rtp_read,
1100 .prop_set = ast_rtp_prop_set,
1102 .remote_address_set = ast_rtp_remote_address_set,
1103 .red_init = rtp_red_init,
1104 .red_buffer = rtp_red_buffer,
1105 .local_bridge = ast_rtp_local_bridge,
1106 .get_stat = ast_rtp_get_stat,
1107 .dtmf_compatible = ast_rtp_dtmf_compatible,
1108 .stun_request = ast_rtp_stun_request,
1109 .stop = ast_rtp_stop,
1110 .qos = ast_rtp_qos_set,
1111 .sendcng = ast_rtp_sendcng,
1112 #ifdef HAVE_PJPROJECT
1113 .ice = &ast_rtp_ice,
1115 #ifdef HAVE_OPENSSL_SRTP
1116 .dtls = &ast_rtp_dtls,
1117 .activate = ast_rtp_activate,
1121 #ifdef HAVE_PJPROJECT
1122 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq);
1124 static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
1126 struct ast_rtp *rtp = ice->user_data;
1132 rtp->strict_rtp_state = STRICT_RTP_LEARN;
1133 rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
1136 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)
1138 struct ast_rtp *rtp = ice->user_data;
1140 /* 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
1142 rtp->passthrough = 1;
1145 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)
1147 struct ast_rtp *rtp = ice->user_data;
1148 pj_status_t status = PJ_EINVALIDOP;
1149 pj_ssize_t _size = (pj_ssize_t)size;
1151 if (transport_id == TRANSPORT_SOCKET_RTP) {
1152 /* Traffic is destined to go right out the RTP socket we already have */
1153 status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
1154 /* sendto on a connectionless socket should send all the data, or none at all */
1155 ast_assert(_size == size || status != PJ_SUCCESS);
1156 } else if (transport_id == TRANSPORT_SOCKET_RTCP) {
1157 /* Traffic is destined to go right out the RTCP socket we already have */
1159 status = pj_sock_sendto(rtp->rtcp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
1160 /* sendto on a connectionless socket should send all the data, or none at all */
1161 ast_assert(_size == size || status != PJ_SUCCESS);
1163 status = PJ_SUCCESS;
1165 } else if (transport_id == TRANSPORT_TURN_RTP) {
1166 /* Traffic is going through the RTP TURN relay */
1167 if (rtp->turn_rtp) {
1168 status = pj_turn_sock_sendto(rtp->turn_rtp, pkt, size, dst_addr, dst_addr_len);
1170 } else if (transport_id == TRANSPORT_TURN_RTCP) {
1171 /* Traffic is going through the RTCP TURN relay */
1172 if (rtp->turn_rtcp) {
1173 status = pj_turn_sock_sendto(rtp->turn_rtcp, pkt, size, dst_addr, dst_addr_len);
1180 /* ICE Session interface declaration */
1181 static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
1182 .on_ice_complete = ast_rtp_on_ice_complete,
1183 .on_rx_data = ast_rtp_on_ice_rx_data,
1184 .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
1187 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)
1189 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1190 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1191 struct ast_sockaddr dest = { { 0, }, };
1193 ast_rtp_instance_get_local_address(instance, &dest);
1195 ast_sendto(rtp->s, pkt, pkt_len, 0, &dest);
1198 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)
1200 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1201 struct ast_rtp *rtp = NULL;
1203 /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
1208 rtp = ast_rtp_instance_get_data(instance);
1210 /* If the TURN session is being destroyed we need to remove it from the RTP instance */
1211 if (new_state == PJ_TURN_STATE_DESTROYING) {
1212 rtp->turn_rtp = NULL;
1216 /* We store the new state so the other thread can actually handle it */
1217 ast_mutex_lock(&rtp->lock);
1218 rtp->turn_state = new_state;
1220 /* If this is a state that the main thread should be notified about do so */
1221 if (new_state == PJ_TURN_STATE_READY || new_state == PJ_TURN_STATE_DEALLOCATING || new_state == PJ_TURN_STATE_DEALLOCATED) {
1222 ast_cond_signal(&rtp->cond);
1225 ast_mutex_unlock(&rtp->lock);
1228 /* RTP TURN Socket interface declaration */
1229 static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
1230 .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
1231 .on_state = ast_rtp_on_turn_rtp_state,
1234 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)
1236 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1237 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1239 ast_sendto(rtp->rtcp->s, pkt, pkt_len, 0, &rtp->rtcp->us);
1242 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)
1244 struct ast_rtp_instance *instance = pj_turn_sock_get_user_data(turn_sock);
1245 struct ast_rtp *rtp = NULL;
1247 /* If this is a leftover from an already destroyed RTP instance just ignore the state change */
1252 rtp = ast_rtp_instance_get_data(instance);
1254 /* If the TURN session is being destroyed we need to remove it from the RTP instance */
1255 if (new_state == PJ_TURN_STATE_DESTROYING) {
1256 rtp->turn_rtcp = NULL;
1260 /* We store the new state so the other thread can actually handle it */
1261 ast_mutex_lock(&rtp->lock);
1262 rtp->turn_state = new_state;
1264 /* If this is a state that the main thread should be notified about do so */
1265 if (new_state == PJ_TURN_STATE_READY || new_state == PJ_TURN_STATE_DEALLOCATING || new_state == PJ_TURN_STATE_DEALLOCATED) {
1266 ast_cond_signal(&rtp->cond);
1269 ast_mutex_unlock(&rtp->lock);
1272 /* RTCP TURN Socket interface declaration */
1273 static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
1274 .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
1275 .on_state = ast_rtp_on_turn_rtcp_state,
1278 /*! \brief Worker thread for I/O queue and timerheap */
1279 static int ice_worker_thread(void *data)
1281 while (!worker_terminate) {
1282 const pj_time_val delay = {0, 10};
1284 pj_ioqueue_poll(ioqueue, &delay);
1286 pj_timer_heap_poll(timerheap, NULL);
1293 static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
1298 if (!ast_sockaddr_isnull(&rtpdebugaddr)) {
1300 return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
1302 return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
1309 static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
1314 if (!ast_sockaddr_isnull(&rtcpdebugaddr)) {
1315 if (rtcpdebugport) {
1316 return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
1318 return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
1325 #ifdef HAVE_OPENSSL_SRTP
1327 static int dtls_srtp_handle_timeout(const void *data)
1329 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
1330 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1337 ast_mutex_lock(&rtp->dtls_timer_lock);
1338 if (rtp->dtlstimerid == -1)
1340 ast_mutex_unlock(&rtp->dtls_timer_lock);
1341 ao2_ref(instance, -1);
1345 rtp->dtlstimerid = -1;
1346 ast_mutex_unlock(&rtp->dtls_timer_lock);
1349 DTLSv1_handle_timeout(rtp->ssl);
1352 dtls_srtp_check_pending(instance, rtp);
1354 ao2_ref(instance, -1);
1359 static void dtls_srtp_check_pending(struct ast_rtp_instance *instance, struct ast_rtp *rtp)
1361 size_t pending = BIO_ctrl_pending(rtp->write_bio);
1362 struct timeval dtls_timeout; /* timeout on DTLS */
1365 char outgoing[pending];
1367 struct ast_sockaddr remote_address = { {0, } };
1370 ast_rtp_instance_get_remote_address(instance, &remote_address);
1372 /* If we do not yet know an address to send this to defer it until we do */
1373 if (ast_sockaddr_isnull(&remote_address)) {
1377 out = BIO_read(rtp->write_bio, outgoing, sizeof(outgoing));
1379 /* Stop existing DTLS timer if running */
1380 ast_mutex_lock(&rtp->dtls_timer_lock);
1381 if (rtp->dtlstimerid > -1) {
1382 AST_SCHED_DEL_UNREF(rtp->sched, rtp->dtlstimerid, ao2_ref(instance, -1));
1383 rtp->dtlstimerid = -1;
1386 if (DTLSv1_get_timeout(rtp->ssl, &dtls_timeout)) {
1387 int timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
1388 ao2_ref(instance, +1);
1389 if ((rtp->dtlstimerid = ast_sched_add(rtp->sched, timeout, dtls_srtp_handle_timeout, instance)) < 0) {
1390 ao2_ref(instance, -1);
1391 ast_log(LOG_WARNING, "scheduling DTLS retransmission for RTP instance [%p] failed.\n", instance);
1394 ast_mutex_unlock(&rtp->dtls_timer_lock);
1396 __rtp_sendto(instance, outgoing, out, 0, &remote_address, 0, &ice, 0);
1400 static int dtls_srtp_renegotiate(const void *data)
1402 struct ast_rtp_instance *instance = (struct ast_rtp_instance *)data;
1403 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1405 SSL_renegotiate(rtp->ssl);
1406 SSL_do_handshake(rtp->ssl);
1407 dtls_srtp_check_pending(instance, rtp);
1410 ao2_ref(instance, -1);
1415 static int dtls_srtp_setup(struct ast_rtp *rtp, struct ast_srtp *srtp, struct ast_rtp_instance *instance)
1417 unsigned char material[SRTP_MASTER_LEN * 2];
1418 unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
1419 struct ast_srtp_policy *local_policy, *remote_policy = NULL;
1420 struct ast_rtp_instance_stats stats = { 0, };
1422 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
1423 if (SSL_CTX_get_verify_mode(rtp->ssl_ctx) != SSL_VERIFY_NONE) {
1426 if (!(certificate = SSL_get_peer_certificate(rtp->ssl))) {
1427 ast_log(LOG_WARNING, "No certificate was provided by the peer on RTP instance '%p'\n", instance);
1431 /* If a fingerprint is present in the SDP make sure that the peer certificate matches it */
1432 if (rtp->remote_fingerprint[0]) {
1433 unsigned char fingerprint[EVP_MAX_MD_SIZE];
1436 if (!X509_digest(certificate, EVP_sha1(), fingerprint, &size) ||
1438 memcmp(fingerprint, rtp->remote_fingerprint, size)) {
1439 X509_free(certificate);
1440 ast_log(LOG_WARNING, "Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
1446 X509_free(certificate);
1449 /* Ensure that certificate verification was successful */
1450 if (SSL_get_verify_result(rtp->ssl) != X509_V_OK) {
1451 ast_log(LOG_WARNING, "Peer certificate on RTP instance '%p' failed verification test\n",
1456 /* Produce key information and set up SRTP */
1457 if (!SSL_export_keying_material(rtp->ssl, material, SRTP_MASTER_LEN * 2, "EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
1458 ast_log(LOG_WARNING, "Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
1463 /* Whether we are acting as a server or client determines where the keys/salts are */
1464 if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_ACTIVE) {
1465 local_key = material;
1466 remote_key = local_key + SRTP_MASTER_KEY_LEN;
1467 local_salt = remote_key + SRTP_MASTER_KEY_LEN;
1468 remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
1470 remote_key = material;
1471 local_key = remote_key + SRTP_MASTER_KEY_LEN;
1472 remote_salt = local_key + SRTP_MASTER_KEY_LEN;
1473 local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
1476 if (!(local_policy = res_srtp_policy->alloc())) {
1480 if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
1481 ast_log(LOG_WARNING, "Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
1485 if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
1486 ast_log(LOG_WARNING, "Could not set suite to '%d' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
1490 if (ast_rtp_instance_get_stats(instance, &stats, AST_RTP_INSTANCE_STAT_LOCAL_SSRC)) {
1494 res_srtp_policy->set_ssrc(local_policy, stats.local_ssrc, 0);
1496 if (!(remote_policy = res_srtp_policy->alloc())) {
1500 if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
1501 ast_log(LOG_WARNING, "Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
1505 if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
1506 ast_log(LOG_WARNING, "Could not set suite to '%d' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
1510 res_srtp_policy->set_ssrc(remote_policy, 0, 1);
1512 if (ast_rtp_instance_add_srtp_policy(instance, remote_policy, local_policy)) {
1513 ast_log(LOG_WARNING, "Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
1518 ao2_ref(instance, +1);
1519 if ((rtp->rekeyid = ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
1520 ao2_ref(instance, -1);
1528 res_srtp_policy->destroy(local_policy);
1530 if (remote_policy) {
1531 res_srtp_policy->destroy(remote_policy);
1538 static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
1541 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1542 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
1545 if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
1549 #ifdef HAVE_OPENSSL_SRTP
1551 dtls_srtp_check_pending(instance, rtp);
1553 /* If this is an SSL packet pass it to OpenSSL for processing */
1554 if ((*in >= 20) && (*in <= 64)) {
1557 /* If no SSL session actually exists terminate things */
1559 ast_log(LOG_ERROR, "Received SSL traffic on RTP instance '%p' without an SSL session\n",
1564 /* If we don't yet know if we are active or passive and we receive a packet... we are obviously passive */
1565 if (rtp->dtls_setup == AST_RTP_DTLS_SETUP_ACTPASS) {
1566 rtp->dtls_setup = AST_RTP_DTLS_SETUP_PASSIVE;
1567 SSL_set_accept_state(rtp->ssl);
1570 dtls_srtp_check_pending(instance, rtp);
1572 BIO_write(rtp->read_bio, buf, len);
1574 len = SSL_read(rtp->ssl, buf, len);
1576 dtls_srtp_check_pending(instance, rtp);
1578 if (rtp->dtls_failure) {
1579 ast_log(LOG_ERROR, "DTLS failure occurred on RTP instance '%p', terminating\n",
1584 if (SSL_is_init_finished(rtp->ssl)) {
1585 /* Any further connections will be existing since this is now established */
1586 rtp->connection = AST_RTP_DTLS_CONNECTION_EXISTING;
1588 /* Use the keying material to set up key/salt information */
1589 res = dtls_srtp_setup(rtp, srtp, instance);
1597 #ifdef HAVE_PJPROJECT
1599 pj_str_t combined = pj_str(ast_sockaddr_stringify(sa));
1600 pj_sockaddr address;
1603 pj_thread_register_check();
1605 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
1607 status = pj_ice_sess_on_rx_pkt(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP,
1608 rtcp ? TRANSPORT_SOCKET_RTCP : TRANSPORT_SOCKET_RTP, buf, len, &address,
1609 pj_sockaddr_get_len(&address));
1610 if (status != PJ_SUCCESS) {
1613 pj_strerror(status, buf, sizeof(buf));
1614 ast_log(LOG_WARNING, "PJ ICE Rx error status code: %d '%s'.\n",
1618 if (!rtp->passthrough) {
1621 rtp->passthrough = 0;
1625 if ((*in & 0xC0) && res_srtp && srtp && res_srtp->unprotect(srtp, buf, &len, rtcp) < 0) {
1632 static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
1634 return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
1637 static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
1639 return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
1642 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)
1646 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1647 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
1651 if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
1655 #ifdef HAVE_PJPROJECT
1657 pj_thread_register_check();
1659 if (pj_ice_sess_send_data(rtp->ice, rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP, temp, len) == PJ_SUCCESS) {
1666 return ast_sendto(rtcp ? rtp->rtcp->s : rtp->s, temp, len, flags, sa);
1669 static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
1671 return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
1674 static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
1676 return __rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1);
1679 static int rtp_get_rate(struct ast_format *format)
1681 return (format->id == AST_FORMAT_G722) ? 8000 : ast_format_rate(format);
1684 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
1686 unsigned int interval;
1687 /*! \todo XXX Do a more reasonable calculation on this one
1688 * Look in RFC 3550 Section A.7 for an example*/
1689 interval = rtcpinterval;
1693 /*! \brief Calculate normal deviation */
1694 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
1696 normdev = normdev * sample_count + sample;
1699 return normdev / sample_count;
1702 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
1705 for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
1706 return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
1707 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
1710 #define SQUARE(x) ((x) * (x))
1712 stddev = sample_count * stddev;
1716 ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
1717 ( SQUARE(sample - normdev_curent) / sample_count );
1722 static int create_new_socket(const char *type, int af)
1724 int sock = socket(af, SOCK_DGRAM, 0);
1730 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
1732 long flags = fcntl(sock, F_GETFL);
1733 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
1736 setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
1746 * \brief Initializes sequence values and probation for learning mode.
1747 * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
1749 * \param info The learning information to track
1750 * \param seq sequence number read from the rtp header to initialize the information with
1752 static void rtp_learning_seq_init(struct rtp_learning_info *info, uint16_t seq)
1754 info->max_seq = seq - 1;
1755 info->packets = learning_min_sequential;
1760 * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
1761 * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
1763 * \param info Structure tracking the learning progress of some address
1764 * \param seq sequence number read from the rtp header
1765 * \retval 0 if probation mode should exit for this address
1766 * \retval non-zero if probation mode should continue
1768 static int rtp_learning_rtp_seq_update(struct rtp_learning_info *info, uint16_t seq)
1770 if (seq == info->max_seq + 1) {
1771 /* packet is in sequence */
1774 /* Sequence discontinuity; reset */
1775 info->packets = learning_min_sequential - 1;
1777 info->max_seq = seq;
1779 return (info->packets == 0);
1782 #ifdef HAVE_PJPROJECT
1783 static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component,
1784 int transport, const pj_turn_sock_cb *turn_cb, pj_turn_sock **turn_sock)
1786 pj_sockaddr address[16];
1787 unsigned int count = PJ_ARRAY_SIZE(address), pos = 0;
1789 /* Add all the local interface IP addresses */
1790 if (ast_sockaddr_is_ipv4(addr)) {
1791 pj_enum_ip_interface(pj_AF_INET(), &count, address);
1792 } else if (ast_sockaddr_is_any(addr)) {
1793 pj_enum_ip_interface(pj_AF_UNSPEC(), &count, address);
1795 pj_enum_ip_interface(pj_AF_INET6(), &count, address);
1798 for (pos = 0; pos < count; pos++) {
1799 pj_sockaddr_set_port(&address[pos], port);
1800 ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_HOST, 65535, &address[pos], &address[pos], NULL,
1801 pj_sockaddr_get_len(&address[pos]));
1804 /* If configured to use a STUN server to get our external mapped address do so */
1805 if (stunaddr.sin_addr.s_addr && ast_sockaddr_is_ipv4(addr) && count) {
1806 struct sockaddr_in answer;
1808 if (!ast_stun_request(component == AST_RTP_ICE_COMPONENT_RTCP ? rtp->rtcp->s : rtp->s, &stunaddr, NULL, &answer)) {
1810 pj_str_t mapped = pj_str(ast_strdupa(ast_inet_ntoa(answer.sin_addr)));
1812 /* Use the first local host candidate as the base */
1813 pj_sockaddr_cp(&base, &address[0]);
1815 pj_sockaddr_init(pj_AF_INET(), &address[0], &mapped, ntohs(answer.sin_port));
1817 ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_SRFLX, 65535, &address[0], &base,
1818 NULL, pj_sockaddr_get_len(&address[0]));
1822 /* If configured to use a TURN relay create a session and allocate */
1823 if (pj_strlen(&turnaddr) && pj_turn_sock_create(&rtp->ice->stun_cfg, ast_sockaddr_is_ipv4(addr) ? pj_AF_INET() : pj_AF_INET6(), PJ_TURN_TP_TCP,
1824 turn_cb, NULL, instance, turn_sock) == PJ_SUCCESS) {
1825 pj_stun_auth_cred cred = { 0, };
1826 struct timeval wait = ast_tvadd(ast_tvnow(), ast_samp2tv(TURN_ALLOCATION_WAIT_TIME, 1000));
1827 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1829 cred.type = PJ_STUN_AUTH_CRED_STATIC;
1830 cred.data.static_cred.username = turnusername;
1831 cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
1832 cred.data.static_cred.data = turnpassword;
1834 /* Because the TURN socket is asynchronous but we are synchronous we need to wait until it is done */
1835 ast_mutex_lock(&rtp->lock);
1836 pj_turn_sock_alloc(*turn_sock, &turnaddr, turnport, NULL, &cred, NULL);
1837 ast_cond_timedwait(&rtp->cond, &rtp->lock, &ts);
1838 ast_mutex_unlock(&rtp->lock);
1840 /* If a TURN session was allocated add it as a candidate */
1841 if (rtp->turn_state == PJ_TURN_STATE_READY) {
1842 pj_turn_session_info info;
1844 pj_turn_sock_get_info(*turn_sock, &info);
1846 if (transport == TRANSPORT_SOCKET_RTP) {
1847 transport = TRANSPORT_TURN_RTP;
1848 } else if (transport == TRANSPORT_SOCKET_RTCP) {
1849 transport = TRANSPORT_TURN_RTCP;
1852 ast_rtp_ice_add_cand(rtp, component, transport, PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr, &info.relay_addr,
1853 NULL, pj_sockaddr_get_len(&info.relay_addr));
1861 * \brief Calculates the elapsed time from issue of the first tx packet in an
1862 * rtp session and a specified time
1864 * \param rtp pointer to the rtp struct with the transmitted rtp packet
1865 * \param delivery time of delivery - if NULL or zero value, will be ast_tvnow()
1867 * \return time elapsed in milliseconds
1869 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1874 if (ast_tvzero(rtp->txcore)) {
1875 rtp->txcore = ast_tvnow();
1876 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1879 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
1880 if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
1885 return (unsigned int) ms;
1888 #ifdef HAVE_PJPROJECT
1891 * \brief Creates an ICE session. Can be used to replace a destroyed ICE session.
1893 * \param instance RTP instance for which the ICE session is being replaced
1894 * \param addr ast_sockaddr to use for adding RTP candidates to the ICE session
1895 * \param port port to use for adding RTP candidates to the ICE session
1896 * \param replace 0 when creating a new session, 1 when replacing a destroyed session
1898 * \retval 0 on success
1899 * \retval -1 on failure
1901 static int ice_create(struct ast_rtp_instance *instance, struct ast_sockaddr *addr,
1902 int port, int replace)
1904 pj_stun_config stun_config;
1905 pj_str_t ufrag, passwd;
1906 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1908 ao2_cleanup(rtp->ice_local_candidates);
1909 rtp->ice_local_candidates = NULL;
1911 pj_thread_register_check();
1913 pj_stun_config_init(&stun_config, &cachingpool.factory, 0, ioqueue, timerheap);
1915 ufrag = pj_str(rtp->local_ufrag);
1916 passwd = pj_str(rtp->local_passwd);
1918 /* Create an ICE session for ICE negotiation */
1919 if (pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN, 2,
1920 &ast_rtp_ice_sess_cb, &ufrag, &passwd, NULL, &rtp->ice) == PJ_SUCCESS) {
1921 /* Make this available for the callbacks */
1922 rtp->ice->user_data = rtp;
1924 /* Add all of the available candidates to the ICE session */
1925 rtp_add_candidates_to_ice(instance, rtp, addr, port, AST_RTP_ICE_COMPONENT_RTP,
1926 TRANSPORT_SOCKET_RTP, &ast_rtp_turn_rtp_sock_cb, &rtp->turn_rtp);
1928 /* Only add the RTCP candidates to ICE when replacing the session. New sessions
1929 * handle this in a separate part of the setup phase */
1930 if (replace && rtp->rtcp) {
1931 rtp_add_candidates_to_ice(instance, rtp, &rtp->rtcp->us,
1932 ast_sockaddr_port(&rtp->rtcp->us), AST_RTP_ICE_COMPONENT_RTCP,
1933 TRANSPORT_SOCKET_RTCP, &ast_rtp_turn_rtcp_sock_cb, &rtp->turn_rtcp);
1944 static int ast_rtp_new(struct ast_rtp_instance *instance,
1945 struct ast_sched_context *sched, struct ast_sockaddr *addr,
1948 struct ast_rtp *rtp = NULL;
1951 /* Create a new RTP structure to hold all of our data */
1952 if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
1956 /* Initialize synchronization aspects */
1957 ast_mutex_init(&rtp->lock);
1958 ast_cond_init(&rtp->cond, NULL);
1960 /* Set default parameters on the newly created RTP structure */
1961 rtp->ssrc = ast_random();
1962 rtp->seqno = ast_random() & 0xffff;
1963 rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
1965 rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t)rtp->seqno);
1966 rtp_learning_seq_init(&rtp->alt_source_learn, (uint16_t)rtp->seqno);
1969 /* Create a new socket for us to listen on and use */
1971 create_new_socket("RTP",
1972 ast_sockaddr_is_ipv4(addr) ? AF_INET :
1973 ast_sockaddr_is_ipv6(addr) ? AF_INET6 : -1)) < 0) {
1974 ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
1979 /* Now actually find a free RTP port to use */
1980 x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
1985 ast_sockaddr_set_port(addr, x);
1986 /* Try to bind, this will tell us whether the port is available or not */
1987 if (!ast_bind(rtp->s, addr)) {
1988 ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
1989 ast_rtp_instance_set_local_address(instance, addr);
1995 x = (rtpstart + 1) & ~1;
1998 /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
1999 if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
2000 ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
2007 #ifdef HAVE_PJPROJECT
2008 generate_random_string(rtp->local_ufrag, sizeof(rtp->local_ufrag));
2009 generate_random_string(rtp->local_passwd, sizeof(rtp->local_passwd));
2011 ast_rtp_instance_set_data(instance, rtp);
2012 #ifdef HAVE_PJPROJECT
2013 /* Create an ICE session for ICE negotiation */
2015 if (ice_create(instance, addr, x, 0)) {
2016 ast_log(LOG_NOTICE, "Failed to start ICE session\n");
2019 ast_sockaddr_copy(&rtp->ice_original_rtp_addr, addr);
2024 /* Record any information we may need */
2027 #ifdef HAVE_OPENSSL_SRTP
2029 rtp->dtlstimerid = -1;
2035 static int ast_rtp_destroy(struct ast_rtp_instance *instance)
2037 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2039 /* Destroy the smoother that was smoothing out audio if present */
2040 if (rtp->smoother) {
2041 ast_smoother_free(rtp->smoother);
2044 /* Close our own socket so we no longer get packets */
2049 /* Destroy RTCP if it was being used */
2052 * It is not possible for there to be an active RTCP scheduler
2053 * entry at this point since it holds a reference to the
2054 * RTP instance while it's active.
2056 close(rtp->rtcp->s);
2057 ast_free(rtp->rtcp);
2060 /* Destroy RED if it was being used */
2062 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
2066 #ifdef HAVE_PJPROJECT
2067 pj_thread_register_check();
2069 /* Destroy the ICE session if being used */
2071 pj_ice_sess_destroy(rtp->ice);
2074 /* Destroy the RTP TURN relay if being used */
2075 if (rtp->turn_rtp) {
2076 pj_turn_sock_set_user_data(rtp->turn_rtp, NULL);
2077 pj_turn_sock_destroy(rtp->turn_rtp);
2080 /* Destroy the RTCP TURN relay if being used */
2081 if (rtp->turn_rtcp) {
2082 pj_turn_sock_set_user_data(rtp->turn_rtcp, NULL);
2083 pj_turn_sock_destroy(rtp->turn_rtcp);
2086 /* Destroy any candidates */
2087 if (rtp->ice_local_candidates) {
2088 ao2_ref(rtp->ice_local_candidates, -1);
2091 if (rtp->ice_active_remote_candidates) {
2092 ao2_ref(rtp->ice_active_remote_candidates, -1);
2096 #ifdef HAVE_OPENSSL_SRTP
2097 /* Destroy the SSL context if present */
2099 SSL_CTX_free(rtp->ssl_ctx);
2102 /* Destroy the SSL session if present */
2108 /* Destroy synchronization items */
2109 ast_mutex_destroy(&rtp->lock);
2110 ast_cond_destroy(&rtp->cond);
2112 /* Finally destroy ourselves */
2118 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
2120 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2121 rtp->dtmfmode = dtmf_mode;
2125 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
2127 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2128 return rtp->dtmfmode;
2131 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
2133 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2134 struct ast_sockaddr remote_address = { {0,} };
2135 int hdrlen = 12, res = 0, i = 0, payload = 101;
2137 unsigned int *rtpheader = (unsigned int*)data;
2139 ast_rtp_instance_get_remote_address(instance, &remote_address);
2141 /* If we have no remote address information bail out now */
2142 if (ast_sockaddr_isnull(&remote_address)) {
2146 /* Convert given digit into what we want to transmit */
2147 if ((digit <= '9') && (digit >= '0')) {
2149 } else if (digit == '*') {
2151 } else if (digit == '#') {
2153 } else if ((digit >= 'A') && (digit <= 'D')) {
2154 digit = digit - 'A' + 12;
2155 } else if ((digit >= 'a') && (digit <= 'd')) {
2156 digit = digit - 'a' + 12;
2158 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2162 /* Grab the payload that they expect the RFC2833 packet to be received in */
2163 payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_DTMF);
2165 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2166 rtp->send_duration = 160;
2167 rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2168 rtp->lastdigitts = rtp->lastts + rtp->send_duration;
2170 /* Create the actual packet that we will be sending */
2171 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2172 rtpheader[1] = htonl(rtp->lastdigitts);
2173 rtpheader[2] = htonl(rtp->ssrc);
2175 /* Actually send the packet */
2176 for (i = 0; i < 2; i++) {
2179 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2180 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2182 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2183 ast_sockaddr_stringify(&remote_address),
2186 update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
2187 if (rtp_debug_test_addr(&remote_address)) {
2188 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2189 ast_sockaddr_stringify(&remote_address),
2190 ice ? " (via ICE)" : "",
2191 payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2194 rtp->send_duration += 160;
2195 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2198 /* Record that we are in the process of sending a digit and information needed to continue doing so */
2199 rtp->sending_digit = 1;
2200 rtp->send_digit = digit;
2201 rtp->send_payload = payload;
2206 static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
2208 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2209 struct ast_sockaddr remote_address = { {0,} };
2210 int hdrlen = 12, res = 0;
2212 unsigned int *rtpheader = (unsigned int*)data;
2215 ast_rtp_instance_get_remote_address(instance, &remote_address);
2217 /* Make sure we know where the other side is so we can send them the packet */
2218 if (ast_sockaddr_isnull(&remote_address)) {
2222 /* Actually create the packet we will be sending */
2223 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2224 rtpheader[1] = htonl(rtp->lastdigitts);
2225 rtpheader[2] = htonl(rtp->ssrc);
2226 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2228 /* Boom, send it on out */
2229 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2231 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2232 ast_sockaddr_stringify(&remote_address),
2236 update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
2238 if (rtp_debug_test_addr(&remote_address)) {
2239 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2240 ast_sockaddr_stringify(&remote_address),
2241 ice ? " (via ICE)" : "",
2242 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2245 /* And now we increment some values for the next time we swing by */
2247 rtp->send_duration += 160;
2248 rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2253 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
2255 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2256 struct ast_sockaddr remote_address = { {0,} };
2257 int hdrlen = 12, res = -1, i = 0;
2259 unsigned int *rtpheader = (unsigned int*)data;
2260 unsigned int measured_samples;
2262 ast_rtp_instance_get_remote_address(instance, &remote_address);
2264 /* Make sure we know where the remote side is so we can send them the packet we construct */
2265 if (ast_sockaddr_isnull(&remote_address)) {
2269 /* Convert the given digit to the one we are going to send */
2270 if ((digit <= '9') && (digit >= '0')) {
2272 } else if (digit == '*') {
2274 } else if (digit == '#') {
2276 } else if ((digit >= 'A') && (digit <= 'D')) {
2277 digit = digit - 'A' + 12;
2278 } else if ((digit >= 'a') && (digit <= 'd')) {
2279 digit = digit - 'a' + 12;
2281 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2285 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2287 if (duration > 0 && (measured_samples = duration * rtp_get_rate(&rtp->f.subclass.format) / 1000) > rtp->send_duration) {
2288 ast_debug(2, "Adjusting final end duration from %u to %u\n", rtp->send_duration, measured_samples);
2289 rtp->send_duration = measured_samples;
2292 /* Construct the packet we are going to send */
2293 rtpheader[1] = htonl(rtp->lastdigitts);
2294 rtpheader[2] = htonl(rtp->ssrc);
2295 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2296 rtpheader[3] |= htonl((1 << 23));
2298 /* Send it 3 times, that's the magical number */
2299 for (i = 0; i < 3; i++) {
2302 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2304 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
2307 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
2308 ast_sockaddr_stringify(&remote_address),
2312 update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
2314 if (rtp_debug_test_addr(&remote_address)) {
2315 ast_verbose("Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2316 ast_sockaddr_stringify(&remote_address),
2317 ice ? " (via ICE)" : "",
2318 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2325 /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
2326 rtp->lastts += calc_txstamp(rtp, NULL) * DTMF_SAMPLE_RATE_MS;
2328 rtp->sending_digit = 0;
2329 rtp->send_digit = 0;
2334 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
2336 return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
2339 static void ast_rtp_update_source(struct ast_rtp_instance *instance)
2341 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2343 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
2344 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2345 ast_debug(3, "Setting the marker bit due to a source update\n");
2350 static void ast_rtp_change_source(struct ast_rtp_instance *instance)
2352 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2353 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
2354 unsigned int ssrc = ast_random();
2357 ast_debug(3, "Not changing SSRC since we haven't sent any RTP yet\n");
2361 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
2362 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2364 ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
2367 ast_debug(3, "Changing ssrc for SRTP from %u to %u\n", rtp->ssrc, ssrc);
2368 res_srtp->change_source(srtp, rtp->ssrc, ssrc);
2376 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
2378 unsigned int sec, usec, frac;
2379 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
2381 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
2386 static void ntp2timeval(unsigned int msw, unsigned int lsw, struct timeval *tv)
2388 tv->tv_sec = msw - 2208988800u;
2389 tv->tv_usec = ((lsw << 6) / 3650) - (lsw >> 12) - (lsw >> 8);
2392 static void calculate_lost_packet_statistics(struct ast_rtp *rtp,
2393 unsigned int *lost_packets,
2396 unsigned int extended_seq_no;
2397 unsigned int expected_packets;
2398 unsigned int expected_interval;
2399 unsigned int received_interval;
2400 double rxlost_current;
2403 /* Compute statistics */
2404 extended_seq_no = rtp->cycles + rtp->lastrxseqno;
2405 expected_packets = extended_seq_no - rtp->seedrxseqno + 1;
2406 if (rtp->rxcount > expected_packets) {
2407 expected_packets += rtp->rxcount - expected_packets;
2409 *lost_packets = expected_packets - rtp->rxcount;
2410 expected_interval = expected_packets - rtp->rtcp->expected_prior;
2411 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2412 lost_interval = expected_interval - received_interval;
2413 if (expected_interval == 0 || lost_interval <= 0) {
2416 *fraction_lost = (lost_interval << 8) / expected_interval;
2419 /* Update RTCP statistics */
2420 rtp->rtcp->received_prior = rtp->rxcount;
2421 rtp->rtcp->expected_prior = expected_packets;
2422 if (lost_interval <= 0) {
2423 rtp->rtcp->rxlost = 0;
2425 rtp->rtcp->rxlost = lost_interval;
2427 if (rtp->rtcp->rxlost_count == 0) {
2428 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
2430 if (lost_interval < rtp->rtcp->minrxlost) {
2431 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
2433 if (lost_interval > rtp->rtcp->maxrxlost) {
2434 rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
2436 rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost,
2438 rtp->rtcp->rxlost_count);
2439 rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost,
2441 rtp->rtcp->normdev_rxlost,
2443 rtp->rtcp->rxlost_count);
2444 rtp->rtcp->normdev_rxlost = rxlost_current;
2445 rtp->rtcp->rxlost_count++;
2448 /*! \brief Send RTCP SR or RR report */
2449 static int ast_rtcp_write_report(struct ast_rtp_instance *instance, int sr)
2451 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2452 RAII_VAR(struct ast_json *, message_blob, NULL, ast_json_unref);
2456 unsigned int now_lsw;
2457 unsigned int now_msw;
2458 unsigned int *rtcpheader;
2459 unsigned int lost_packets;
2461 struct timeval dlsr = { 0, };
2463 int rate = rtp_get_rate(&rtp->f.subclass.format);
2465 int header_offset = 0;
2466 struct ast_sockaddr remote_address = { {0,} };
2467 struct ast_rtp_rtcp_report_block *report_block;
2468 RAII_VAR(struct ast_rtp_rtcp_report *, rtcp_report,
2469 ast_rtp_rtcp_report_alloc(1),
2472 if (!rtp || !rtp->rtcp) {
2476 if (ast_sockaddr_isnull(&rtp->rtcp->them)) { /* This'll stop rtcp for this rtp session */
2477 /* RTCP was stopped. */
2485 report_block = ast_calloc(1, sizeof(*report_block));
2486 if (!report_block) {
2490 /* Compute statistics */
2491 calculate_lost_packet_statistics(rtp, &lost_packets, &fraction_lost);
2493 gettimeofday(&now, NULL);
2494 rtcp_report->reception_report_count = 1;
2495 rtcp_report->ssrc = rtp->ssrc;
2496 rtcp_report->type = sr ? RTCP_PT_SR : RTCP_PT_RR;
2498 rtcp_report->sender_information.ntp_timestamp = now;
2499 rtcp_report->sender_information.rtp_timestamp = rtp->lastts;
2500 rtcp_report->sender_information.packet_count = rtp->txcount;
2501 rtcp_report->sender_information.octet_count = rtp->txoctetcount;
2503 rtcp_report->report_block[0] = report_block;
2504 report_block->source_ssrc = rtp->themssrc;
2505 report_block->lost_count.fraction = (fraction_lost & 0xff);
2506 report_block->lost_count.packets = (lost_packets & 0xffffff);
2507 report_block->highest_seq_no = (rtp->cycles | (rtp->lastrxseqno & 0xffff));
2508 report_block->ia_jitter = (unsigned int)(rtp->rxjitter * rate);
2509 report_block->lsr = rtp->rtcp->themrxlsr;
2510 /* If we haven't received an SR report, DLSR should be 0 */
2511 if (!ast_tvzero(rtp->rtcp->rxlsr)) {
2512 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2513 report_block->dlsr = (((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000;
2515 timeval2ntp(rtcp_report->sender_information.ntp_timestamp, &now_msw, &now_lsw);
2516 rtcpheader = (unsigned int *)bdata;
2517 rtcpheader[1] = htonl(rtcp_report->ssrc); /* Our SSRC */
2521 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
2522 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
2523 rtcpheader[4] = htonl(rtcp_report->sender_information.rtp_timestamp);
2524 rtcpheader[5] = htonl(rtcp_report->sender_information.packet_count);
2525 rtcpheader[6] = htonl(rtcp_report->sender_information.octet_count);
2528 rtcpheader[2 + header_offset] = htonl(report_block->source_ssrc); /* Their SSRC */
2529 rtcpheader[3 + header_offset] = htonl((report_block->lost_count.fraction << 24) | report_block->lost_count.packets);
2530 rtcpheader[4 + header_offset] = htonl(report_block->highest_seq_no);
2531 rtcpheader[5 + header_offset] = htonl(report_block->ia_jitter);
2532 rtcpheader[6 + header_offset] = htonl(report_block->lsr);
2533 rtcpheader[7 + header_offset] = htonl(report_block->dlsr);
2535 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | ((sr ? RTCP_PT_SR : RTCP_PT_RR) << 16) | ((len/4)-1));
2537 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2538 /* it can change mid call, and SDES can't) */
2539 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2540 rtcpheader[(len/4)+1] = htonl(rtcp_report->ssrc);
2541 rtcpheader[(len/4)+2] = htonl(0x01 << 24);
2544 ast_sockaddr_copy(&remote_address, &rtp->rtcp->them);
2545 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &remote_address, &ice);
2547 ast_log(LOG_ERROR, "RTCP %s transmission error to %s, rtcp halted %s\n",
2549 ast_sockaddr_stringify(&rtp->rtcp->them),
2554 /* Update RTCP SR/RR statistics */
2556 rtp->rtcp->txlsr = rtcp_report->sender_information.ntp_timestamp;
2557 rtp->rtcp->sr_count++;
2558 rtp->rtcp->lastsrtxcount = rtp->txcount;
2560 rtp->rtcp->rr_count++;
2563 update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTCP, &remote_address);
2565 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2566 ast_verbose("* Sent RTCP %s to %s%s\n", sr ? "SR" : "RR",
2567 ast_sockaddr_stringify(&remote_address), ice ? " (via ICE)" : "");
2568 ast_verbose(" Our SSRC: %u\n", rtcp_report->ssrc);
2570 ast_verbose(" Sent(NTP): %u.%010u\n",
2571 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
2572 (unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec * 4096);
2573 ast_verbose(" Sent(RTP): %u\n", rtcp_report->sender_information.rtp_timestamp);
2574 ast_verbose(" Sent packets: %u\n", rtcp_report->sender_information.packet_count);
2575 ast_verbose(" Sent octets: %u\n", rtcp_report->sender_information.octet_count);
2577 ast_verbose(" Report block:\n");
2578 ast_verbose(" Their SSRC: %u\n", report_block->source_ssrc);
2579 ast_verbose(" Fraction lost: %u\n", report_block->lost_count.fraction);
2580 ast_verbose(" Cumulative loss: %u\n", report_block->lost_count.packets);
2581 ast_verbose(" Highest seq no: %u\n", report_block->highest_seq_no);
2582 ast_verbose(" IA jitter: %.4f\n", (double)report_block->ia_jitter / rate);
2583 ast_verbose(" Their last SR: %u\n", report_block->lsr);
2584 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(report_block->dlsr / 65536.0));
2587 message_blob = ast_json_pack("{s: s}",
2588 "to", ast_sockaddr_stringify(&remote_address));
2589 ast_rtp_publish_rtcp_message(instance, ast_rtp_rtcp_sent_type(),
2595 /*! \brief Write and RTCP packet to the far end
2596 * \note Decide if we are going to send an SR (with Reception Block) or RR
2597 * RR is sent if we have not sent any rtp packets in the previous interval */
2598 static int ast_rtcp_write(const void *data)
2600 struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
2601 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2604 if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
2605 ao2_ref(instance, -1);
2609 if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
2611 res = ast_rtcp_write_report(instance, 1);
2614 res = ast_rtcp_write_report(instance, 0);
2619 * Not being rescheduled.
2621 ao2_ref(instance, -1);
2622 rtp->rtcp->schedid = -1;
2628 static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
2630 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2632 unsigned int ms = calc_txstamp(rtp, &frame->delivery);
2633 struct ast_sockaddr remote_address = { {0,} };
2634 int rate = rtp_get_rate(&frame->subclass.format) / 1000;
2636 if (frame->subclass.format.id == AST_FORMAT_G722) {
2637 frame->samples /= 2;
2640 if (rtp->sending_digit) {
2644 if (frame->frametype == AST_FRAME_VOICE) {
2645 pred = rtp->lastts + frame->samples;
2647 /* Re-calculate last TS */
2648 rtp->lastts = rtp->lastts + ms * rate;
2649 if (ast_tvzero(frame->delivery)) {
2650 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
2651 and if so, go with our prediction */
2652 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
2655 ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2659 } else if (frame->frametype == AST_FRAME_VIDEO) {
2660 mark = ast_format_get_video_mark(&frame->subclass.format);
2661 pred = rtp->lastovidtimestamp + frame->samples;
2662 /* Re-calculate last TS */
2663 rtp->lastts = rtp->lastts + ms * 90;
2664 /* If it's close to our prediction, go for it */
2665 if (ast_tvzero(frame->delivery)) {
2666 if (abs(rtp->lastts - pred) < 7200) {
2668 rtp->lastovidtimestamp += frame->samples;
2670 ast_debug(3, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
2671 rtp->lastovidtimestamp = rtp->lastts;
2675 pred = rtp->lastotexttimestamp + frame->samples;
2676 /* Re-calculate last TS */
2677 rtp->lastts = rtp->lastts + ms;
2678 /* If it's close to our prediction, go for it */
2679 if (ast_tvzero(frame->delivery)) {
2680 if (abs(rtp->lastts - pred) < 7200) {
2682 rtp->lastotexttimestamp += frame->samples;
2684 ast_debug(3, "Difference is %d, ms is %d, pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
2685 rtp->lastotexttimestamp = rtp->lastts;
2690 /* If we have been explicitly told to set the marker bit then do so */
2691 if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
2693 ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
2696 /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
2697 if (rtp->lastts > rtp->lastdigitts) {
2698 rtp->lastdigitts = rtp->lastts;
2701 if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
2702 rtp->lastts = frame->ts * rate;
2705 ast_rtp_instance_get_remote_address(instance, &remote_address);
2707 /* If we know the remote address construct a packet and send it out */
2708 if (!ast_sockaddr_isnull(&remote_address)) {
2709 int hdrlen = 12, res, ice;
2710 unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
2712 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
2713 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
2714 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
2716 if ((res = rtp_sendto(instance, (void *)rtpheader, frame->datalen + hdrlen, 0, &remote_address, &ice)) < 0) {
2717 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))) {
2718 ast_debug(1, "RTP Transmission error of packet %d to %s: %s\n",
2720 ast_sockaddr_stringify(&remote_address),
2722 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
2723 /* Only give this error message once if we are not RTP debugging */
2725 ast_debug(0, "RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
2726 ast_sockaddr_stringify(&remote_address));
2727 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
2731 rtp->txoctetcount += (res - hdrlen);
2733 if (rtp->rtcp && rtp->rtcp->schedid < 1) {
2734 ast_debug(1, "Starting RTCP transmission on RTP instance '%p'\n", instance);
2735 ao2_ref(instance, +1);
2736 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
2737 if (rtp->rtcp->schedid < 0) {
2738 ao2_ref(instance, -1);
2739 ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
2744 update_address_with_ice_candidate(rtp, AST_RTP_ICE_COMPONENT_RTP, &remote_address);
2746 if (rtp_debug_test_addr(&remote_address)) {
2747 ast_verbose("Sent RTP packet to %s%s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2748 ast_sockaddr_stringify(&remote_address),
2749 ice ? " (via ICE)" : "",
2750 codec, rtp->seqno, rtp->lastts, res - hdrlen);
2759 static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
2760 unsigned char *data = red->t140red.data.ptr;
2764 /* replace most aged generation */
2766 for (i = 1; i < red->num_gen+1; i++)
2769 memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
2772 /* Store length of each generation and primary data length*/
2773 for (i = 0; i < red->num_gen; i++)
2774 red->len[i] = red->len[i+1];
2775 red->len[i] = red->t140.datalen;
2777 /* write each generation length in red header */
2779 for (i = 0; i < red->num_gen; i++) {
2780 len += data[i*4+3] = red->len[i];
2783 /* add primary data to buffer */
2784 memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
2785 red->t140red.datalen = len + red->t140.datalen;
2787 /* no primary data and no generations to send */
2788 if (len == red->hdrlen && !red->t140.datalen) {
2792 /* reset t.140 buffer */
2793 red->t140.datalen = 0;
2795 return &red->t140red;
2798 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
2800 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2801 struct ast_sockaddr remote_address = { {0,} };
2802 struct ast_format subclass;
2805 ast_rtp_instance_get_remote_address(instance, &remote_address);
2807 /* If we don't actually know the remote address don't even bother doing anything */
2808 if (ast_sockaddr_isnull(&remote_address)) {
2809 ast_debug(1, "No remote address on RTP instance '%p' so dropping frame\n", instance);
2813 /* VP8: is this a request to send a RTCP FIR? */
2814 if (frame->frametype == AST_FRAME_CONTROL && frame->subclass.integer == AST_CONTROL_VIDUPDATE) {
2815 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2816 unsigned int *rtcpheader;
2822 if (!rtp || !rtp->rtcp) {
2826 if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
2833 /* Prepare RTCP FIR (PT=206, FMT=4) */
2834 rtp->rtcp->firseq++;
2835 if(rtp->rtcp->firseq == 256) {
2836 rtp->rtcp->firseq = 0;
2839 rtcpheader = (unsigned int *)bdata;
2840 rtcpheader[0] = htonl((2 << 30) | (4 << 24) | (RTCP_PT_PSFB << 16) | ((len/4)-1));
2841 rtcpheader[1] = htonl(rtp->ssrc);
2842 rtcpheader[2] = htonl(rtp->themssrc);
2843 rtcpheader[3] = htonl(rtp->themssrc); /* FCI: SSRC */
2844 rtcpheader[4] = htonl(rtp->rtcp->firseq << 24); /* FCI: Sequence number */
2845 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &rtp->rtcp->them, &ice);
2847 ast_log(LOG_ERROR, "RTCP FIR transmission error: %s\n", strerror(errno));
2852 /* If there is no data length we can't very well send the packet */
2853 if (!frame->datalen) {
2854 ast_debug(1, "Received frame with no data for RTP instance '%p' so dropping frame\n", instance);
2858 /* If the packet is not one our RTP stack supports bail out */
2859 if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
2860 ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
2866 /* no primary data or generations to send */
2867 if ((frame = red_t140_to_red(rtp->red)) == NULL)
2871 /* Grab the subclass and look up the payload we are going to use */
2872 ast_format_copy(&subclass, &frame->subclass.format);
2873 if ((codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 1, &subclass, 0)) < 0) {
2874 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(&frame->subclass.format));
2878 /* Oh dear, if the format changed we will have to set up a new smoother */
2879 if (ast_format_cmp(&rtp->lasttxformat, &subclass) == AST_FORMAT_CMP_NOT_EQUAL) {
2880 ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(&rtp->lasttxformat), ast_getformatname(&subclass));
2881 rtp->lasttxformat = subclass;
2882 ast_format_copy(&rtp->lasttxformat, &subclass);
2883 if (rtp->smoother) {
2884 ast_smoother_free(rtp->smoother);
2885 rtp->smoother = NULL;
2889 /* If no smoother is present see if we have to set one up */
2890 if (!rtp->smoother) {
2891 struct ast_format_list fmt = ast_codec_pref_getsize(&ast_rtp_instance_get_codecs(instance)->pref, &subclass);
2893 switch (subclass.id) {
2894 case AST_FORMAT_SPEEX:
2895 case AST_FORMAT_SPEEX16:
2896 case AST_FORMAT_SPEEX32:
2897 case AST_FORMAT_SILK:
2898 case AST_FORMAT_CELT:
2899 case AST_FORMAT_G723_1:
2900 case AST_FORMAT_SIREN7:
2901 case AST_FORMAT_SIREN14:
2902 case AST_FORMAT_G719:
2904 case AST_FORMAT_OPUS:
2905 /* these are all frame-based codecs and cannot be safely run through
2910 if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
2911 ast_log(LOG_WARNING, "Unable to create smoother: format %s ms: %d len: %d\n", ast_getformatname(&subclass), fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
2915 ast_smoother_set_flags(rtp->smoother, fmt.flags);
2917 ast_debug(1, "Created smoother: format: %s ms: %d len: %d\n", ast_getformatname(&subclass), fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
2922 /* Feed audio frames into the actual function that will create a frame and send it */
2923 if (rtp->smoother) {
2924 struct ast_frame *f;
2926 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
2927 ast_smoother_feed_be(rtp->smoother, frame);
2929 ast_smoother_feed(rtp->smoother, frame);
2932 while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
2933 ast_rtp_raw_write(instance, f, codec);
2937 struct ast_frame *f = NULL;
2939 if (frame->offset < hdrlen) {
2940 f = ast_frdup(frame);
2945 ast_rtp_raw_write(instance, f, codec);
2956 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
2961 double current_time;
2965 int rate = rtp_get_rate(&rtp->f.subclass.format);
2967 double normdev_rxjitter_current;
2968 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
2969 gettimeofday(&rtp->rxcore, NULL);
2970 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
2971 /* map timestamp to a real time */
2972 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
2973 tmp = ast_samp2tv(timestamp, rate);
2974 rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
2975 /* Round to 0.1ms for nice, pretty timestamps */
2976 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
2979 gettimeofday(&now,NULL);
2980 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
2981 tmp = ast_samp2tv(timestamp, rate);
2982 *tv = ast_tvadd(rtp->rxcore, tmp);
2984 prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
2985 dtv = (double)rtp->drxcore + (double)(prog);
2986 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
2987 transit = current_time - dtv;
2988 d = transit - rtp->rxtransit;
2989 rtp->rxtransit = transit;
2993 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
2995 if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
2996 rtp->rtcp->maxrxjitter = rtp->rxjitter;
2997 if (rtp->rtcp->rxjitter_count == 1)
2998 rtp->rtcp->minrxjitter = rtp->rxjitter;
2999 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
3000 rtp->rtcp->minrxjitter = rtp->rxjitter;
3002 normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
3003 rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
3005 rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
3006 rtp->rtcp->rxjitter_count++;
3010 static struct ast_frame *create_dtmf_frame(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
3012 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3013 struct ast_sockaddr remote_address = { {0,} };
3015 ast_rtp_instance_get_remote_address(instance, &remote_address);
3017 if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
3018 ast_debug(1, "Ignore potential DTMF echo from '%s'\n",
3019 ast_sockaddr_stringify(&remote_address));
3021 rtp->dtmfsamples = 0;
3022 return &ast_null_frame;
3024 ast_debug(1, "Creating %s DTMF Frame: %d (%c), at %s\n",
3025 type == AST_FRAME_DTMF_END ? "END" : "BEGIN",
3026 rtp->resp, rtp->resp,
3027 ast_sockaddr_stringify(&remote_address));
3028 if (rtp->resp == 'X') {
3029 rtp->f.frametype = AST_FRAME_CONTROL;
3030 rtp->f.subclass.integer = AST_CONTROL_FLASH;
3032 rtp->f.frametype = type;
3033 rtp->f.subclass.integer = rtp->resp;
3039 AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
3044 static void process_dtmf_rfc2833(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark, struct frame_list *frames)
3046 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
3047 struct ast_sockaddr remote_address = { {0,} };
3048 unsigned int event, event_end, samples;
3050 struct ast_frame *f = NULL;
3052 ast_rtp_instance_get_remote_address(instance, &remote_address);
3054 /* Figure out event, event end, and samples */
3055 event = ntohl(*((unsigned int *)(data)));
3057 event_end = ntohl(*((unsigned int *)(data)));
3060 samples = ntohl(*((unsigned int *)(data)));
3063 if (rtp_debug_test_addr(&remote_address)) {
3064 ast_verbose("Got RTP RFC2833 from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n",
3065 ast_sockaddr_stringify(&remote_address),
3066 payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
3069 /* Print out debug if turned on */
3071 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
3073 /* Figure out what digit was pressed */
3076 } else if (event < 11) {
3078 } else if (event < 12) {
3080 } else if (event < 16) {
3081 resp = 'A' + (event - 12);
3082 } else if (event < 17) { /* Event 16: Hook flash */
3085 /* Not a supported event */
3086 ast_debug(1, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
3090 if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
3091 if ((rtp->last_end_timestamp != timestamp) || (rtp->resp && rtp->resp != resp)) {
3093 rtp->dtmf_timeout = 0;
3094 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)));
3096 rtp->last_end_timestamp = timestamp;
3097 AST_LIST_INSERT_TAIL(frames, f, frame_list);
3100 /* The duration parameter measures the complete
3101 duration of the event (from the beginning) - RFC2833.
3102 Account for the fact that duration is only 16 bits long
3103 (about 8 seconds at 8000 Hz) and can wrap is digit
3104 is hold for too long. */
3105 unsigned int new_duration = rtp->dtmf_duration;
3106 unsigned int last_duration = new_duration & 0xFFFF;
3108 if (last_duration > 64000 && samples < last_duration) {
3109 new_duration += 0xFFFF + 1;
3111 new_duration = (new_duration & ~0xFFFF) | samples;
3113 if (event_end & 0x80) {
3115 if ((rtp->last_seqno != seqno) && (timestamp > rtp->last_end_timestamp)) {
3116 rtp->last_end_timestamp = timestamp;
3117 rtp->dtmf_duration = new_duration;
3119 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
3120 f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
3122 rtp->dtmf_duration = rtp->dtmf_timeout = 0;
3123 AST_LIST_INSERT_TAIL(frames, f, frame_list);
3124 } else if (rtpdebug) {
3125 ast_debug(1, "Dropping duplicate or out of order DTMF END frame (seqno: %d, ts %d, digit %c)\n",
3126 seqno, timestamp, resp);
3129 /* Begin/continuation */
3131 /* The second portion of the seqno check is to not mistakenly
3132 * stop accepting DTMF if the seqno rolls over beyond
3135 if ((rtp->last_seqno > seqno && rtp->last_seqno - seqno < 50)
3136 || timestamp <= rtp->last_end_timestamp) {
3137 /* Out of order frame. Processing this can cause us to
3138 * improperly duplicate incoming DTMF, so just drop
3142 ast_debug(1, "Dropping out of order DTMF frame (seqno %d, ts %d, digit %c)\n",
3143 seqno, timestamp, resp);
3148 if (rtp->resp && rtp->resp != resp) {
3149 /* Another digit already began. End it */
3150 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
3151 f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
3153 rtp->dtmf_duration = rtp->dtmf_timeout = 0;
3154 AST_LIST_INSERT_TAIL(frames, f, frame_list);
3158 /* Digit continues */
3159 rtp->dtmf_duration = new_duration;
3161 /* New digit began */
3163 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0));
3164 rtp->dtmf_duration = samples;