39 #include <arpa/nameser.h>
50 #include <openssl/opensslconf.h>
51 #include <openssl/opensslv.h>
52 #if !defined(OPENSSL_NO_SRTP) && (OPENSSL_VERSION_NUMBER >= 0x10001000L)
53 #include <openssl/ssl.h>
54 #include <openssl/err.h>
55 #include <openssl/bio.h>
56 #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
57 #include <openssl/bn.h>
60 #include <openssl/dh.h>
67 #include <pjlib-util.h>
74 #include "asterisk/logger_category.h"
94 #include "asterisk/res_pjproject.h"
98 #define MAX_TIMESTAMP_SKEW 640
100 #define RTP_SEQ_MOD (1<<16)
101 #define RTCP_DEFAULT_INTERVALMS 5000
102 #define RTCP_MIN_INTERVALMS 500
103 #define RTCP_MAX_INTERVALMS 60000
105 #define DEFAULT_RTP_START 5000
106 #define DEFAULT_RTP_END 31000
108 #define MINIMUM_RTP_PORT 1024
109 #define MAXIMUM_RTP_PORT 65535
111 #define DEFAULT_TURN_PORT 3478
113 #define TURN_STATE_WAIT_TIME 2000
115 #define DEFAULT_RTP_SEND_BUFFER_SIZE 250
116 #define MAXIMUM_RTP_SEND_BUFFER_SIZE (DEFAULT_RTP_SEND_BUFFER_SIZE + 200)
117 #define DEFAULT_RTP_RECV_BUFFER_SIZE 20
118 #define MAXIMUM_RTP_RECV_BUFFER_SIZE (DEFAULT_RTP_RECV_BUFFER_SIZE + 20)
119 #define OLD_PACKET_COUNT 1000
120 #define MISSING_SEQNOS_ADDED_TRIGGER 2
122 #define SEQNO_CYCLE_OVER 65536
125 #define RTCP_PT_FUR 192
127 #define RTCP_PT_SR AST_RTP_RTCP_SR
129 #define RTCP_PT_RR AST_RTP_RTCP_RR
131 #define RTCP_PT_SDES 202
133 #define RTCP_PT_BYE 203
135 #define RTCP_PT_APP 204
138 #define RTCP_PT_PSFB AST_RTP_RTCP_PSFB
142 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000))
144 #define ZFONE_PROFILE_ID 0x505a
146 #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
159 #define CALC_LEARNING_MIN_DURATION(count) (((count) - 1) * 9 - 5)
160 #define DEFAULT_LEARNING_MIN_DURATION CALC_LEARNING_MIN_DURATION(DEFAULT_LEARNING_MIN_SEQUENTIAL)
162 #define SRTP_MASTER_KEY_LEN 16
163 #define SRTP_MASTER_SALT_LEN 14
164 #define SRTP_MASTER_LEN (SRTP_MASTER_KEY_LEN + SRTP_MASTER_SALT_LEN)
166 #define RTP_DTLS_ESTABLISHED -37
187 #define STRICT_RTP_LEARN_TIMEOUT 5000
189 #define DEFAULT_STRICT_RTP STRICT_RTP_YES
190 #define DEFAULT_SRTP_REPLAY_PROTECTION 1
191 #define DEFAULT_ICESUPPORT 1
192 #define DEFAULT_STUN_SOFTWARE_ATTRIBUTE 1
193 #define DEFAULT_DTLS_MTU 1200
203 #define RTP_IGNORE_FIRST_PACKETS_COUNT 15
219 static int nochecksums;
224 static int srtp_replay_protection = DEFAULT_SRTP_REPLAY_PROTECTION;
225 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
226 static int dtls_mtu = DEFAULT_DTLS_MTU;
228 #ifdef HAVE_PJPROJECT
229 static int icesupport = DEFAULT_ICESUPPORT;
230 static int stun_software_attribute = DEFAULT_STUN_SOFTWARE_ATTRIBUTE;
231 static struct sockaddr_in stunaddr;
232 static pj_str_t turnaddr;
233 static int turnport = DEFAULT_TURN_PORT;
234 static pj_str_t turnusername;
235 static pj_str_t turnpassword;
241 static ast_rwlock_t ice_acl_lock = AST_RWLOCK_INIT_VALUE;
245 static ast_rwlock_t stun_acl_lock = AST_RWLOCK_INIT_VALUE;
291 unsigned int include_local;
292 AST_RWLIST_ENTRY(ast_ice_host_candidate) next;
302 #define FLAG_3389_WARNING (1 << 0)
303 #define FLAG_NAT_ACTIVE (3 << 1)
304 #define FLAG_NAT_INACTIVE (0 << 1)
305 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
306 #define FLAG_NEED_MARKER_BIT (1 << 3)
307 #define FLAG_DTMF_COMPENSATE (1 << 4)
308 #define FLAG_REQ_LOCAL_BRIDGE_BIT (1 << 5)
310 #define TRANSPORT_SOCKET_RTP 0
311 #define TRANSPORT_SOCKET_RTCP 1
312 #define TRANSPORT_TURN_RTP 2
313 #define TRANSPORT_TURN_RTCP 3
318 struct timeval start;
319 struct timeval received;
326 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
327 struct dtls_details {
337 #ifdef HAVE_PJPROJECT
359 struct timeval received;
382 unsigned char is_set;
394 char cname[AST_UUID_STR_LEN];
398 unsigned int lastividtimestamp;
399 unsigned int lastovidtimestamp;
400 unsigned int lastitexttimestamp;
401 unsigned int lastotexttimestamp;
407 unsigned short seedrxseqno;
408 unsigned int rxcount;
409 unsigned int rxoctetcount;
410 unsigned int txcount;
411 unsigned int txoctetcount;
420 double rxstart_stable;
421 unsigned int remote_seed_rx_rtp_ts;
422 unsigned int remote_seed_rx_rtp_ts_stable;
423 unsigned int last_transit_time_samples;
425 double rxjitter_samples;
430 unsigned int last_seqno;
432 unsigned int dtmf_duration;
433 unsigned int dtmf_timeout;
434 unsigned int dtmfsamples;
436 unsigned int dtmf_samplerate_ms;
438 unsigned int lastdigitts;
444 struct timeval rxcore;
445 struct timeval txcore;
447 struct timeval dtmfmute;
452 unsigned int asymmetric_codec;
481 #ifdef HAVE_PJPROJECT
489 unsigned int passthrough:1;
490 unsigned int rtp_passthrough:1;
491 unsigned int rtcp_passthrough:1;
498 char remote_ufrag[256];
499 char remote_passwd[256];
501 char local_ufrag[256];
502 char local_passwd[256];
509 unsigned int ice_media_started:1;
512 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
515 enum ast_srtp_suite suite;
517 char local_fingerprint[160];
519 unsigned char remote_fingerprint[EVP_MAX_MD_SIZE];
522 struct dtls_details dtls;
544 struct timeval rxlsr;
545 struct timeval txlsr;
604 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
605 struct dtls_details dtls;
612 char *local_addr_str;
627 unsigned char t140red_data[64000];
628 unsigned char buf_data[64000];
636 unsigned char buf[0];
671 static void update_reported_mes_stats(
struct ast_rtp *rtp);
672 static void update_local_mes_stats(
struct ast_rtp *rtp);
674 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
678 static int dtls_bio_write(BIO *bio,
const char *buf,
int len);
679 static long dtls_bio_ctrl(BIO *bio,
int cmd,
long arg1,
void *arg2);
680 static int dtls_bio_new(BIO *bio);
681 static int dtls_bio_free(BIO *bio);
683 #ifndef HAVE_OPENSSL_BIO_METHOD
684 static BIO_METHOD dtls_bio_methods = {
685 .type = BIO_TYPE_BIO,
687 .bwrite = dtls_bio_write,
688 .ctrl = dtls_bio_ctrl,
689 .create = dtls_bio_new,
690 .destroy = dtls_bio_free,
693 static BIO_METHOD *dtls_bio_methods;
699 #ifdef HAVE_PJPROJECT
700 static void stunaddr_resolve_callback(
const struct ast_dns_query *query);
701 static int store_stunaddr_resolved(
const struct ast_dns_query *query);
704 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
705 static int dtls_bio_new(BIO *bio)
707 #ifdef HAVE_OPENSSL_BIO_METHOD
708 BIO_set_init(bio, 1);
709 BIO_set_data(bio, NULL);
710 BIO_set_shutdown(bio, 0);
719 static int dtls_bio_free(BIO *bio)
725 #ifdef HAVE_OPENSSL_BIO_METHOD
726 BIO_set_data(bio, NULL);
733 static int dtls_bio_write(BIO *bio,
const char *buf,
int len)
735 #ifdef HAVE_OPENSSL_BIO_METHOD
750 if (rtp->rtcp && rtp->rtcp->dtls.write_bio == bio) {
761 bytes_sent =
__rtp_sendto(instance, (
char *)buf, len, 0, &remote_address, rtcp, &ice, 0);
763 if (bytes_sent > 0 && ast_debug_dtls_packet_is_allowed) {
764 ast_debug(0,
"(%p) DTLS - sent %s packet to %s%s (len %-6.6d)\n",
766 ice ?
" (via ICE)" :
"", bytes_sent);
772 static long dtls_bio_ctrl(BIO *bio,
int cmd,
long arg1,
void *arg2)
777 case BIO_CTRL_DGRAM_QUERY_MTU:
779 case BIO_CTRL_WPENDING:
780 case BIO_CTRL_PENDING:
789 #ifdef HAVE_PJPROJECT
797 AST_RWLIST_REMOVE_CURRENT(next);
800 AST_RWLIST_TRAVERSE_SAFE_END;
808 char address[PJ_INET6_ADDRSTRLEN];
810 if (component < 1 || !ice->comp[component - 1].valid_check) {
815 pj_sockaddr_print(&ice->comp[component - 1].valid_check->rcand->addr, address,
816 sizeof(address), 0), 0);
818 pj_sockaddr_get_port(&ice->comp[component - 1].valid_check->rcand->addr));
839 int ice_attrb_reset = 0;
841 if (!ast_strlen_zero(ufrag)) {
848 if (!ast_strlen_zero(password)) {
856 if (ice_attrb_reset) {
862 static int ice_candidate_cmp(
void *obj,
void *arg,
int flags)
866 if (strcmp(candidate1->
foundation, candidate2->foundation) ||
867 candidate1->
id != candidate2->id ||
868 candidate1->
type != candidate2->type ||
883 if (strcasecmp(candidate->
transport,
"udp")) {
905 remote_candidate->
id = candidate->
id;
910 remote_candidate->
type = candidate->
type;
912 ast_debug_ice(2,
"(%p) ICE add remote candidate\n", instance);
923 pj_thread_desc *desc;
926 if (pj_thread_is_registered() == PJ_TRUE) {
932 ast_log(LOG_ERROR,
"Could not get thread desc from thread-local storage. Expect awful things to occur\n");
935 pj_bzero(*desc,
sizeof(*desc));
937 if (pj_thread_register(
"Asterisk Thread", *desc, &thread) != PJ_SUCCESS) {
938 ast_log(LOG_ERROR,
"Coudln't register thread with PJLIB.\n");
944 int port,
int replace);
956 ao2_unlock(instance);
983 static void ast2pj_rtp_ice_role(
enum ast_rtp_ice_role ast_role,
enum pj_ice_sess_role *pj_role)
986 case AST_RTP_ICE_ROLE_CONTROLLED:
987 *pj_role = PJ_ICE_SESS_ROLE_CONTROLLED;
989 case AST_RTP_ICE_ROLE_CONTROLLING:
990 *pj_role = PJ_ICE_SESS_ROLE_CONTROLLING;
995 static void pj2ast_rtp_ice_role(
enum pj_ice_sess_role pj_role,
enum ast_rtp_ice_role *ast_role)
998 case PJ_ICE_SESS_ROLE_CONTROLLED:
999 *ast_role = AST_RTP_ICE_ROLE_CONTROLLED;
1001 case PJ_ICE_SESS_ROLE_CONTROLLING:
1002 *ast_role = AST_RTP_ICE_ROLE_CONTROLLING;
1004 case PJ_ICE_SESS_ROLE_UNKNOWN:
1022 ast_debug_ice(3,
" (%p) ICE nevermind, not ready for a reset\n", instance);
1026 ast_debug_ice(3,
"(%p) ICE recreating ICE session %s (%d)\n",
1031 enum pj_ice_sess_role
role = PJ_ICE_SESS_ROLE_UNKNOWN;
1032 ast2pj_rtp_ice_role(rtp->
role, &role);
1033 pj_ice_sess_change_role(rtp->
ice->
real_ice, role);
1041 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1046 ao2_unlock(instance);
1049 while (rtp->
turn_state != PJ_TURN_STATE_DESTROYING) {
1069 while ((right_candidate = ao2_iterator_next(&i))) {
1072 if (!left_candidate) {
1091 pj_ice_sess_cand candidates[PJ_ICE_MAX_CAND];
1094 int cand_cnt = 0, has_rtp = 0, has_rtcp = 0;
1103 ast_debug_ice(2,
"(%p) ICE proposed equals active candidates\n", instance);
1120 ast_log(LOG_NOTICE,
"(%p) ICE failed to create replacement session\n", instance);
1128 while ((candidate = ao2_iterator_next(&i)) && (cand_cnt < PJ_ICE_MAX_CAND)) {
1132 has_rtp |= candidate->
id == AST_RTP_ICE_COMPONENT_RTP;
1133 has_rtcp |= candidate->
id == AST_RTP_ICE_COMPONENT_RTCP;
1135 pj_strdup2(rtp->
ice->
real_ice->pool, &candidates[cand_cnt].foundation,
1137 candidates[cand_cnt].comp_id = candidate->
id;
1138 candidates[cand_cnt].prio = candidate->
priority;
1147 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_HOST;
1149 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_SRFLX;
1151 candidates[cand_cnt].type = PJ_ICE_CAND_TYPE_RELAYED;
1154 if (candidate->
id == AST_RTP_ICE_COMPONENT_RTP && rtp->
turn_rtp) {
1157 ao2_unlock(instance);
1158 pj_turn_sock_set_perm(rtp->
turn_rtp, 1, &candidates[cand_cnt].addr, 1);
1160 }
else if (candidate->
id == AST_RTP_ICE_COMPONENT_RTCP && rtp->
turn_rtcp) {
1163 ao2_unlock(instance);
1164 pj_turn_sock_set_perm(rtp->
turn_rtcp, 1, &candidates[cand_cnt].addr, 1);
1175 ast_log(LOG_WARNING,
"(%p) ICE lost %d candidates. Consider increasing PJ_ICE_MAX_CAND in PJSIP\n",
1180 ast_log(LOG_WARNING,
"(%p) ICE no RTP candidates; skipping checklist\n", instance);
1185 ast_log(LOG_WARNING,
"(%p) ICE no RTCP candidates; skipping checklist\n", instance);
1196 ao2_unlock(instance);
1197 res = pj_ice_sess_create_check_list(ice->
real_ice, &ufrag, &passwd, cand_cnt, &candidates[0]);
1198 if (res == PJ_SUCCESS) {
1199 ast_debug_ice(2,
"(%p) ICE successfully created checklist\n", instance);
1201 pj_ice_sess_start_check(ice->
real_ice);
1211 pj_strerror(res, reason,
sizeof(reason));
1212 ast_log(LOG_WARNING,
"(%p) ICE failed to create session check list: %s\n", instance, reason);
1267 pj_ice_sess_change_role(rtp->
ice->
real_ice, PJ_ICE_SESS_ROLE_CONTROLLING);
1276 ast_debug_ice(3,
"(%p) ICE set role failed; no ice instance\n", instance);
1285 instance, role == AST_RTP_ICE_ROLE_CONTROLLED ?
"CONTROLLED" :
"CONTROLLING");
1286 pj_ice_sess_change_role(rtp->
ice->
real_ice, role == AST_RTP_ICE_ROLE_CONTROLLED ?
1287 PJ_ICE_SESS_ROLE_CONTROLLED : PJ_ICE_SESS_ROLE_CONTROLLING);
1289 ast_debug_ice(2,
"(%p) ICE not setting role because state is %s\n",
1290 instance, rtp->
ice->
real_ice->is_nominating ?
"nominating" :
"complete");
1296 unsigned comp_id,
unsigned transport_id, pj_ice_cand_type type, pj_uint16_t local_pref,
1297 const pj_sockaddr_t *addr,
const pj_sockaddr_t *base_addr,
const pj_sockaddr_t *rel_addr,
1300 pj_str_t foundation;
1303 char address[PJ_INET6_ADDRSTRLEN];
1312 pj_ice_calc_foundation(rtp->
ice->
real_ice->pool, &foundation, type, addr);
1316 NULL, ice_candidate_cmp);
1327 candidate->
id = comp_id;
1338 if (type == PJ_ICE_CAND_TYPE_HOST) {
1340 }
else if (type == PJ_ICE_CAND_TYPE_SRFLX) {
1342 }
else if (type == PJ_ICE_CAND_TYPE_RELAYED) {
1355 ao2_unlock(instance);
1356 status = pj_ice_sess_add_cand(ice->
real_ice, comp_id, transport_id, type, local_pref,
1357 &foundation, addr, base_addr, rel_addr, addr_len, NULL);
1360 if (!rtp->
ice || status != PJ_SUCCESS) {
1378 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)
1387 ao2_unlock(instance);
1390 status = pj_ice_sess_on_rx_pkt(ice->
real_ice, AST_RTP_ICE_COMPONENT_RTP,
1391 TRANSPORT_TURN_RTP, pkt, pkt_len, peer_addr, addr_len);
1393 if (status != PJ_SUCCESS) {
1396 pj_strerror(status, buf,
sizeof(buf));
1397 ast_log(LOG_WARNING,
"(%p) ICE PJ Rx error status code: %d '%s'.\n",
1398 instance, (
int)status, buf);
1411 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)
1427 ast_cond_signal(&rtp->
cond);
1429 if (new_state == PJ_TURN_STATE_DESTROYING) {
1430 pj_turn_sock_set_user_data(rtp->
turn_rtp, NULL);
1434 ao2_unlock(instance);
1438 static pj_turn_sock_cb ast_rtp_turn_rtp_sock_cb = {
1439 .on_rx_data = ast_rtp_on_turn_rx_rtp_data,
1440 .on_state = ast_rtp_on_turn_rtp_state,
1444 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)
1453 ao2_unlock(instance);
1456 status = pj_ice_sess_on_rx_pkt(ice->
real_ice, AST_RTP_ICE_COMPONENT_RTCP,
1457 TRANSPORT_TURN_RTCP, pkt, pkt_len, peer_addr, addr_len);
1459 if (status != PJ_SUCCESS) {
1462 pj_strerror(status, buf,
sizeof(buf));
1463 ast_log(LOG_WARNING,
"PJ ICE Rx error status code: %d '%s'.\n",
1477 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)
1493 ast_cond_signal(&rtp->
cond);
1495 if (new_state == PJ_TURN_STATE_DESTROYING) {
1496 pj_turn_sock_set_user_data(rtp->
turn_rtcp, NULL);
1500 ao2_unlock(instance);
1504 static pj_turn_sock_cb ast_rtp_turn_rtcp_sock_cb = {
1505 .on_rx_data = ast_rtp_on_turn_rx_rtcp_data,
1506 .on_state = ast_rtp_on_turn_rtcp_state,
1515 const pj_time_val delay = {0, 10};
1517 pj_ioqueue_poll(ioqueue->
ioqueue, &delay);
1519 pj_timer_heap_poll(ioqueue->
timerheap, NULL);
1530 pj_thread_join(ioqueue->
thread);
1531 pj_thread_destroy(ioqueue->
thread);
1534 if (ioqueue->
pool) {
1538 pj_pool_t *temp_pool = ioqueue->
pool;
1540 ioqueue->
pool = NULL;
1541 pj_pool_release(temp_pool);
1554 if ((ioqueue->
count -= 2) == 0) {
1577 if ((ioqueue->
count + 2) < PJ_IOQUEUE_MAX_HANDLES) {
1584 ioqueue->
count += 2;
1593 ioqueue->
pool = pj_pool_create(&
cachingpool.factory,
"rtp", 512, 512, NULL);
1598 if (pj_timer_heap_create(ioqueue->
pool, 4, &ioqueue->
timerheap) != PJ_SUCCESS) {
1602 if (pj_lock_create_recursive_mutex(ioqueue->
pool,
"rtp%p", &lock) != PJ_SUCCESS) {
1606 pj_timer_heap_set_lock(ioqueue->
timerheap, lock, PJ_TRUE);
1608 if (pj_ioqueue_create(ioqueue->
pool, PJ_IOQUEUE_MAX_HANDLES, &ioqueue->
ioqueue) != PJ_SUCCESS) {
1634 enum ast_transport transport,
const char *server,
unsigned int port,
const char *username,
const char *password)
1637 pj_turn_sock **turn_sock;
1638 const pj_turn_sock_cb *turn_cb;
1639 pj_turn_tp_type conn_type;
1641 pj_stun_auth_cred cred = { 0, };
1644 pj_stun_config stun_config;
1646 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
1647 pj_turn_session_info info;
1650 pj_turn_sock_cfg turn_sock_cfg;
1661 if (component == AST_RTP_ICE_COMPONENT_RTP) {
1663 turn_cb = &ast_rtp_turn_rtp_sock_cb;
1664 conn_transport = TRANSPORT_TURN_RTP;
1666 }
else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1668 turn_cb = &ast_rtp_turn_rtcp_sock_cb;
1669 conn_transport = TRANSPORT_TURN_RTCP;
1675 if (transport == AST_TRANSPORT_UDP) {
1676 conn_type = PJ_TURN_TP_UDP;
1677 }
else if (transport == AST_TRANSPORT_TCP) {
1678 conn_type = PJ_TURN_TP_TCP;
1690 ao2_unlock(instance);
1691 pj_turn_sock_destroy(*turn_sock);
1693 while (rtp->
turn_state != PJ_TURN_STATE_DESTROYING) {
1698 if (component == AST_RTP_ICE_COMPONENT_RTP && !rtp->
ioqueue) {
1704 ao2_unlock(instance);
1713 if (!stun_software_attribute) {
1714 stun_config.software_name = pj_str(NULL);
1718 pj_turn_sock_cfg_default(&turn_sock_cfg);
1721 turn_sock_cfg.grp_lock = ice->
real_ice->grp_lock;
1726 ao2_unlock(instance);
1727 status = pj_turn_sock_create(&stun_config,
1729 turn_cb, &turn_sock_cfg, instance, turn_sock);
1731 if (status != PJ_SUCCESS) {
1732 ast_log(LOG_WARNING,
"(%p) Could not create a TURN client socket\n", instance);
1737 cred.type = PJ_STUN_AUTH_CRED_STATIC;
1738 pj_strset2(&cred.data.static_cred.username, (
char*)username);
1739 cred.data.static_cred.data_type = PJ_STUN_PASSWD_PLAIN;
1740 pj_strset2(&cred.data.static_cred.data, (
char*)password);
1742 pj_turn_sock_alloc(*turn_sock, pj_cstr(&turn_addr, server), port, NULL, &cred, NULL);
1744 ast_debug_ice(2,
"(%p) ICE request TURN %s %s candidate\n", instance,
1745 transport == AST_TRANSPORT_UDP ?
"UDP" :
"TCP",
1746 component == AST_RTP_ICE_COMPONENT_RTP ?
"RTP" :
"RTCP");
1754 while (rtp->
turn_state < PJ_TURN_STATE_READY) {
1759 if (rtp->
turn_state != PJ_TURN_STATE_READY) {
1763 pj_turn_sock_get_info(*turn_sock, &info);
1766 PJ_ICE_CAND_TYPE_RELAYED, 65535, &info.relay_addr, &info.relay_addr,
1767 &info.mapped_addr, pj_sockaddr_get_len(&info.relay_addr));
1769 if (component == AST_RTP_ICE_COMPONENT_RTP) {
1771 }
else if (component == AST_RTP_ICE_COMPONENT_RTCP) {
1781 for (x=0; x<4; x++) {
1782 val[x] = ast_random();
1784 snprintf(buf, size,
"%08lx%08lx%08lx%08lx", (
long unsigned)val[0], (
long unsigned)val[1], (
long unsigned)val[2], (
long unsigned)val[3]);
1801 ast_debug_ice(2,
"(%p) ICE change number of components %u -> %u\n", instance,
1824 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
1825 static int dtls_verify_callback(
int preverify_ok, X509_STORE_CTX *ctx)
1831 static int dtls_details_initialize(
struct dtls_details *dtls, SSL_CTX *ssl_ctx,
1834 dtls->dtls_setup = setup;
1836 if (!(dtls->ssl = SSL_new(ssl_ctx))) {
1837 ast_log(LOG_ERROR,
"Failed to allocate memory for SSL\n");
1841 if (!(dtls->read_bio = BIO_new(BIO_s_mem()))) {
1842 ast_log(LOG_ERROR,
"Failed to allocate memory for inbound SSL traffic\n");
1845 BIO_set_mem_eof_return(dtls->read_bio, -1);
1847 #ifdef HAVE_OPENSSL_BIO_METHOD
1848 if (!(dtls->write_bio = BIO_new(dtls_bio_methods))) {
1849 ast_log(LOG_ERROR,
"Failed to allocate memory for outbound SSL traffic\n");
1853 BIO_set_data(dtls->write_bio, instance);
1855 if (!(dtls->write_bio = BIO_new(&dtls_bio_methods))) {
1856 ast_log(LOG_ERROR,
"Failed to allocate memory for outbound SSL traffic\n");
1859 dtls->write_bio->ptr = instance;
1861 SSL_set_bio(dtls->ssl, dtls->read_bio, dtls->write_bio);
1864 SSL_set_accept_state(dtls->ssl);
1866 SSL_set_connect_state(dtls->ssl);
1873 if (dtls->read_bio) {
1874 BIO_free(dtls->read_bio);
1875 dtls->read_bio = NULL;
1878 if (dtls->write_bio) {
1879 BIO_free(dtls->write_bio);
1880 dtls->write_bio = NULL;
1884 SSL_free(dtls->ssl);
1894 if (!rtp->ssl_ctx || !rtp->rtcp) {
1899 return dtls_details_initialize(&rtp->rtcp->dtls, rtp->ssl_ctx, rtp->dtls.dtls_setup, instance);
1902 static const SSL_METHOD *get_dtls_method(
void)
1904 #if OPENSSL_VERSION_NUMBER < 0x10002000L
1905 return DTLSv1_method();
1907 return DTLS_method();
1911 struct dtls_cert_info {
1912 EVP_PKEY *private_key;
1916 static int apply_dh_params(SSL_CTX *ctx, BIO *bio)
1920 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1921 EVP_PKEY *dhpkey = PEM_read_bio_Parameters(bio, NULL);
1922 if (dhpkey && EVP_PKEY_is_a(dhpkey,
"DH")) {
1923 res = SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey);
1929 EVP_PKEY_free(dhpkey);
1932 DH *dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1934 res = SSL_CTX_set_tmp_dh(ctx, dh);
1944 #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
1948 #ifndef OPENSSL_NO_DH
1949 if (!ast_strlen_zero(dtls_cfg->
pvtfile)) {
1950 BIO *bio = BIO_new_file(dtls_cfg->
pvtfile,
"r");
1952 if (apply_dh_params(rtp->ssl_ctx, bio)) {
1953 long options = SSL_OP_CIPHER_SERVER_PREFERENCE |
1954 SSL_OP_SINGLE_DH_USE | SSL_OP_SINGLE_ECDH_USE;
1955 options = SSL_CTX_set_options(rtp->ssl_ctx, options);
1956 ast_verb(2,
"DTLS DH initialized, PFS enabled\n");
1963 #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L) && (OPENSSL_VERSION_NUMBER < 0x10100000L)
1965 ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
1967 if (SSL_CTX_set_tmp_ecdh(rtp->ssl_ctx, ecdh)) {
1968 #ifndef SSL_CTRL_SET_ECDH_AUTO
1969 #define SSL_CTRL_SET_ECDH_AUTO 94
1972 if (SSL_CTX_ctrl(rtp->ssl_ctx, SSL_CTRL_SET_ECDH_AUTO, 1, NULL)) {
1973 ast_verb(2,
"DTLS ECDH initialized (automatic), faster PFS enabled\n");
1975 ast_verb(2,
"DTLS ECDH initialized (secp256r1), faster PFS enabled\n");
1983 #if !defined(OPENSSL_NO_ECDH) && (OPENSSL_VERSION_NUMBER >= 0x10000000L)
1985 static int create_ephemeral_ec_keypair(EVP_PKEY **keypair)
1987 #if OPENSSL_VERSION_NUMBER >= 0x30000000L
1988 *keypair = EVP_EC_gen(SN_X9_62_prime256v1);
1989 return *keypair ? 0 : -1;
1991 EC_KEY *eckey = NULL;
1992 EC_GROUP *
group = NULL;
1994 group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
1999 EC_GROUP_set_asn1_flag(group, OPENSSL_EC_NAMED_CURVE);
2000 EC_GROUP_set_point_conversion_form(group, POINT_CONVERSION_UNCOMPRESSED);
2002 eckey = EC_KEY_new();
2007 if (!EC_KEY_set_group(eckey, group)) {
2011 if (!EC_KEY_generate_key(eckey)) {
2015 *keypair = EVP_PKEY_new();
2020 EVP_PKEY_assign_EC_KEY(*keypair, eckey);
2021 EC_GROUP_free(group);
2027 EC_GROUP_free(group);
2034 #define SERIAL_RAND_BITS 159
2036 static int create_ephemeral_certificate(EVP_PKEY *keypair, X509 **certificate)
2039 BIGNUM *serial = NULL;
2040 X509_NAME *name = NULL;
2047 if (!X509_set_version(cert, 2)) {
2052 X509_set_pubkey(cert, keypair);
2055 if (!(serial = BN_new())
2056 || !BN_rand(serial, SERIAL_RAND_BITS, -1, 0)
2057 || !BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(cert))) {
2068 #if OPENSSL_VERSION_NUMBER < 0x10100000L
2069 if (!X509_time_adj_ex(X509_get_notBefore(cert), -1, 0, NULL)
2070 || !X509_time_adj_ex(X509_get_notAfter(cert), 30, 0, NULL)) {
2074 if (!X509_time_adj_ex(X509_getm_notBefore(cert), -1, 0, NULL)
2075 || !X509_time_adj_ex(X509_getm_notAfter(cert), 30, 0, NULL)) {
2081 if (!(name = X509_get_subject_name(cert))
2082 || !X509_NAME_add_entry_by_NID(name, NID_commonName, MBSTRING_ASC,
2083 (
unsigned char *)
"asterisk", -1, -1, 0)
2084 || !X509_set_issuer_name(cert, name)) {
2089 if (!X509_sign(cert, keypair, EVP_sha256())) {
2093 *certificate = cert;
2105 struct dtls_cert_info *cert_info)
2108 cert_info->private_key = NULL;
2109 cert_info->certificate = NULL;
2111 if (create_ephemeral_ec_keypair(&cert_info->private_key)) {
2112 ast_log(LOG_ERROR,
"Failed to create ephemeral ECDSA keypair\n");
2116 if (create_ephemeral_certificate(cert_info->private_key, &cert_info->certificate)) {
2117 ast_log(LOG_ERROR,
"Failed to create ephemeral X509 certificate\n");
2124 X509_free(cert_info->certificate);
2125 EVP_PKEY_free(cert_info->private_key);
2134 struct dtls_cert_info *cert_info)
2136 ast_log(LOG_ERROR,
"Your version of OpenSSL does not support ECDSA keys\n");
2144 struct dtls_cert_info *cert_info)
2147 BIO *certbio = NULL;
2148 EVP_PKEY *private_key = NULL;
2152 fp = fopen(private_key_file,
"r");
2154 ast_log(LOG_ERROR,
"Failed to read private key from file '%s': %s\n", private_key_file, strerror(errno));
2158 if (!PEM_read_PrivateKey(fp, &private_key, NULL, NULL)) {
2159 ast_log(LOG_ERROR,
"Failed to read private key from PEM file '%s'\n", private_key_file);
2165 ast_log(LOG_ERROR,
"Failed to close private key file '%s': %s\n", private_key_file, strerror(errno));
2169 certbio = BIO_new(BIO_s_file());
2171 ast_log(LOG_ERROR,
"Failed to allocate memory for certificate fingerprinting on RTP instance '%p'\n",
2176 if (!BIO_read_filename(certbio, dtls_cfg->
certfile)
2177 || !(cert = PEM_read_bio_X509(certbio, NULL, 0, NULL))) {
2178 ast_log(LOG_ERROR,
"Failed to read certificate from file '%s'\n", dtls_cfg->
certfile);
2182 cert_info->private_key = private_key;
2183 cert_info->certificate = cert;
2185 BIO_free_all(certbio);
2191 BIO_free_all(certbio);
2192 EVP_PKEY_free(private_key);
2199 struct dtls_cert_info *cert_info)
2202 return create_certificate_ephemeral(instance, dtls_cfg, cert_info);
2203 }
else if (!ast_strlen_zero(dtls_cfg->
certfile)) {
2204 return create_certificate_from_file(instance, dtls_cfg, cert_info);
2214 struct dtls_cert_info cert_info = { 0 };
2223 if (!ast_rtp_engine_srtp_is_registered()) {
2224 ast_log(LOG_ERROR,
"SRTP support module is not loaded or available. Try loading res_srtp.so.\n");
2232 rtp->ssl_ctx = SSL_CTX_new(get_dtls_method());
2233 if (!rtp->ssl_ctx) {
2237 SSL_CTX_set_read_ahead(rtp->ssl_ctx, 1);
2239 configure_dhparams(rtp, dtls_cfg);
2241 rtp->dtls_verify = dtls_cfg->
verify;
2245 dtls_verify_callback : NULL);
2247 if (dtls_cfg->
suite == AST_AES_CM_128_HMAC_SHA1_80) {
2248 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx,
"SRTP_AES128_CM_SHA1_80");
2249 }
else if (dtls_cfg->
suite == AST_AES_CM_128_HMAC_SHA1_32) {
2250 SSL_CTX_set_tlsext_use_srtp(rtp->ssl_ctx,
"SRTP_AES128_CM_SHA1_32");
2252 ast_log(LOG_ERROR,
"Unsupported suite specified for DTLS-SRTP on RTP instance '%p'\n", instance);
2256 rtp->local_hash = dtls_cfg->
hash;
2258 if (!load_dtls_certificate(instance, dtls_cfg, &cert_info)) {
2260 unsigned int size, i;
2261 unsigned char fingerprint[EVP_MAX_MD_SIZE];
2262 char *local_fingerprint = rtp->local_fingerprint;
2264 if (!SSL_CTX_use_certificate(rtp->ssl_ctx, cert_info.certificate)) {
2265 ast_log(LOG_ERROR,
"Specified certificate for RTP instance '%p' could not be used\n",
2270 if (!SSL_CTX_use_PrivateKey(rtp->ssl_ctx, cert_info.private_key)
2271 || !SSL_CTX_check_private_key(rtp->ssl_ctx)) {
2272 ast_log(LOG_ERROR,
"Specified private key for RTP instance '%p' could not be used\n",
2280 type = EVP_sha256();
2282 ast_log(LOG_ERROR,
"Unsupported fingerprint hash type on RTP instance '%p'\n",
2287 if (!X509_digest(cert_info.certificate, type, fingerprint, &size) || !size) {
2288 ast_log(LOG_ERROR,
"Could not produce fingerprint from certificate for RTP instance '%p'\n",
2293 for (i = 0; i < size; i++) {
2294 sprintf(local_fingerprint,
"%02hhX:", fingerprint[i]);
2295 local_fingerprint += 3;
2298 *(local_fingerprint - 1) = 0;
2300 EVP_PKEY_free(cert_info.private_key);
2301 X509_free(cert_info.certificate);
2304 if (!ast_strlen_zero(dtls_cfg->
cipher)) {
2305 if (!SSL_CTX_set_cipher_list(rtp->ssl_ctx, dtls_cfg->
cipher)) {
2306 ast_log(LOG_ERROR,
"Invalid cipher specified in cipher list '%s' for RTP instance '%p'\n",
2307 dtls_cfg->
cipher, instance);
2312 if (!ast_strlen_zero(dtls_cfg->
cafile) || !ast_strlen_zero(dtls_cfg->
capath)) {
2313 if (!SSL_CTX_load_verify_locations(rtp->ssl_ctx,
S_OR(dtls_cfg->
cafile, NULL),
S_OR(dtls_cfg->
capath, NULL))) {
2314 ast_log(LOG_ERROR,
"Invalid certificate authority file '%s' or path '%s' specified for RTP instance '%p'\n",
2320 rtp->rekey = dtls_cfg->
rekey;
2321 rtp->suite = dtls_cfg->
suite;
2323 res = dtls_details_initialize(&rtp->dtls, rtp->ssl_ctx, dtls_cfg->
default_setup, instance);
2325 dtls_setup_rtcp(instance);
2336 return !rtp->ssl_ctx ? 0 : 1;
2343 SSL *ssl = rtp->dtls.ssl;
2346 ao2_unlock(instance);
2347 dtls_srtp_stop_timeout_timer(instance, rtp, 0);
2351 SSL_CTX_free(rtp->ssl_ctx);
2352 rtp->ssl_ctx = NULL;
2355 if (rtp->dtls.ssl) {
2356 SSL_free(rtp->dtls.ssl);
2357 rtp->dtls.ssl = NULL;
2361 ao2_unlock(instance);
2362 dtls_srtp_stop_timeout_timer(instance, rtp, 1);
2365 if (rtp->rtcp->dtls.ssl) {
2366 if (rtp->rtcp->dtls.ssl != ssl) {
2367 SSL_free(rtp->rtcp->dtls.ssl);
2369 rtp->rtcp->dtls.ssl = NULL;
2379 if (SSL_is_init_finished(rtp->dtls.ssl)) {
2380 SSL_shutdown(rtp->dtls.ssl);
2384 if (rtp->rtcp && SSL_is_init_finished(rtp->rtcp->dtls.ssl)) {
2385 SSL_shutdown(rtp->rtcp->dtls.ssl);
2395 return rtp->dtls.connection;
2403 return rtp->dtls.dtls_setup;
2432 if (old == *dtls_setup) {
2442 SSL_set_connect_state(ssl);
2444 SSL_set_accept_state(ssl);
2455 if (rtp->dtls.ssl) {
2456 dtls_set_setup(&rtp->dtls.dtls_setup, setup, rtp->dtls.ssl);
2459 if (rtp->rtcp && rtp->rtcp->dtls.ssl) {
2460 dtls_set_setup(&rtp->rtcp->dtls.dtls_setup, setup, rtp->rtcp->dtls.ssl);
2475 rtp->remote_hash = hash;
2477 while ((value = strsep(&tmp,
":")) && (pos != (EVP_MAX_MD_SIZE - 1))) {
2478 sscanf(value,
"%02hhx", &rtp->remote_fingerprint[pos++]);
2487 return rtp->local_hash;
2491 static const char *ast_rtp_dtls_get_fingerprint(
struct ast_rtp_instance *instance)
2495 return rtp->local_fingerprint;
2501 .active = ast_rtp_dtls_active,
2502 .stop = ast_rtp_dtls_stop,
2503 .reset = ast_rtp_dtls_reset,
2504 .get_connection = ast_rtp_dtls_get_connection,
2505 .get_setup = ast_rtp_dtls_get_setup,
2506 .set_setup = ast_rtp_dtls_set_setup,
2507 .set_fingerprint = ast_rtp_dtls_set_fingerprint,
2508 .get_fingerprint_hash = ast_rtp_dtls_get_fingerprint_hash,
2509 .get_fingerprint = ast_rtp_dtls_get_fingerprint,
2514 #ifdef TEST_FRAMEWORK
2548 static void set_rtp_rtcp_schedid(
struct ast_rtp_instance *instance,
int id)
2552 if (rtp && rtp->rtcp) {
2557 static struct ast_rtp_engine_test ast_rtp_test = {
2558 .packets_to_drop = 0,
2561 .recv_buffer_count = get_recv_buffer_count,
2562 .recv_buffer_max = get_recv_buffer_max,
2563 .send_buffer_count = get_send_buffer_count,
2564 .set_schedid = set_rtp_rtcp_schedid,
2594 #ifdef HAVE_PJPROJECT
2595 .ice = &ast_rtp_ice,
2597 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2598 .dtls = &ast_rtp_dtls,
2599 .activate = ast_rtp_activate,
2604 .set_stream_num = ast_rtp_set_stream_num,
2605 .extension_enable = ast_rtp_extension_enable,
2607 #ifdef TEST_FRAMEWORK
2608 .test = &ast_rtp_test,
2612 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2614 static void dtls_perform_handshake(
struct ast_rtp_instance *instance,
struct dtls_details *dtls,
int rtcp)
2618 ast_debug_dtls(3,
"(%p) DTLS perform handshake - ssl = %p, setup = %d\n",
2619 rtp, dtls->ssl, dtls->dtls_setup);
2629 SSL_do_handshake(dtls->ssl);
2639 dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
2643 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2644 static void dtls_perform_setup(
struct dtls_details *dtls)
2646 if (!dtls->ssl || !SSL_is_init_finished(dtls->ssl)) {
2650 SSL_clear(dtls->ssl);
2652 SSL_set_accept_state(dtls->ssl);
2654 SSL_set_connect_state(dtls->ssl);
2662 #ifdef HAVE_PJPROJECT
2666 static void ast_rtp_ice_start_media(pj_ice_sess *ice, pj_status_t status)
2673 if (status == PJ_SUCCESS) {
2690 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2693 ao2_unlock(instance);
2697 ast_debug_category(2, AST_DEBUG_CATEGORY_ICE | AST_DEBUG_CATEGORY_DTLS,
2698 "(%p) ICE starting media - perform DTLS - (%p)\n", instance, rtp);
2712 dtls_perform_handshake(instance, &rtp->dtls, 0);
2715 dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
2722 ao2_unlock(instance);
2726 ast_verb(4,
"%p -- Strict RTP learning after ICE completion\n", rtp);
2728 ao2_unlock(instance);
2731 #ifdef HAVE_PJPROJECT_ON_VALID_ICE_PAIR_CALLBACK
2733 static void ast_rtp_on_valid_pair(pj_ice_sess *ice)
2735 ast_debug_ice(2,
"(%p) ICE valid pair, start media\n", ice->user_data);
2736 ast_rtp_ice_start_media(ice, PJ_SUCCESS);
2741 static void ast_rtp_on_ice_complete(pj_ice_sess *ice, pj_status_t status)
2743 ast_debug_ice(2,
"(%p) ICE complete, start media\n", ice->user_data);
2744 ast_rtp_ice_start_media(ice, status);
2748 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)
2755 if (transport_id == TRANSPORT_SOCKET_RTP || transport_id == TRANSPORT_SOCKET_RTCP) {
2757 }
else if (transport_id == TRANSPORT_TURN_RTP) {
2759 }
else if (transport_id == TRANSPORT_TURN_RTCP) {
2765 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)
2769 pj_status_t status = PJ_EINVALIDOP;
2770 pj_ssize_t _size = (pj_ssize_t)size;
2772 if (transport_id == TRANSPORT_SOCKET_RTP) {
2774 status = pj_sock_sendto(rtp->s, pkt, &_size, 0, dst_addr, dst_addr_len);
2776 ast_assert(_size == size || status != PJ_SUCCESS);
2777 }
else if (transport_id == TRANSPORT_SOCKET_RTCP) {
2780 status = pj_sock_sendto(rtp->rtcp->
s, pkt, &_size, 0, dst_addr, dst_addr_len);
2782 ast_assert(_size == size || status != PJ_SUCCESS);
2784 status = PJ_SUCCESS;
2786 }
else if (transport_id == TRANSPORT_TURN_RTP) {
2789 status = pj_turn_sock_sendto(rtp->
turn_rtp, pkt, size, dst_addr, dst_addr_len);
2791 }
else if (transport_id == TRANSPORT_TURN_RTCP) {
2794 status = pj_turn_sock_sendto(rtp->
turn_rtcp, pkt, size, dst_addr, dst_addr_len);
2802 static pj_ice_sess_cb ast_rtp_ice_sess_cb = {
2803 #ifdef HAVE_PJPROJECT_ON_VALID_ICE_PAIR_CALLBACK
2804 .on_valid_pair = ast_rtp_on_valid_pair,
2806 .on_ice_complete = ast_rtp_on_ice_complete,
2807 .on_rx_data = ast_rtp_on_ice_rx_data,
2808 .on_tx_pkt = ast_rtp_on_ice_tx_pkt,
2816 if (pj_ioqueue_create(pool, 1, &ioqueue) != PJ_SUCCESS) {
2821 const pj_time_val delay = {0, 10};
2824 pj_ioqueue_poll(ioqueue, &delay);
2831 static inline int rtp_debug_test_addr(
struct ast_sockaddr *addr)
2833 if (!ast_debug_rtp_packet_is_allowed) {
2847 static inline int rtcp_debug_test_addr(
struct ast_sockaddr *addr)
2849 if (!ast_debug_rtcp_packet_is_allowed) {
2863 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
2865 static int dtls_srtp_handle_timeout(
struct ast_rtp_instance *instance,
int rtcp)
2868 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2869 struct timeval dtls_timeout;
2871 ast_debug_dtls(3,
"(%p) DTLS srtp - handle timeout - rtcp=%d\n", instance, rtcp);
2872 DTLSv1_handle_timeout(dtls->ssl);
2875 if (!DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
2876 dtls->timeout_timer = -1;
2880 return dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
2884 static int dtls_srtp_handle_rtp_timeout(
const void *data)
2890 reschedule = dtls_srtp_handle_timeout(instance, 0);
2891 ao2_unlock(instance);
2900 static int dtls_srtp_handle_rtcp_timeout(
const void *data)
2906 reschedule = dtls_srtp_handle_timeout(instance, 1);
2907 ao2_unlock(instance);
2917 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2918 struct timeval dtls_timeout;
2920 if (DTLSv1_get_timeout(dtls->ssl, &dtls_timeout)) {
2921 int timeout = dtls_timeout.tv_sec * 1000 + dtls_timeout.tv_usec / 1000;
2923 ast_assert(dtls->timeout_timer == -1);
2926 if ((dtls->timeout_timer =
ast_sched_add(rtp->sched, timeout,
2927 !rtcp ? dtls_srtp_handle_rtp_timeout : dtls_srtp_handle_rtcp_timeout, instance)) < 0) {
2929 ast_log(LOG_WARNING,
"Scheduling '%s' DTLS retransmission for RTP instance [%p] failed.\n",
2930 !rtcp ?
"RTP" :
"RTCP", instance);
2932 ast_debug_dtls(3,
"(%p) DTLS srtp - scheduled timeout timer for '%d'\n", instance, timeout);
2940 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2943 ast_debug_dtls(3,
"(%p) DTLS srtp - stopped timeout timer'\n", instance);
2947 static int dtls_srtp_renegotiate(
const void *data)
2955 SSL_renegotiate(rtp->dtls.ssl);
2956 SSL_do_handshake(rtp->dtls.ssl);
2958 if (rtp->rtcp && rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
2959 SSL_renegotiate(rtp->rtcp->dtls.ssl);
2960 SSL_do_handshake(rtp->rtcp->dtls.ssl);
2965 ao2_unlock(instance);
2971 static int dtls_srtp_add_local_ssrc(
struct ast_rtp *rtp,
struct ast_rtp_instance *instance,
int rtcp,
unsigned int ssrc,
int set_remote_policy)
2973 unsigned char material[SRTP_MASTER_LEN * 2];
2974 unsigned char *local_key, *local_salt, *remote_key, *remote_salt;
2977 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
2979 ast_debug_dtls(3,
"(%p) DTLS srtp - add local ssrc - rtcp=%d, set_remote_policy=%d'\n",
2980 instance, rtcp, set_remote_policy);
2983 if (!SSL_export_keying_material(dtls->ssl, material, SRTP_MASTER_LEN * 2,
"EXTRACTOR-dtls_srtp", 19, NULL, 0, 0)) {
2984 ast_log(LOG_WARNING,
"Unable to extract SRTP keying material from DTLS-SRTP negotiation on RTP instance '%p'\n",
2991 local_key = material;
2992 remote_key = local_key + SRTP_MASTER_KEY_LEN;
2993 local_salt = remote_key + SRTP_MASTER_KEY_LEN;
2994 remote_salt = local_salt + SRTP_MASTER_SALT_LEN;
2996 remote_key = material;
2997 local_key = remote_key + SRTP_MASTER_KEY_LEN;
2998 remote_salt = local_key + SRTP_MASTER_KEY_LEN;
2999 local_salt = remote_salt + SRTP_MASTER_SALT_LEN;
3002 if (!(local_policy = res_srtp_policy->alloc())) {
3006 if (res_srtp_policy->set_master_key(local_policy, local_key, SRTP_MASTER_KEY_LEN, local_salt, SRTP_MASTER_SALT_LEN) < 0) {
3007 ast_log(LOG_WARNING,
"Could not set key/salt information on local policy of '%p' when setting up DTLS-SRTP\n", rtp);
3011 if (res_srtp_policy->set_suite(local_policy, rtp->suite)) {
3012 ast_log(LOG_WARNING,
"Could not set suite to '%u' on local policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
3016 res_srtp_policy->set_ssrc(local_policy, ssrc, 0);
3018 if (set_remote_policy) {
3019 if (!(remote_policy = res_srtp_policy->alloc())) {
3023 if (res_srtp_policy->set_master_key(remote_policy, remote_key, SRTP_MASTER_KEY_LEN, remote_salt, SRTP_MASTER_SALT_LEN) < 0) {
3024 ast_log(LOG_WARNING,
"Could not set key/salt information on remote policy of '%p' when setting up DTLS-SRTP\n", rtp);
3028 if (res_srtp_policy->set_suite(remote_policy, rtp->suite)) {
3029 ast_log(LOG_WARNING,
"Could not set suite to '%u' on remote policy of '%p' when setting up DTLS-SRTP\n", rtp->suite, rtp);
3033 res_srtp_policy->set_ssrc(remote_policy, 0, 1);
3037 ast_log(LOG_WARNING,
"Could not set policies when setting up DTLS-SRTP on '%p'\n", rtp);
3045 res_srtp_policy->destroy(local_policy);
3047 if (remote_policy) {
3048 res_srtp_policy->destroy(remote_policy);
3056 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3059 ast_debug_dtls(3,
"(%p) DTLS setup SRTP rtp=%p'\n", instance, rtp);
3065 if (!(certificate = SSL_get_peer_certificate(dtls->ssl))) {
3066 ast_log(LOG_WARNING,
"No certificate was provided by the peer on RTP instance '%p'\n", instance);
3071 if (rtp->remote_fingerprint[0]) {
3073 unsigned char fingerprint[EVP_MAX_MD_SIZE];
3079 type = EVP_sha256();
3081 ast_log(LOG_WARNING,
"Unsupported fingerprint hash type on RTP instance '%p'\n", instance);
3085 if (!X509_digest(certificate, type, fingerprint, &size) ||
3087 memcmp(fingerprint, rtp->remote_fingerprint, size)) {
3088 X509_free(certificate);
3089 ast_log(LOG_WARNING,
"Fingerprint provided by remote party does not match that of peer certificate on RTP instance '%p'\n",
3095 X509_free(certificate);
3099 ast_log(LOG_ERROR,
"Failed to add local source '%p'\n", rtp);
3113 if ((rtp->rekeyid =
ast_sched_add(rtp->sched, rtp->rekey * 1000, dtls_srtp_renegotiate, instance)) < 0) {
3126 return elem - value;
3132 return elem == value;
3135 static int rtcp_mux(
struct ast_rtp *rtp,
const unsigned char *packet)
3145 version = (packet[0] & 0XC0) >> 6;
3160 m = packet[1] & 0x80;
3161 pt = packet[1] & 0x7F;
3162 if (m && pt >= 64 && pt <= 95) {
3173 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3176 #ifdef HAVE_PJPROJECT
3179 #ifdef TEST_FRAMEWORK
3180 struct ast_rtp_engine_test *
test = ast_rtp_instance_get_test(instance);
3183 if ((len =
ast_recvfrom(rtcp ? rtp->rtcp->
s : rtp->s, buf, size, flags, sa)) < 0) {
3187 #ifdef TEST_FRAMEWORK
3188 if (test && test->packets_to_drop > 0) {
3189 test->packets_to_drop--;
3194 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
3197 if ((*in >= 20) && (*in <= 63)) {
3198 struct dtls_details *dtls = !rtcp ? &rtp->dtls : &rtp->rtcp->dtls;
3203 ast_log(LOG_ERROR,
"Received SSL traffic on RTP instance '%p' without an SSL session\n",
3208 ast_debug_dtls(3,
"(%p) DTLS - __rtp_recvfrom rtp=%p - Got SSL packet '%d'\n", instance, rtp, *in);
3217 #ifdef HAVE_PJPROJECT
3219 int pass_src_check = 0;
3234 ast_log(LOG_WARNING,
"%s: DTLS packet from %s dropped. ICE not completed yet.\n",
3246 for (ix = 0; ix < rtp->
ice->
real_ice->rcand_cnt; ix++) {
3247 pj_ice_sess_cand *rcand = &rtp->
ice->
real_ice->rcand[ix];
3254 if (!pass_src_check) {
3255 ast_log(LOG_WARNING,
"%s: DTLS packet from %s dropped. Source not in ICE active candidate list.\n",
3272 ao2_unlock(instance);
3273 dtls_srtp_stop_timeout_timer(instance, rtp, rtcp);
3279 SSL_set_accept_state(dtls->ssl);
3282 BIO_write(dtls->read_bio, buf, len);
3284 len = SSL_read(dtls->ssl, buf, len);
3286 if ((len < 0) && (SSL_get_error(dtls->ssl, len) == SSL_ERROR_SSL)) {
3287 unsigned long error = ERR_get_error();
3288 ast_log(LOG_ERROR,
"DTLS failure occurred on RTP instance '%p' due to reason '%s', terminating\n",
3289 instance, ERR_reason_error_string(error));
3293 if (SSL_is_init_finished(dtls->ssl)) {
3297 if ((res = dtls_srtp_setup(rtp, instance, rtcp))) {
3301 res = RTP_DTLS_ESTABLISHED;
3303 ast_debug_dtls(3,
"(%p) DTLS - __rtp_recvfrom rtp=%p - established'\n", instance, rtp);
3306 dtls_srtp_start_timeout_timer(instance, rtp, rtcp);
3313 #ifdef HAVE_PJPROJECT
3323 }
else if (rtp->
ice) {
3331 pj_sockaddr_parse(pj_AF_UNSPEC(), 0, &combined, &address);
3336 ao2_unlock(instance);
3337 status = pj_ice_sess_on_rx_pkt(ice->
real_ice,
3338 rtcp ? AST_RTP_ICE_COMPONENT_RTCP : AST_RTP_ICE_COMPONENT_RTP,
3339 rtcp ? TRANSPORT_SOCKET_RTCP : TRANSPORT_SOCKET_RTP, buf, len, &address,
3340 pj_sockaddr_get_len(&address));
3343 if (status != PJ_SUCCESS) {
3346 pj_strerror(status, err_buf,
sizeof(err_buf));
3347 ast_log(LOG_WARNING,
"PJ ICE Rx error status code: %d '%s'.\n",
3348 (
int)status, err_buf);
3397 if (use_srtp && res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
3401 #ifdef HAVE_PJPROJECT
3402 if (transport_rtp->
ice) {
3408 if (rtcp && rtp->rtcp->
s == rtp->s) {
3409 component = AST_RTP_ICE_COMPONENT_RTP;
3415 ice = transport_rtp->
ice;
3417 if (instance == transport) {
3418 ao2_unlock(instance);
3420 status = pj_ice_sess_send_data(ice->
real_ice, component, temp, len);
3422 if (instance == transport) {
3425 if (status == PJ_SUCCESS) {
3432 res =
ast_sendto(rtcp ? transport_rtp->rtcp->
s : transport_rtp->s, temp, len, flags, sa);
3443 return __rtp_sendto(instance, buf, size, flags, sa, 1, ice, 1);
3453 if ((res =
__rtp_sendto(instance, buf, size, flags, sa, 0, ice, 1)) > 0) {
3463 unsigned int interval;
3470 static void calc_mean_and_standard_deviation(
double new_sample,
double *mean,
double *std_dev,
unsigned int *count)
3476 double last_sum_of_squares = (*std_dev) * (*std_dev) * (*count ?: 1);
3478 if (++(*count) == 0) {
3490 delta1 = new_sample - *mean;
3491 *mean += (delta1 / *
count);
3492 delta2 = new_sample - *mean;
3495 *std_dev = sqrt((last_sum_of_squares + (delta1 * delta2)) / *count);
3498 static int create_new_socket(
const char *type,
int af)
3503 ast_log(LOG_WARNING,
"Unable to allocate %s socket: %s\n", type, strerror(errno));
3509 setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums,
sizeof(nochecksums));
3541 static int rtp_learning_rtp_seq_update(
struct rtp_learning_info *info, uint16_t seq)
3543 if (seq == (uint16_t) (info->
max_seq + 1)) {
3555 case AST_MEDIA_TYPE_UNKNOWN:
3556 case AST_MEDIA_TYPE_AUDIO:
3571 case AST_MEDIA_TYPE_VIDEO:
3572 case AST_MEDIA_TYPE_IMAGE:
3573 case AST_MEDIA_TYPE_TEXT:
3574 case AST_MEDIA_TYPE_END:
3595 rtp_learning_seq_init(&rtp->rtp_source_learn, (uint16_t) rtp->
lastrxseqno);
3598 #ifdef HAVE_PJPROJECT
3607 ast_rwlock_wrlock(lock);
3609 ast_rwlock_unlock(lock);
3621 static int rtp_address_is_ice_blacklisted(
const struct ast_sockaddr *address)
3625 ast_rwlock_rdlock(&ice_acl_lock);
3627 ast_rwlock_unlock(&ice_acl_lock);
3644 static int stun_address_is_blacklisted(
const struct ast_sockaddr *addr)
3648 ast_rwlock_rdlock(&stun_acl_lock);
3650 ast_rwlock_unlock(&stun_acl_lock);
3659 unsigned int count = 0;
3660 struct ifaddrs *ifa, *ia;
3664 int af_inet_ok = 0, af_inet6_ok = 0;
3665 struct sockaddr_in stunaddr_copy;
3670 af_inet_ok = af_inet6_ok = 1;
3675 if (getifaddrs(&ifa) < 0) {
3677 ast_log(LOG_ERROR,
"(%p) ICE Error obtaining list of local addresses: %s\n",
3678 instance, strerror(errno));
3680 ast_debug_ice(2,
"(%p) ICE add system candidates\n", instance);
3684 for (ia = ifa; ia && count < PJ_ICE_MAX_CAND; ia = ia->ifa_next) {
3687 if (!ia->ifa_addr || (ia->ifa_flags & IFF_UP) == 0) {
3692 if (ia->ifa_addr->sa_family != AF_INET && ia->ifa_addr->sa_family != AF_INET6) {
3698 if (ia->ifa_addr->sa_family == AF_INET) {
3699 const struct sockaddr_in *sa_in = (
struct sockaddr_in*)ia->ifa_addr;
3707 if ((sa_in->sin_addr.s_addr & htonl(0xFF000000)) == htonl(0x7F000000)) {
3712 if ((sa_in->sin_addr.s_addr & htonl(0xFF000000)) == 0) {
3735 if (!rtp_address_is_ice_blacklisted(&candidate->advertised)) {
3737 pj_sockaddr_set_port(&pjtmp, port);
3739 PJ_ICE_CAND_TYPE_HOST, 65535, &pjtmp, &pjtmp, NULL,
3740 pj_sockaddr_get_len(&pjtmp));
3744 if (!candidate->include_local) {
3761 if (rtp_address_is_ice_blacklisted(&tmp)) {
3766 pj_sockaddr_set_port(&pjtmp, port);
3768 PJ_ICE_CAND_TYPE_HOST, 65535, &pjtmp, &pjtmp, NULL,
3769 pj_sockaddr_get_len(&pjtmp));
3775 ast_rwlock_rdlock(&stunaddr_lock);
3776 memcpy(&stunaddr_copy, &stunaddr,
sizeof(stunaddr));
3777 ast_rwlock_unlock(&stunaddr_lock);
3780 if (stunaddr_copy.sin_addr.s_addr && !stun_address_is_blacklisted(addr) &&
3782 count < PJ_ICE_MAX_CAND) {
3783 struct sockaddr_in answer;
3786 ast_debug_category(3, AST_DEBUG_CATEGORY_ICE | AST_DEBUG_CATEGORY_STUN,
3787 "(%p) ICE request STUN %s %s candidate\n", instance,
3788 transport == AST_TRANSPORT_UDP ?
"UDP" :
"TCP",
3789 component == AST_RTP_ICE_COMPONENT_RTP ?
"RTP" :
"RTCP");
3795 ao2_unlock(instance);
3797 ? rtp->rtcp->
s : rtp->s, &stunaddr_copy, NULL, &answer);
3801 pj_sockaddr ext, base;
3803 int srflx = 1, baseset = 0;
3806 pj_sockaddr_init(pj_AF_INET(), &ext, &mapped, ntohs(answer.sin_port));
3814 while (srflx && (candidate = ao2_iterator_next(&i))) {
3820 if (!pj_sockaddr_cmp(&candidate->
address, &ext)) {
3828 if (srflx && baseset) {
3829 pj_sockaddr_set_port(&base, port);
3831 PJ_ICE_CAND_TYPE_SRFLX, 65535, &ext, &base, &base,
3832 pj_sockaddr_get_len(&ext));
3838 if (pj_strlen(&turnaddr)) {
3840 pj_strbuf(&turnusername), pj_strbuf(&turnpassword));
3855 static unsigned int calc_txstamp(
struct ast_rtp *rtp,
struct timeval *delivery)
3862 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
3871 return (
unsigned int) ms;
3874 #ifdef HAVE_PJPROJECT
3890 int port,
int replace)
3892 pj_stun_config stun_config;
3893 pj_str_t ufrag, passwd;
3903 ast_debug_ice(2,
"(%p) ICE create%s\n", instance, replace ?
" and replace" :
"");
3914 if (!stun_software_attribute) {
3915 stun_config.software_name = pj_str(NULL);
3922 ao2_unlock(instance);
3924 status = pj_ice_sess_create(&stun_config, NULL, PJ_ICE_SESS_ROLE_UNKNOWN,
3927 if (status == PJ_SUCCESS) {
3929 real_ice->user_data = instance;
3934 ao2_unlock(instance);
3941 TRANSPORT_SOCKET_RTP);
3949 TRANSPORT_SOCKET_RTCP);
3969 int x, startplace, i, maxloops;
3975 create_new_socket(
"RTP",
3978 ast_log(LOG_WARNING,
"Failed to create a new socket for RTP instance '%p'\n", instance);
3990 for (i = 0; i <= maxloops; i++) {
3994 ast_debug_rtp(1,
"(%p) RTP allocated port %d\n", instance, x);
4002 x = (rtpstart + 1) & ~1;
4006 if (x == startplace || (errno != EADDRINUSE && errno != EACCES)) {
4007 ast_log(LOG_ERROR,
"Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
4014 #ifdef HAVE_PJPROJECT
4016 ast_cond_init(&rtp->
cond, NULL);
4024 ast_debug_ice(2,
"(%p) ICE creating session %s (%d)\n", instance,
4027 ast_log(LOG_NOTICE,
"(%p) ICE failed to create session\n", instance);
4035 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
4037 rtp->dtls.timeout_timer = -1;
4045 int saved_rtp_s = rtp->s;
4046 #ifdef HAVE_PJPROJECT
4048 struct timespec ts = { .tv_sec = wait.tv_sec, .tv_nsec = wait.tv_usec * 1000, };
4051 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
4052 ast_rtp_dtls_stop(instance);
4062 if (rtp->rtcp && rtp->rtcp->
s > -1) {
4063 if (saved_rtp_s != rtp->rtcp->
s) {
4064 close(rtp->rtcp->
s);
4069 #ifdef HAVE_PJPROJECT
4081 ao2_unlock(instance);
4082 pj_turn_sock_destroy(rtp->
turn_rtp);
4084 while (rtp->
turn_state != PJ_TURN_STATE_DESTROYING) {
4095 ao2_unlock(instance);
4098 while (rtp->
turn_state != PJ_TURN_STATE_DESTROYING) {
4104 ast_debug_ice(2,
"(%p) ICE RTP transport deallocating\n", instance);
4130 ao2_unlock(instance);
4149 rtp->
owner = instance;
4151 rtp->
ssrc = ast_random();
4153 rtp->
seqno = ast_random() & 0x7fff;
4162 if (rtp_allocate_transport(instance, rtp)) {
4192 #define SSRC_MAPPING_ELEM_CMP(elem, value) ((elem).instance == (value))
4203 ao2_unlock(instance);
4214 rtp_deallocate_transport(instance, rtp);
4217 if (rtp->smoother) {
4218 ast_smoother_free(rtp->smoother);
4228 ast_free(rtp->rtcp->local_addr_str);
4229 ast_free(rtp->rtcp);
4234 ao2_unlock(instance);
4253 ao2_cleanup(rtp->lasttxformat);
4254 ao2_cleanup(rtp->lastrxformat);
4286 int hdrlen = 12, res = 0, i = 0, payload = 101;
4287 unsigned int sample_rate = 8000;
4289 unsigned int *rtpheader = (
unsigned int*)data;
4300 if ((digit <=
'9') && (digit >=
'0')) {
4302 }
else if (digit ==
'*') {
4304 }
else if (digit ==
'#') {
4306 }
else if ((digit >=
'A') && (digit <=
'D')) {
4307 digit = digit -
'A' + 12;
4308 }
else if ((digit >=
'a') && (digit <=
'd')) {
4309 digit = digit -
'a' + 12;
4311 ast_log(LOG_WARNING,
"Don't know how to represent '%c'\n", digit);
4318 if (payload_format) {
4331 if (payload == -1) {
4332 sample_rate = DEFAULT_DTMF_SAMPLE_RATE_MS;
4336 if (payload == -1) {
4341 ast_debug(1,
"Sending digit '%d' at rate %d with payload %d\n", digit, sample_rate, payload);
4344 rtp->send_duration = 160;
4347 rtp->lastdigitts = rtp->lastts + rtp->send_duration;
4350 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->
seqno));
4351 rtpheader[1] = htonl(rtp->lastdigitts);
4352 rtpheader[2] = htonl(rtp->
ssrc);
4355 for (i = 0; i < 2; i++) {
4358 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
4359 res =
rtp_sendto(instance, (
void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4361 ast_log(LOG_ERROR,
"RTP Transmission error to %s: %s\n",
4365 if (rtp_debug_test_addr(&remote_address)) {
4366 ast_verbose(
"Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4368 ice ?
" (via ICE)" :
"",
4369 payload, rtp->
seqno, rtp->lastdigitts, res - hdrlen);
4372 rtp->send_duration += 160;
4373 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->
seqno));
4379 rtp->send_payload = payload;
4389 int hdrlen = 12, res = 0;
4391 unsigned int *rtpheader = (
unsigned int*)data;
4402 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->
seqno));
4403 rtpheader[1] = htonl(rtp->lastdigitts);
4404 rtpheader[2] = htonl(rtp->
ssrc);
4405 rtpheader[3] = htonl((rtp->
send_digit << 24) | (0xa << 16) | (rtp->send_duration));
4408 res =
rtp_sendto(instance, (
void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4410 ast_log(LOG_ERROR,
"RTP Transmission error to %s: %s\n",
4415 if (rtp_debug_test_addr(&remote_address)) {
4416 ast_verbose(
"Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4418 ice ?
" (via ICE)" :
"",
4419 rtp->send_payload, rtp->
seqno, rtp->lastdigitts, res - hdrlen);
4424 rtp->send_duration += 160;
4435 int hdrlen = 12, res = -1, i = 0;
4437 unsigned int *rtpheader = (
unsigned int*)data;
4438 unsigned int measured_samples;
4448 if ((digit <=
'9') && (digit >=
'0')) {
4450 }
else if (digit ==
'*') {
4452 }
else if (digit ==
'#') {
4454 }
else if ((digit >=
'A') && (digit <=
'D')) {
4455 digit = digit -
'A' + 12;
4456 }
else if ((digit >=
'a') && (digit <=
'd')) {
4457 digit = digit -
'a' + 12;
4459 ast_log(LOG_WARNING,
"Don't know how to represent '%c'\n", digit);
4466 ast_debug_rtp(2,
"(%p) RTP adjusting final end duration from %d to %u\n",
4467 instance, rtp->send_duration, measured_samples);
4468 rtp->send_duration = measured_samples;
4472 rtpheader[1] = htonl(rtp->lastdigitts);
4473 rtpheader[2] = htonl(rtp->
ssrc);
4474 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
4475 rtpheader[3] |= htonl((1 << 23));
4478 for (i = 0; i < 3; i++) {
4481 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->
seqno));
4483 res =
rtp_sendto(instance, (
void *) rtpheader, hdrlen + 4, 0, &remote_address, &ice);
4486 ast_log(LOG_ERROR,
"RTP Transmission error to %s: %s\n",
4491 if (rtp_debug_test_addr(&remote_address)) {
4492 ast_verbose(
"Sent RTP DTMF packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
4494 ice ?
" (via ICE)" :
"",
4495 rtp->send_payload, rtp->
seqno, rtp->lastdigitts, res - hdrlen);
4506 if (rtp->smoother) {
4507 ast_smoother_free(rtp->smoother);
4508 rtp->smoother = NULL;
4532 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
4533 ast_debug_rtp(3,
"(%p) RTP setting the marker bit due to a source update\n", instance);
4544 unsigned int ssrc = ast_random();
4548 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
4551 ast_debug_rtp(3,
"(%p) RTP changing ssrc from %u to %u due to a source change\n",
4552 instance, rtp->
ssrc, ssrc);
4555 ast_debug_rtp(3,
"(%p) RTP changing ssrc for SRTP from %u to %u\n",
4556 instance, rtp->
ssrc, ssrc);
4557 res_srtp->change_source(srtp, rtp->
ssrc, ssrc);
4558 if (rtcp_srtp != srtp) {
4559 res_srtp->change_source(rtcp_srtp, rtp->
ssrc, ssrc);
4571 static void timeval2ntp(
struct timeval tv,
unsigned int *msw,
unsigned int *lsw)
4573 unsigned int sec, usec, frac;
4574 sec = tv.tv_sec + 2208988800u;
4595 frac = ((((usec << 12) / 125) << 7) / 125) << 7;
4600 static void ntp2timeval(
unsigned int msw,
unsigned int lsw,
struct timeval *tv)
4602 tv->tv_sec = msw - 2208988800u;
4604 tv->tv_usec = ((((lsw >> 7) * 125) >> 7) * 125) >> 12;
4607 static void calculate_lost_packet_statistics(
struct ast_rtp *rtp,
4608 unsigned int *lost_packets,
4611 unsigned int extended_seq_no;
4612 unsigned int expected_packets;
4613 unsigned int expected_interval;
4614 unsigned int received_interval;
4619 expected_packets = extended_seq_no - rtp->
seedrxseqno + 1;
4620 if (rtp->
rxcount > expected_packets) {
4621 expected_packets += rtp->
rxcount - expected_packets;
4623 *lost_packets = expected_packets - rtp->
rxcount;
4624 expected_interval = expected_packets - rtp->rtcp->
expected_prior;
4626 if (received_interval > expected_interval) {
4632 expected_interval = received_interval;
4634 lost_interval = expected_interval - received_interval;
4635 if (expected_interval == 0 || lost_interval <= 0) {
4638 *fraction_lost = (lost_interval << 8) / expected_interval;
4651 if (lost_interval <= 0) {
4654 rtp->rtcp->
rxlost = lost_interval;
4659 if (lost_interval && lost_interval < rtp->rtcp->minrxlost) {
4662 if (lost_interval > rtp->rtcp->
maxrxlost) {
4670 static int ast_rtcp_generate_report(
struct ast_rtp_instance *instance,
unsigned char *rtcpheader,
4676 unsigned int now_lsw;
4677 unsigned int now_msw;
4678 unsigned int lost_packets;
4680 struct timeval dlsr = { 0, };
4683 if (!rtp || !rtp->rtcp) {
4699 calculate_lost_packet_statistics(rtp, &lost_packets, &fraction_lost);
4704 update_local_mes_stats(rtp);
4706 gettimeofday(&now, NULL);
4707 rtcp_report->reception_report_count = rtp->
themssrc_valid ? 1 : 0;
4708 rtcp_report->ssrc = rtp->
ssrc;
4711 rtcp_report->sender_information.ntp_timestamp = now;
4712 rtcp_report->sender_information.rtp_timestamp = rtp->lastts;
4713 rtcp_report->sender_information.packet_count = rtp->
txcount;
4714 rtcp_report->sender_information.octet_count = rtp->
txoctetcount;
4718 report_block =
ast_calloc(1,
sizeof(*report_block));
4719 if (!report_block) {
4724 report_block->source_ssrc = rtp->
themssrc;
4725 report_block->lost_count.fraction = (fraction_lost & 0xff);
4726 report_block->lost_count.packets = (lost_packets & 0xffffff);
4729 report_block->lsr = rtp->rtcp->
themrxlsr;
4732 timersub(&now, &rtp->rtcp->
rxlsr, &dlsr);
4733 report_block->dlsr = (((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000;
4736 timeval2ntp(rtcp_report->sender_information.ntp_timestamp, &now_msw, &now_lsw);
4737 put_unaligned_uint32(rtcpheader + 4, htonl(rtcp_report->ssrc));
4740 put_unaligned_uint32(rtcpheader + len, htonl(now_msw));
4741 put_unaligned_uint32(rtcpheader + len + 4, htonl(now_lsw));
4742 put_unaligned_uint32(rtcpheader + len + 8, htonl(rtcp_report->sender_information.rtp_timestamp));
4743 put_unaligned_uint32(rtcpheader + len + 12, htonl(rtcp_report->sender_information.packet_count));
4744 put_unaligned_uint32(rtcpheader + len + 16, htonl(rtcp_report->sender_information.octet_count));
4748 put_unaligned_uint32(rtcpheader + len, htonl(report_block->source_ssrc));
4749 put_unaligned_uint32(rtcpheader + len + 4, htonl((report_block->lost_count.fraction << 24) | report_block->lost_count.packets));
4750 put_unaligned_uint32(rtcpheader + len + 8, htonl(report_block->highest_seq_no));
4751 put_unaligned_uint32(rtcpheader + len + 12, htonl(report_block->ia_jitter));
4752 put_unaligned_uint32(rtcpheader + len + 16, htonl(report_block->lsr));
4753 put_unaligned_uint32(rtcpheader + len + 20, htonl(report_block->dlsr));
4757 put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (rtcp_report->reception_report_count << 24)
4763 static int ast_rtcp_calculate_sr_rr_statistics(
struct ast_rtp_instance *instance,
4770 if (!rtp || !rtp->rtcp) {
4785 rtp->rtcp->
txlsr = rtcp_report->sender_information.ntp_timestamp;
4792 if (rtcp_debug_test_addr(&rtp->rtcp->
them)) {
4793 ast_verbose(
"* Sent RTCP %s to %s%s\n", sr ?
"SR" :
"RR",
4795 ast_verbose(
" Our SSRC: %u\n", rtcp_report->ssrc);
4797 ast_verbose(
" Sent(NTP): %u.%06u\n",
4798 (
unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
4799 (
unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec);
4800 ast_verbose(
" Sent(RTP): %u\n", rtcp_report->sender_information.rtp_timestamp);
4801 ast_verbose(
" Sent packets: %u\n", rtcp_report->sender_information.packet_count);
4802 ast_verbose(
" Sent octets: %u\n", rtcp_report->sender_information.octet_count);
4806 ast_verbose(
" Report block:\n");
4807 ast_verbose(
" Their SSRC: %u\n", report_block->source_ssrc);
4808 ast_verbose(
" Fraction lost: %d\n", report_block->lost_count.fraction);
4809 ast_verbose(
" Cumulative loss: %u\n", report_block->lost_count.packets);
4810 ast_verbose(
" Highest seq no: %u\n", report_block->highest_seq_no);
4811 ast_verbose(
" IA jitter (samp): %u\n", report_block->ia_jitter);
4812 ast_verbose(
" IA jitter (secs): %.6f\n",
ast_samp2sec(report_block->ia_jitter, rate));
4813 ast_verbose(
" Their last SR: %u\n", report_block->lsr);
4814 ast_verbose(
" DLSR: %4.4f (sec)\n\n", (
double)(report_block->dlsr / 65536.0));
4820 "from", rtp->rtcp->local_addr_str,
4824 rtcp_report, message_blob);
4829 static int ast_rtcp_generate_sdes(
struct ast_rtp_instance *instance,
unsigned char *rtcpheader,
4834 uint16_t sdes_packet_len_bytes;
4835 uint16_t sdes_packet_len_rounded;
4837 if (!rtp || !rtp->rtcp) {
4849 sdes_packet_len_bytes =
4858 sdes_packet_len_rounded = (sdes_packet_len_bytes + 3) & ~0x3;
4860 put_unaligned_uint32(rtcpheader, htonl((2 << 30) | (1 << 24) | (
RTCP_PT_SDES << 16) | ((sdes_packet_len_rounded / 4) - 1)));
4861 put_unaligned_uint32(rtcpheader + 4, htonl(rtcp_report->ssrc));
4862 rtcpheader[8] = 0x01;
4863 rtcpheader[9] = AST_UUID_STR_LEN - 1;
4864 memcpy(rtcpheader + 10, rtp->
cname, AST_UUID_STR_LEN);
4865 len += 10 + AST_UUID_STR_LEN;
4877 len += (sdes_packet_len_rounded - sdes_packet_len_bytes);
4887 static int ast_rtcp_generate_compound_prefix(
struct ast_rtp_instance *instance,
unsigned char *rtcpheader,
4898 res = ast_rtcp_generate_report(instance, rtcpheader, report, sr);
4900 if (res == 0 || res == 1) {
4901 ast_debug_rtcp(1,
"(%p) RTCP failed to generate %s report!\n", instance, sr ?
"SR" :
"RR");
4907 res = ast_rtcp_generate_sdes(instance, rtcpheader + packet_len, report);
4909 if (res == 0 || res == 1) {
4910 ast_debug_rtcp(1,
"(%p) RTCP failed to generate SDES!\n", instance);
4914 return packet_len + res;
4917 static int ast_rtcp_generate_nack(
struct ast_rtp_instance *instance,
unsigned char *rtcpheader)
4923 unsigned int fci = 0;
4924 size_t remaining_missing_seqno;
4926 if (!rtp || !rtp->rtcp) {
4939 if (!remaining_missing_seqno) {
4946 while (remaining_missing_seqno) {
4956 if (missing_seqno) {
4958 if (blp_index >= 17) {
4959 put_unaligned_uint32(rtcpheader + packet_len, htonl(fci));
4965 if (blp_index == 0) {
4966 fci |= (current_seqno << 16);
4968 fci |= (1 << (blp_index - 1));
4972 remaining_missing_seqno--;
4982 put_unaligned_uint32(rtcpheader + packet_len, htonl(fci));
4988 put_unaligned_uint32(rtcpheader + 4, htonl(rtp->
ssrc));
4989 put_unaligned_uint32(rtcpheader + 8, htonl(rtp->
themssrc));
5011 unsigned char *rtcpheader;
5012 unsigned char bdata[AST_UUID_STR_LEN + 128] =
"";
5015 if (!rtp || !rtp->rtcp || rtp->rtcp->
schedid == -1) {
5023 res = ast_rtcp_generate_compound_prefix(instance, rtcpheader, rtcp_report, &sr);
5025 if (res == 0 || res == 1) {
5037 res =
rtcp_sendto(instance, (
unsigned int *)rtcpheader, packet_len, 0, &remote_address, &ice);
5039 ast_log(LOG_ERROR,
"RTCP %s transmission error to %s, rtcp halted %s\n",
5045 ast_rtcp_calculate_sr_rr_statistics(instance, rtcp_report, remote_address, ice, sr);
5049 ao2_unlock(instance);
5062 static void put_unaligned_time24(
void *p, uint32_t time_msw, uint32_t time_lsw)
5064 unsigned char *cp = p;
5068 datum = (time_msw << 18) & 0x00fc0000;
5069 datum |= (time_lsw >> 14) & 0x0003ffff;
5071 cp[0] = datum >> 16;
5081 unsigned int ms = calc_txstamp(rtp, &frame->
delivery);
5085 #ifdef TEST_FRAMEWORK
5086 struct ast_rtp_engine_test *
test = ast_rtp_instance_get_test(instance);
5097 #ifdef TEST_FRAMEWORK
5098 if (test && test->send_report) {
5099 test->send_report = 0;
5106 pred = rtp->lastts + frame->
samples;
5109 rtp->lastts = rtp->lastts + ms * rate;
5116 ast_debug_rtp(3,
"(%p) RTP audio difference is %d, ms is %u\n",
5117 instance, abs((
int)rtp->lastts - pred), ms);
5123 pred = rtp->lastovidtimestamp + frame->
samples;
5125 rtp->lastts = rtp->lastts + ms * 90;
5128 if (abs((
int)rtp->lastts - pred) < 7200) {
5130 rtp->lastovidtimestamp += frame->
samples;
5132 ast_debug_rtp(3,
"(%p) RTP video difference is %d, ms is %u (%u), pred/ts/samples %u/%d/%d\n",
5133 instance, abs((
int)rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->
samples);
5134 rtp->lastovidtimestamp = rtp->lastts;
5138 pred = rtp->lastotexttimestamp + frame->
samples;
5140 rtp->lastts = rtp->lastts + ms;
5143 if (abs((
int)rtp->lastts - pred) < 7200) {
5145 rtp->lastotexttimestamp += frame->
samples;
5147 ast_debug_rtp(3,
"(%p) RTP other difference is %d, ms is %u, pred/ts/samples %u/%d/%d\n",
5148 instance, abs((
int)rtp->lastts - pred), ms, rtp->lastts, pred, frame->
samples);
5149 rtp->lastotexttimestamp = rtp->lastts;
5155 if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
5157 ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
5161 if (rtp->lastts > rtp->lastdigitts) {
5162 rtp->lastdigitts = rtp->lastts;
5179 if (abs(difference) > 100) {
5184 seqno += difference;
5186 if (difference >= 0) {
5189 rtp->
seqno += difference;
5200 rtp->lastts = frame->
ts * rate;
5211 int abs_send_time_id;
5213 unsigned char *rtpheader;
5217 if (abs_send_time_id != -1) {
5223 packet_len = frame->
datalen + hdrlen;
5224 rtpheader = (
unsigned char *)(frame->
data.ptr - hdrlen);
5226 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (ext << 28) | (codec << 16) | (seqno) | (mark << 23)));
5227 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
5228 put_unaligned_uint32(rtpheader + 8, htonl(rtp->
ssrc));
5233 if (abs_send_time_id != -1) {
5234 unsigned int now_msw;
5235 unsigned int now_lsw;
5240 put_unaligned_uint32(rtpheader + 12, htonl((0xBEDE << 16) | 1));
5241 rtpheader[16] = (abs_send_time_id << 4) | 2;
5243 timeval2ntp(
ast_tvnow(), &now_msw, &now_lsw);
5244 put_unaligned_time24(rtpheader + 17, now_msw, now_lsw);
5251 payload =
ast_malloc(
sizeof(*payload) + packet_len);
5253 payload->
size = packet_len;
5254 memcpy(payload->
buf, rtpheader, packet_len);
5261 res =
rtp_sendto(instance, (
void *)rtpheader, packet_len, 0, &remote_address, &ice);
5264 ast_debug_rtp(1,
"(%p) RTP transmission error of packet %d to %s: %s\n",
5265 instance, rtp->
seqno,
5268 }
else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || ast_debug_rtp_packet_is_allowed) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
5270 if (ast_debug_rtp_packet_is_allowed)
5271 ast_debug(0,
"(%p) RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
5273 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
5276 if (rtp->rtcp && rtp->rtcp->
schedid < 0) {
5283 ast_log(LOG_WARNING,
"scheduling RTCP transmission failed.\n");
5288 if (rtp_debug_test_addr(&remote_address)) {
5289 ast_verbose(
"Sent RTP packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
5291 ice ?
" (via ICE)" :
"",
5292 codec, rtp->
seqno, rtp->lastts, res - hdrlen);
5300 if (seqno == rtp->
seqno) {
5315 for (i = 1; i < red->
num_gen+1; i++)
5318 memmove(&data[red->hdrlen], &data[red->hdrlen+red->
len[0]], len);
5322 for (i = 0; i < red->
num_gen; i++)
5323 red->
len[i] = red->
len[i+1];
5328 for (i = 0; i < red->
num_gen; i++) {
5329 len += data[i*4+3] = red->
len[i];
5349 unsigned char *rtcpheader;
5350 unsigned char bdata[1024];
5358 if (!rtp || !rtp->rtcp) {
5375 rtp->rtcp->firseq++;
5376 if(rtp->rtcp->firseq == 256) {
5377 rtp->rtcp->firseq = 0;
5384 res = ast_rtcp_generate_compound_prefix(instance, rtcpheader, rtcp_report, &sr);
5386 if (res == 0 || res == 1) {
5387 ao2_unlock(instance);
5393 put_unaligned_uint32(rtcpheader + packet_len + 0, htonl((2 << 30) | (4 << 24) | (
RTCP_PT_PSFB << 16) | ((fir_len/4)-1)));
5394 put_unaligned_uint32(rtcpheader + packet_len + 4, htonl(rtp->
ssrc));
5395 put_unaligned_uint32(rtcpheader + packet_len + 8, htonl(rtp->
themssrc));
5396 put_unaligned_uint32(rtcpheader + packet_len + 12, htonl(rtp->
themssrc));
5397 put_unaligned_uint32(rtcpheader + packet_len + 16, htonl(rtp->rtcp->firseq << 24));
5398 res =
rtcp_sendto(instance, (
unsigned int *)rtcpheader, packet_len + fir_len, 0, rtp->
bundled ? remote_address : &rtp->rtcp->
them, &ice);
5400 ast_log(LOG_ERROR,
"RTCP FIR transmission error: %s\n", strerror(errno));
5402 ast_rtcp_calculate_sr_rr_statistics(instance, rtcp_report, rtp->
bundled ? *remote_address : rtp->rtcp->
them, ice, sr);
5405 ao2_unlock(instance);
5411 unsigned char *rtcpheader;
5412 unsigned char bdata[1024];
5421 ast_debug_rtcp(1,
"(%p) RTCP provided feedback frame of format %d to write, but only REMB is supported\n",
5422 instance, feedback->
fmt);
5426 if (!rtp || !rtp->rtcp) {
5432 ast_debug_rtcp(1,
"(%p) RTCP provided feedback REMB report to write, but REMB support not enabled\n",
5448 res = ast_rtcp_generate_compound_prefix(instance, rtcpheader, rtcp_report, &sr);
5450 if (res == 0 || res == 1) {
5451 ao2_unlock(instance);
5458 put_unaligned_uint32(rtcpheader + packet_len + 4, htonl(rtp->
ssrc));
5459 put_unaligned_uint32(rtcpheader + packet_len + 8, htonl(0));
5460 put_unaligned_uint32(rtcpheader + packet_len + 12, htonl((
'R' << 24) | (
'E' << 16) | (
'M' << 8) | (
'B')));
5461 put_unaligned_uint32(rtcpheader + packet_len + 16, htonl((1 << 24) | (feedback->
remb.
br_exp << 18) | (feedback->
remb.
br_mantissa)));
5462 put_unaligned_uint32(rtcpheader + packet_len + 20, htonl(rtp->
ssrc));
5463 res =
rtcp_sendto(instance, (
unsigned int *)rtcpheader, packet_len + remb_len, 0, rtp->
bundled ? remote_address : &rtp->rtcp->
them, &ice);
5465 ast_log(LOG_ERROR,
"RTCP PSFB transmission error: %s\n", strerror(errno));
5467 ast_rtcp_calculate_sr_rr_statistics(instance, rtcp_report, rtp->
bundled ? *remote_address : rtp->rtcp->
them, ice, sr);
5470 ao2_unlock(instance);
5485 ast_debug_rtp(1,
"(%p) RTP no remote address on instance, so dropping frame\n", instance);
5491 rtp_write_rtcp_fir(instance, rtp, &remote_address);
5495 rtp_write_rtcp_psfb(instance, rtp, frame, &remote_address);
5502 ast_debug_rtp(1,
"(%p) RTP received frame with no data for instance, so dropping frame\n", instance);
5508 ast_log(LOG_WARNING,
"RTP can only send voice, video, and text\n");
5515 if ((frame = red_t140_to_red(rtp->red)) == NULL)
5523 ast_log(LOG_WARNING,
"Don't know how to send format %s packets with RTP\n",
5534 ast_debug_rtp(1,
"(%s) RTP ooh, format changed from %s to %s\n",
5539 if (rtp->smoother) {
5540 ast_smoother_free(rtp->smoother);
5541 rtp->smoother = NULL;
5550 if (!framing_ms && (smoother_flags & AST_SMOOTHER_FLAG_FORCED)) {
5556 if (!rtp->smoother) {
5557 ast_log(LOG_WARNING,
"Unable to create smoother: format %s ms: %u len: %u\n",
5561 ast_smoother_set_flags(rtp->smoother, smoother_flags);
5566 if (rtp->smoother) {
5569 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
5570 ast_smoother_feed_be(rtp->smoother, frame);
5572 ast_smoother_feed(rtp->smoother, frame);
5575 while ((f = ast_smoother_read(rtp->smoother)) && (f->
data.ptr)) {
5582 if (frame->
offset < hdrlen) {
5599 static void calc_rxstamp_and_jitter(
struct timeval *tv,
5600 struct ast_rtp *rtp,
unsigned int rx_rtp_ts,
5605 double jitter = 0.0;
5606 double prev_jitter = 0.0;
5611 unsigned int arrival;
5615 gettimeofday(&now,NULL);
5617 if (rtp->
rxcount == 1 || mark) {
5634 rtp->rxcore =
ast_tvsub(rtp->rxcore, tmp);
5635 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
5639 "Seed ts: %u current time: %f\n",
5681 "pkt: %5u Stable Seed ts: %u current time: %f\n",
5697 ast_debug_rtcp(3,
"%s: Current packet seq %d != last packet seq %d + 1. Ignoring\n",
5737 transit = arrival - rx_rtp_ts;
5745 jitter = (1.0/16.0) * (((double)d) - prev_jitter);
5754 "Arrival sec: %7.3f Arrival ts: %10u RX ts: %10u "
5755 "Transit samp: %6d Last transit samp: %6d d: %4d "
5756 "Curr jitter: %7.0f(%7.3f) Prev Jitter: %7.0f(%7.3f) New Jitter: %7.0f(%7.3f)\n",
5786 calc_mean_and_standard_deviation(rtp->
rxjitter,
5802 ast_debug_rtp(1,
"(%p) RTP ignore potential DTMF echo from '%s'\n",
5805 rtp->dtmfsamples = 0;
5811 rtp->dtmfsamples = 0;
5815 if (rtp->
resp ==
'X') {
5821 ast_debug_rtp(1,
"(%p) RTP creating %s DTMF Frame: %d (%c), at %s\n",
5837 static void process_dtmf_rfc2833(
struct ast_rtp_instance *instance,
unsigned char *data,
int len,
unsigned int seqno,
unsigned int timestamp,
int payloadtype,
int mark,
struct frame_list *frames)
5841 unsigned int event, event_end, samples;
5848 event = ntohl(*((
unsigned int *)(data)));
5850 event_end = ntohl(*((
unsigned int *)(data)));
5853 samples = ntohl(*((
unsigned int *)(data)));
5856 if (rtp_debug_test_addr(&remote_address)) {
5857 ast_verbose(
"Got RTP RFC2833 from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6d, mark %d, event %08x, end %d, duration %-5.5u) \n",
5859 payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
5863 if (ast_debug_rtp_packet_is_allowed)
5864 ast_debug(0,
"- RTP 2833 Event: %08x (len = %d)\n", event, len);
5869 }
else if (event < 11) {
5871 }
else if (event < 12) {
5873 }
else if (event < 16) {
5874 resp =
'A' + (
event - 12);
5875 }
else if (event < 17) {
5879 ast_debug_rtp(1,
"(%p) RTP ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", instance, event);
5900 unsigned int last_duration = new_duration & 0xFFFF;
5902 if (last_duration > 64000 && samples < last_duration) {
5903 new_duration += 0xFFFF + 1;
5905 new_duration = (new_duration & ~0xFFFF) | samples;
5907 if (event_end & 0x80) {
5919 }
else if (ast_debug_rtp_packet_is_allowed) {
5920 ast_debug_rtp(1,
"(%p) RTP dropping duplicate or out of order DTMF END frame (seqno: %u, ts %u, digit %c)\n",
5921 instance, seqno, timestamp, resp);
5932 && timestamp <= rtp->last_end_timestamp.ts)) {
5937 if (ast_debug_rtp_packet_is_allowed) {
5938 ast_debug(0,
"Dropping out of order DTMF frame (seqno %u, ts %u, digit %c)\n",
5939 seqno, timestamp, resp);
5944 if (rtp->
resp && rtp->
resp != resp) {
5975 static struct ast_frame *process_dtmf_cisco(
struct ast_rtp_instance *instance,
unsigned char *data,
int len,
unsigned int seqno,
unsigned int timestamp,
int payloadtype,
int mark)
5978 unsigned int event, flags, power;
6020 event = data[3] & 0x1f;
6022 if (ast_debug_rtp_packet_is_allowed)
6023 ast_debug(0,
"Cisco DTMF Digit: %02x (len=%d, seq=%d, flags=%02x, power=%u, history count=%d)\n", event, len, seq, flags, power, (len - 4) / 2);
6026 }
else if (event < 11) {
6028 }
else if (event < 12) {
6030 }
else if (event < 16) {
6031 resp =
'A' + (
event - 12);
6032 }
else if (event < 17) {
6035 if ((!rtp->
resp && power) || (rtp->
resp && (rtp->
resp != resp))) {
6040 rtp->dtmfsamples = 0;
6042 }
else if ((rtp->
resp == resp) && !power) {
6046 }
else if (rtp->
resp == resp) {
6055 static struct ast_frame *process_cn_rfc3389(
struct ast_rtp_instance *instance,
unsigned char *data,
int len,
unsigned int seqno,
unsigned int timestamp,
int payloadtype,
int mark)
6062 if (ast_debug_rtp_packet_is_allowed) {
6063 ast_debug(0,
"- RTP 3389 Comfort noise event: Format %s (len = %d)\n",
6067 if (!ast_test_flag(rtp, FLAG_3389_WARNING)) {
6072 ast_log(LOG_NOTICE,
"Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client address: %s\n",
6074 ast_set_flag(rtp, FLAG_3389_WARNING);
6085 memcpy(rtp->
f.
data.ptr, data + 1, len - 1);
6087 rtp->
f.
data.ptr = NULL;
6099 static int update_rtt_stats(
struct ast_rtp *rtp,
unsigned int lsr,
unsigned int dlsr)
6102 struct timeval rtt_tv;
6105 unsigned int rtt_msw;
6106 unsigned int rtt_lsw;
6110 gettimeofday(&now, NULL);
6111 timeval2ntp(now, &msw, &lsw);
6113 lsr_a = ((msw & 0x0000ffff) << 16) | ((lsw & 0xffff0000) >> 16);
6114 rtt = lsr_a - lsr - dlsr;
6115 rtt_msw = (rtt & 0xffff0000) >> 16;
6116 rtt_lsw = (rtt & 0x0000ffff);
6117 rtt_tv.tv_sec = rtt_msw;
6131 rtt_tv.tv_usec = (rtt_lsw * 15625) >> 10;
6132 rtp->rtcp->
rtt = (double)rtt_tv.tv_sec + ((
double)rtt_tv.tv_usec / 1000000);
6133 if (lsr_a - dlsr < lsr) {
6141 if (rtp->rtcp->
maxrtt < rtp->rtcp->
rtt) {
6145 calc_mean_and_standard_deviation(rtp->rtcp->
rtt, &rtp->rtcp->
normdevrtt,
6155 static void update_jitter_stats(
struct ast_rtp *rtp,
unsigned int ia_jitter)
6180 static void update_lost_stats(
struct ast_rtp *rtp,
unsigned int lost_packets)
6182 double reported_lost;
6189 if (reported_lost < rtp->rtcp->reported_minlost) {
6200 #define RESCALE(in, inmin, inmax, outmin, outmax) ((((in - inmin)/(inmax-inmin))*(outmax-outmin))+outmin)
6225 double normdevrtt,
double normdev_rxjitter,
double stdev_rxjitter,
6226 double normdev_rxlost)
6241 double effective_latency = (normdevrtt * 1000)
6242 + ((normdev_rxjitter * 2) * (stdev_rxjitter / 3))
6253 if (effective_latency < 160) {
6254 r_value = 93.2 - (effective_latency / 40);
6256 r_value = 93.2 - (effective_latency - 120) / 10;
6260 r_value = r_value - (normdev_rxlost * 2.0);
6268 }
else if (r_value > 100) {
6271 pseudo_mos = 1 + (0.035 * r_value) + (r_value * (r_value - 60) * (100 - r_value) * 0.000007);
6279 mes = RESCALE(pseudo_mos, 0.0, 5.0, 0.0, 100.0);
6289 static void update_reported_mes_stats(
struct ast_rtp *rtp)
6301 if (mes < rtp->rtcp->reported_minmes) {
6311 ast_debug_rtcp(2,
"%s: rtt: %.9f j: %.9f sjh: %.9f lost: %.9f mes: %4.1f\n",
6324 static void update_local_mes_stats(
struct ast_rtp *rtp)
6345 ast_debug_rtcp(2,
" %s: rtt: %.9f j: %.9f sjh: %.9f lost: %.9f mes: %4.1f\n",
6355 struct ast_rtp *rtp,
unsigned int ssrc,
int source)
6369 if (mapping->
ssrc_valid && mapping_ssrc == ssrc) {
6383 struct ast_rtp *rtp,
unsigned int ssrc)
6390 struct ast_rtp *rtp,
unsigned int ssrc)
6395 static const char *rtcp_payload_type2str(
unsigned int pt)
6401 str =
"Sender Report";
6404 str =
"Receiver Report";
6415 str =
"Source Description";
6427 static const char *rtcp_payload_subtype2str(
unsigned int pt,
unsigned int subtype)
6449 unsigned int length)
6457 unsigned int current_word;
6461 int abs_send_time_id;
6462 unsigned int now_msw = 0;
6463 unsigned int now_lsw = 0;
6464 unsigned int packets_not_found = 0;
6468 "but we don't have a RTP packet storage!\n", instance);
6473 if (abs_send_time_id != -1) {
6474 timeval2ntp(
ast_tvnow(), &now_msw, &now_lsw);
6483 for (packet_index = 3; packet_index < length; packet_index++) {
6484 current_word = ntohl(nackdata[position + packet_index]);
6485 pid = current_word >> 16;
6489 if (abs_send_time_id != -1) {
6493 put_unaligned_time24(payload->
buf + 17, now_msw, now_lsw);
6495 res +=
rtp_sendto(instance, payload->
buf, payload->
size, 0, &remote_address, &ice);
6497 ast_debug_rtcp(1,
"(%p) RTCP received NACK request for RTP packet with seqno %d, "
6498 "but we don't have it\n", instance, pid);
6499 packets_not_found++;
6507 blp = current_word & 0xffff;
6512 unsigned int seqno = (pid + blp_index) % 65536;
6515 if (abs_send_time_id != -1) {
6516 put_unaligned_time24(payload->
buf + 17, now_msw, now_lsw);
6518 res +=
rtp_sendto(instance, payload->
buf, payload->
size, 0, &remote_address, &ice);
6520 ast_debug_rtcp(1,
"(%p) RTCP remote end also requested RTP packet with seqno %d, "
6521 "but we don't have it\n", instance, seqno);
6522 packets_not_found++;
6530 if (packets_not_found) {
6536 ast_debug_rtcp(2,
"(%p) RTCP send buffer on RTP instance is now at maximum of %zu\n",
6546 #define RTCP_LENGTH_MASK 0xFFFF
6547 #define RTCP_PAYLOAD_TYPE_MASK 0xFF
6548 #define RTCP_REPORT_COUNT_MASK 0x1F
6549 #define RTCP_PADDING_MASK 0x01
6550 #define RTCP_VERSION_MASK 0x03
6555 #define RTCP_LENGTH_SHIFT 0
6556 #define RTCP_PAYLOAD_TYPE_SHIFT 16
6557 #define RTCP_REPORT_COUNT_SHIFT 24
6558 #define RTCP_PADDING_SHIFT 29
6559 #define RTCP_VERSION_SHIFT 30
6561 #define RTCP_VERSION 2U
6562 #define RTCP_VERSION_SHIFTED (RTCP_VERSION << RTCP_VERSION_SHIFT)
6563 #define RTCP_VERSION_MASK_SHIFTED (RTCP_VERSION_MASK << RTCP_VERSION_SHIFT)
6576 #define RTCP_VALID_MASK (RTCP_VERSION_MASK_SHIFTED | (((RTCP_PAYLOAD_TYPE_MASK & ~0x1)) << RTCP_PAYLOAD_TYPE_SHIFT))
6577 #define RTCP_VALID_VALUE (RTCP_VERSION_SHIFTED | (RTCP_PT_SR << RTCP_PAYLOAD_TYPE_SHIFT))
6579 #define RTCP_SR_BLOCK_WORD_LENGTH 5
6580 #define RTCP_RR_BLOCK_WORD_LENGTH 6
6581 #define RTCP_HEADER_SSRC_LENGTH 2
6582 #define RTCP_FB_REMB_BLOCK_WORD_LENGTH 4
6583 #define RTCP_FB_NACK_BLOCK_WORD_LENGTH 2
6586 const unsigned char *rtcpdata,
size_t size,
struct ast_sockaddr *addr)
6591 unsigned int *rtcpheader = (
unsigned int *)(rtcpdata);
6592 unsigned int packetwords;
6593 unsigned int position;
6594 unsigned int first_word;
6596 unsigned int ssrc_seen;
6599 #ifdef TEST_FRAMEWORK
6600 struct ast_rtp_engine_test *test_engine;
6604 if ((*rtcpheader & 0xC0) && res_srtp && srtp && res_srtp->unprotect(
6605 srtp, rtcpheader, &len, 1 | (srtp_replay_protection << 1)) < 0) {
6609 packetwords = len / 4;
6619 if (packetwords < RTCP_HEADER_SSRC_LENGTH) {
6620 ast_debug_rtcp(2,
"(%s) RTCP %p -- from %s: Frame size (%u words) is too short\n",
6626 first_word = ntohl(rtcpheader[position]);
6627 if ((first_word & RTCP_VALID_MASK) != RTCP_VALID_VALUE) {
6628 ast_debug_rtcp(2,
"(%s) RTCP %p -- from %s: Failed first packet validity check\n",
6634 position += ((first_word >> RTCP_LENGTH_SHIFT) & RTCP_LENGTH_MASK) + 1;
6635 if (packetwords <= position) {
6638 first_word = ntohl(rtcpheader[position]);
6639 }
while ((first_word & RTCP_VERSION_MASK_SHIFTED) == RTCP_VERSION_SHIFTED);
6640 if (position != packetwords) {
6641 ast_debug_rtcp(2,
"(%s) RTCP %p -- from %s: Failed packet version or length check\n",
6666 while (position < packetwords) {
6672 unsigned int ssrc_valid;
6673 unsigned int length;
6674 unsigned int min_length;
6676 unsigned int use_packet_source = 1;
6685 first_word = ntohl(rtcpheader[i]);
6686 pt = (first_word >> RTCP_PAYLOAD_TYPE_SHIFT) & RTCP_PAYLOAD_TYPE_MASK;
6687 rc = (first_word >> RTCP_REPORT_COUNT_SHIFT) & RTCP_REPORT_COUNT_MASK;
6689 length = ((first_word >> RTCP_LENGTH_SHIFT) & RTCP_LENGTH_MASK) + 1;
6692 min_length = RTCP_HEADER_SSRC_LENGTH;
6695 min_length += RTCP_SR_BLOCK_WORD_LENGTH;
6698 min_length += (rc * RTCP_RR_BLOCK_WORD_LENGTH);
6699 use_packet_source = 0;
6706 min_length += RTCP_FB_NACK_BLOCK_WORD_LENGTH;
6711 use_packet_source = 0;
6716 min_length += RTCP_FB_REMB_BLOCK_WORD_LENGTH;
6730 min_length = length;
6733 ast_debug_rtcp(1,
"(%p) RTCP %p -- from %s: %u(%s) skipping record\n",
6735 if (rtcp_debug_test_addr(addr)) {
6737 ast_verbose(
"RTCP from %s: %u(%s) skipping record\n",
6743 if (length < min_length) {
6744 ast_debug_rtcp(1,
"(%p) RTCP %p -- from %s: %u(%s) length field less than expected minimum. Min:%u Got:%u\n",
6746 min_length - 1, length - 1);
6759 rtcp_report->reception_report_count = rc;
6761 ssrc = ntohl(rtcpheader[i + 2]);
6762 rtcp_report->ssrc = ssrc;
6766 ssrc = ntohl(rtcpheader[i + 1]);
6769 ssrc = ntohl(rtcpheader[i + 2]);
6779 if (rtcp_debug_test_addr(addr)) {
6780 const char *subtype = rtcp_payload_subtype2str(pt, rc);
6784 ast_verbose(
"PT: %u (%s)\n", pt, rtcp_payload_type2str(pt));
6786 ast_verbose(
"Packet Subtype: %u (%s)\n", rc, subtype);
6788 ast_verbose(
"Reception reports: %u\n", rc);
6790 ast_verbose(
"SSRC of sender: %u\n", ssrc);
6799 if (use_packet_source) {
6804 if (child && child != transport) {
6816 rtp = transport_rtp;
6820 rtp = transport_rtp;
6833 if ((ssrc != rtp->
themssrc && use_packet_source && ssrc != 1)
6841 ast_debug_rtcp(1,
"(%p) RTCP %p -- from %s: Skipping record, received SSRC '%u' != expected '%u'\n",
6855 if (ast_debug_rtp_packet_is_allowed) {
6856 ast_debug(0,
"(%p) RTCP NAT: Got RTCP from other end. Now sending to address %s\n",
6862 i += RTCP_HEADER_SSRC_LENGTH;
6865 gettimeofday(&rtp->rtcp->
rxlsr, NULL);
6866 rtp->rtcp->
themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16);
6867 rtp->rtcp->
spc = ntohl(rtcpheader[i + 3]);
6868 rtp->rtcp->
soc = ntohl(rtcpheader[i + 4]);
6871 rtcp_report->sender_information.packet_count = rtp->rtcp->
spc;
6872 rtcp_report->sender_information.octet_count = rtp->rtcp->
soc;
6873 ntp2timeval((
unsigned int)ntohl(rtcpheader[i]),
6874 (
unsigned int)ntohl(rtcpheader[i + 1]),
6875 &rtcp_report->sender_information.ntp_timestamp);
6876 rtcp_report->sender_information.rtp_timestamp = ntohl(rtcpheader[i + 2]);
6877 if (rtcp_debug_test_addr(addr)) {
6878 ast_verbose(
"NTP timestamp: %u.%06u\n",
6879 (
unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_sec,
6880 (
unsigned int)rtcp_report->sender_information.ntp_timestamp.tv_usec);
6881 ast_verbose(
"RTP timestamp: %u\n", rtcp_report->sender_information.rtp_timestamp);
6882 ast_verbose(
"SPC: %u\tSOC: %u\n",
6883 rtcp_report->sender_information.packet_count,
6884 rtcp_report->sender_information.octet_count);
6886 i += RTCP_SR_BLOCK_WORD_LENGTH;
6895 report_block =
ast_calloc(1,
sizeof(*report_block));
6896 if (!report_block) {
6903 report_block->source_ssrc = ntohl(rtcpheader[i]);
6904 report_block->lost_count.packets = ntohl(rtcpheader[i + 1]) & 0x00ffffff;
6905 report_block->lost_count.fraction = ((ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24);
6906 report_block->highest_seq_no = ntohl(rtcpheader[i + 2]);
6907 report_block->ia_jitter = ntohl(rtcpheader[i + 3]);
6908 report_block->lsr = ntohl(rtcpheader[i + 4]);
6909 report_block->dlsr = ntohl(rtcpheader[i + 5]);
6910 if (report_block->lsr) {
6911 int skewed = update_rtt_stats(rtp, report_block->lsr, report_block->dlsr);
6912 if (skewed && rtcp_debug_test_addr(addr)) {
6914 unsigned int lsr_now, lsw, msw;
6915 gettimeofday(&now, NULL);
6916 timeval2ntp(now, &msw, &lsw);
6917 lsr_now = (((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16));
6918 ast_verbose(
"Internal RTCP NTP clock skew detected: "
6919 "lsr=%u, now=%u, dlsr=%u (%u:%03ums), "
6921 report_block->lsr, lsr_now, report_block->dlsr, report_block->dlsr / 65536,
6922 (report_block->dlsr % 65536) * 1000 / 65536,
6923 report_block->dlsr - (lsr_now - report_block->lsr));
6926 update_jitter_stats(rtp, report_block->ia_jitter);
6927 update_lost_stats(rtp, report_block->lost_count.packets);
6933 update_reported_mes_stats(rtp);
6935 if (rtcp_debug_test_addr(addr)) {
6938 ast_verbose(
" Fraction lost: %d\n", report_block->lost_count.fraction);
6939 ast_verbose(
" Packets lost so far: %u\n", report_block->lost_count.packets);
6940 ast_verbose(
" Highest sequence number: %u\n", report_block->highest_seq_no & 0x0000ffff);
6941 ast_verbose(
" Sequence number cycles: %u\n", report_block->highest_seq_no >> 16);
6942 ast_verbose(
" Interarrival jitter (samp): %u\n", report_block->ia_jitter);
6943 ast_verbose(
" Interarrival jitter (secs): %.6f\n",
ast_samp2sec(report_block->ia_jitter, rate));
6944 ast_verbose(
" Last SR(our NTP): %lu.%010lu\n",(
unsigned long)(report_block->lsr) >> 16,((
unsigned long)(report_block->lsr) << 16) * 4096);
6945 ast_verbose(
" DLSR: %4.4f (sec)\n",(
double)report_block->dlsr / 65536.0);
6946 ast_verbose(
" RTT: %4.4f(sec)\n", rtp->rtcp->
rtt);
6956 "to", transport_rtp->rtcp->local_addr_str,
6957 "rtt", rtp->rtcp->
rtt,
6985 transport_rtp->
f.
src =
"RTP";
6987 f = &transport_rtp->
f;
6997 if (rtcp_debug_test_addr(addr)) {
6998 ast_verbose(
"Received generic RTCP NACK message\n");
7014 if (rtcp_debug_test_addr(addr)) {
7015 ast_verbose(
"Received an RTCP Fast Update Request\n");
7022 transport_rtp->
f.
src =
"RTP";
7023 f = &transport_rtp->
f;
7031 if (rtcp_debug_test_addr(addr)) {
7032 ast_verbose(
"Received REMB report\n");
7038 feedback = transport_rtp->
f.
data.ptr;
7042 first_word = ntohl(rtcpheader[i + 2]);
7043 feedback->
remb.
br_exp = (first_word >> 18) & ((1 << 6) - 1);
7052 transport_rtp->
f.
src =
"RTP";
7053 f = &transport_rtp->
f;
7060 if (rtcp_debug_test_addr(addr)) {
7061 ast_verbose(
"Received an SDES from %s\n",
7064 #ifdef TEST_FRAMEWORK
7065 if ((test_engine = ast_rtp_instance_get_test(instance))) {
7066 test_engine->sdes_received = 1;
7071 if (rtcp_debug_test_addr(addr)) {
7072 ast_verbose(
"Received a BYE from %s\n",
7080 rtp->rtcp->rtcp_info = 1;
7098 size_t read_area_size =
sizeof(rtcpdata) - AST_FRIENDLY_OFFSET;
7102 if ((res =
rtcp_recvfrom(instance, read_area, read_area_size,
7104 if (res == RTP_DTLS_ESTABLISHED) {
7110 ast_assert(errno != EBADF);
7111 if (errno != EAGAIN) {
7112 ast_log(LOG_WARNING,
"RTCP Read error: %s. Hanging up.\n",
7113 (errno) ? strerror(errno) :
"Unspecified");
7125 struct sockaddr_in addr_tmp;
7135 ast_debug_stun(2,
"(%p) STUN cannot do for non IPv4 address %s\n",
7151 struct ast_rtp_instance *instance1,
unsigned int *rtpheader,
int len,
int hdrlen)
7155 int res = 0, payload = 0, bridged_payload = 0, mark;
7157 int reconstruct = ntohl(rtpheader[0]);
7160 unsigned int timestamp = ntohl(rtpheader[1]);
7163 payload = (reconstruct & 0x7f0000) >> 16;
7164 mark = (reconstruct & 0x800000) >> 23;
7168 if (!payload_type) {
7174 payload_type->asterisk_format, payload_type->format, payload_type->rtp_code);
7177 if (bridged_payload < 0) {
7183 ast_debug_rtp(1,
"(%p, %p) RTP unsupported payload type received\n", instance, instance1);
7193 ast_debug_rtp(1,
"(%p, %p) RTP feeding packet with duplicate timestamp to core\n", instance, instance1);
7197 if (payload_type->asterisk_format) {
7198 ao2_replace(rtp->lastrxformat, payload_type->format);
7213 ao2_unlock(instance);
7214 ao2_lock(instance1);
7225 ast_debug_rtp(1,
"(%p, %p) RTP Feeding packet to core until DTMF finishes\n", instance, instance1);
7226 ao2_unlock(instance1);
7231 if (payload_type->asterisk_format) {
7239 ast_debug_rtp(1,
"(%p, %p) RTP asymmetric RTP codecs detected (TX: %s, RX: %s) sending frame to core\n",
7242 ao2_unlock(instance1);
7247 ao2_replace(bridged->lasttxformat, payload_type->format);
7253 ast_debug_rtp(5,
"(%p, %p) RTP remote address is null, most likely RTP has been stopped\n",
7254 instance, instance1);
7255 ao2_unlock(instance1);
7261 if (ast_test_flag(bridged, FLAG_NEED_MARKER_BIT)) {
7263 ast_clear_flag(bridged, FLAG_NEED_MARKER_BIT);
7267 if (ast_test_flag(bridged, FLAG_REQ_LOCAL_BRIDGE_BIT)) {
7269 ast_clear_flag(bridged, FLAG_REQ_LOCAL_BRIDGE_BIT);
7273 reconstruct &= 0xFF80FFFF;
7274 reconstruct |= (bridged_payload << 16);
7275 reconstruct |= (mark << 23);
7276 rtpheader[0] = htonl(reconstruct);
7280 bridged->
ssrc = ntohl(rtpheader[2]);
7284 res =
rtp_sendto(instance1, (
void *)rtpheader, len, 0, &remote_address, &ice);
7287 ast_log(LOG_WARNING,
7288 "RTP Transmission error of packet to %s: %s\n",
7291 }
else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || ast_debug_rtp_packet_is_allowed) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
7292 if (ast_debug_rtp_packet_is_allowed || DEBUG_ATLEAST(1)) {
7293 ast_log(LOG_WARNING,
7294 "RTP NAT: Can't write RTP to private "
7295 "address %s, waiting for other end to "
7299 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
7301 ao2_unlock(instance1);
7306 if (rtp_debug_test_addr(&remote_address)) {
7307 ast_verbose(
"Sent RTP P2P packet to %s%s (type %-2.2d, len %-6.6d)\n",
7309 ice ?
" (via ICE)" :
"",
7310 bridged_payload, len - hdrlen);
7313 ao2_unlock(instance1);
7321 ao2_unlock(instance);
7331 static void rtp_transport_wide_cc_feedback_status_vector_append(
unsigned char *rtcpheader,
int *packet_len,
int *status_vector_chunk_bits,
7332 uint16_t *status_vector_chunk,
int status)
7335 *status_vector_chunk_bits -= 2;
7341 *status_vector_chunk |= (status << (16 - 2 - (14 - *status_vector_chunk_bits)));
7344 if (*status_vector_chunk_bits) {
7349 put_unaligned_uint16(rtcpheader + *packet_len, htons(*status_vector_chunk));
7350 *status_vector_chunk_bits = 14;
7356 *status_vector_chunk = (1 << 15) | (1 << 14);
7360 static void rtp_transport_wide_cc_feedback_status_append(
unsigned char *rtcpheader,
int *packet_len,
int *status_vector_chunk_bits,
7361 uint16_t *status_vector_chunk,
int *run_length_chunk_count,
int *run_length_chunk_status,
int status)
7363 if (*run_length_chunk_status != status) {
7364 while (*run_length_chunk_count > 0 && *run_length_chunk_count < 8) {
7371 rtp_transport_wide_cc_feedback_status_vector_append(rtcpheader, packet_len, status_vector_chunk_bits,
7372 status_vector_chunk, *run_length_chunk_status);
7373 *run_length_chunk_count -= 1;
7376 if (*run_length_chunk_count) {
7378 put_unaligned_uint16(rtcpheader + *packet_len, htons((0 << 15) | (*run_length_chunk_status << 13) | *run_length_chunk_count));
7383 *run_length_chunk_count = 0;
7384 *run_length_chunk_status = -1;
7386 if (*status_vector_chunk_bits == 14) {
7388 *run_length_chunk_status = status;
7389 *run_length_chunk_count = 1;
7392 rtp_transport_wide_cc_feedback_status_vector_append(rtcpheader, packet_len, status_vector_chunk_bits,
7393 status_vector_chunk, status);
7397 *run_length_chunk_count += 1;
7401 static int rtp_transport_wide_cc_feedback_produce(
const void *data)
7405 unsigned char *rtcpheader;
7410 int status_vector_chunk_bits = 14;
7411 uint16_t status_vector_chunk = (1 << 15) | (1 << 14);
7412 int run_length_chunk_count = 0;
7413 int run_length_chunk_status = -1;
7414 int packet_len = 20;
7416 int packet_count = 0;
7417 unsigned int received_msw;
7418 unsigned int received_lsw;
7422 unsigned int large_delta_count = 0;
7423 unsigned int small_delta_count = 0;
7424 unsigned int lost_count = 0;
7435 ao2_unlock(instance);
7439 rtcpheader = (
unsigned char *)bdata;
7443 previous_packet = first_packet;
7458 if (first_packet != statistics) {
7463 lost = statistics->
seqno - (previous_packet->
seqno + 1);
7469 rtp_transport_wide_cc_feedback_status_append(rtcpheader, &packet_len, &status_vector_chunk_bits,
7470 &status_vector_chunk, &run_length_chunk_count, &run_length_chunk_status, 0);
7476 if (packet_len + delta_len + 20 >
sizeof(bdata)) {
7493 if (statistics->
delta < 0 || statistics->
delta > 127) {
7495 rtp_transport_wide_cc_feedback_status_append(rtcpheader, &packet_len, &status_vector_chunk_bits,
7496 &status_vector_chunk, &run_length_chunk_count, &run_length_chunk_status, 2);
7498 large_delta_count++;
7501 rtp_transport_wide_cc_feedback_status_append(rtcpheader, &packet_len, &status_vector_chunk_bits,
7502 &status_vector_chunk, &run_length_chunk_count, &run_length_chunk_status, 1);
7504 small_delta_count++;
7507 previous_packet = statistics;
7510 if (packet_len + delta_len + 20 >
sizeof(bdata)) {
7515 if (status_vector_chunk_bits != 14) {
7517 put_unaligned_uint16(rtcpheader + packet_len, htons(status_vector_chunk));
7519 }
else if (run_length_chunk_count) {
7521 put_unaligned_uint16(rtcpheader + packet_len, htons((0 << 15) | (run_length_chunk_status << 13) | run_length_chunk_count));
7531 if (statistics->
delta < 0 || statistics->
delta > 127) {
7533 put_unaligned_uint16(rtcpheader + packet_len, htons(statistics->
delta));
7537 rtcpheader[packet_len] = statistics->
delta;
7544 if (statistics == previous_packet) {
7550 while (packet_len % 4) {
7551 rtcpheader[packet_len++] = 0;
7557 put_unaligned_uint32(rtcpheader + 4, htonl(rtp->
ssrc));
7558 put_unaligned_uint32(rtcpheader + 8, htonl(rtp->
themssrc));
7561 put_unaligned_uint32(rtcpheader + 12, htonl((first_packet->
seqno << 16) | packet_count));
7563 timeval2ntp(first_packet->
received, &received_msw, &received_lsw);
7564 put_unaligned_time24(rtcpheader + 16, received_msw, received_lsw);
7570 ast_debug_rtcp(2,
"(%p) RTCP sending transport-cc feedback packet of size '%d' on '%s' with packet count of %d (small = %d, large = %d, lost = %d)\n",
7573 res =
rtcp_sendto(instance, (
unsigned int *)rtcpheader, packet_len, 0, &remote_address, &ice);
7575 ast_log(LOG_ERROR,
"RTCP transport-cc feedback error to %s due to %s\n",
7583 ao2_unlock(instance);
7589 unsigned char *data,
int len)
7591 uint16_t *seqno = (uint16_t *)data;
7624 rtp_transport_wide_cc_packet_statistics_cmp)) {
7631 ast_debug_rtcp(1,
"(%p) RTCP starting transport-cc feedback transmission on RTP instance '%p'\n", instance, transport);
7634 rtp_transport_wide_cc_feedback_produce, transport);
7637 ast_log(LOG_WARNING,
"Scheduling RTCP transport-cc feedback transmission failed on RTP instance '%p'\n",
7650 if (transport_wide_cc_id == -1) {
7656 int id = extension[pos] >> 4;
7657 int extension_len = (extension[pos] & 0xF) + 1;
7674 }
else if (
id == 15) {
7684 }
else if ((pos + extension_len) > len) {
7692 if (
id == transport_wide_cc_id) {
7693 rtp_instance_parse_transport_wide_cc(instance, rtp, extension + pos, extension_len);
7697 pos += extension_len;
7702 const struct ast_sockaddr *remote_address,
unsigned char *read_area,
int length,
int prev_seqno,
7703 unsigned int bundled)
7705 unsigned int *rtpheader = (
unsigned int*)(read_area);
7708 int res = length, hdrlen = 12, ssrc, seqno, payloadtype, padding, mark, ext, cc;
7709 unsigned int timestamp;
7714 if ((*read_area & 0xC0) && res_srtp && srtp && res_srtp->unprotect(
7715 srtp, read_area, &res, 0 | (srtp_replay_protection << 1)) < 0) {
7725 ssrc = ntohl(rtpheader[2]);
7726 seqno = ntohl(rtpheader[0]);
7727 payloadtype = (seqno & 0x7f0000) >> 16;
7728 padding = seqno & (1 << 29);
7729 mark = seqno & (1 << 23);
7730 ext = seqno & (1 << 28);
7731 cc = (seqno & 0xF000000) >> 24;
7733 timestamp = ntohl(rtpheader[1]);
7739 res -= read_area[res - 1];
7749 int extensions_size = (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
7750 unsigned int profile;
7751 profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
7753 if (profile == 0xbede) {
7755 rtp_instance_parse_extmap_extensions(instance, rtp, read_area + hdrlen + 4, extensions_size);
7756 }
else if (DEBUG_ATLEAST(1)) {
7757 if (profile == 0x505a) {
7758 ast_log(LOG_DEBUG,
"Found Zfone extension in RTP stream - zrtp - not supported.\n");
7761 ast_log(LOG_DEBUG,
"Found unknown RTP Extensions %x\n", profile);
7765 hdrlen += extensions_size;
7771 ast_log(LOG_WARNING,
"RTP Read too short (%d, expecting %d\n", res, hdrlen);
7785 if (ast_debug_rtp_packet_is_allowed) {
7786 ast_debug(0,
"(%p) RTP forcing Marker bit, because SSRC has changed\n", instance);
7825 ast_log(LOG_WARNING,
"scheduling RTCP transmission failed.\n");
7828 if ((
int)prev_seqno - (
int)seqno > 100)
7838 struct timeval rxtime;
7842 calc_rxstamp_and_jitter(&rxtime, rtp, timestamp, mark);
7860 if (!payload->asterisk_format) {
7867 process_dtmf_rfc2833(instance, read_area + hdrlen, res - hdrlen, seqno, timestamp, payloadtype, mark, &frames);
7869 f = process_dtmf_cisco(instance, read_area + hdrlen, res - hdrlen, seqno, timestamp, payloadtype, mark);
7870 }
else if (payload->rtp_code ==
AST_RTP_CN) {
7871 f = process_cn_rfc3389(instance, read_area + hdrlen, res - hdrlen, seqno, timestamp, payloadtype, mark);
7873 ast_log(LOG_NOTICE,
"Unknown RTP codec %d received from '%s'\n",
7890 case AST_MEDIA_TYPE_AUDIO:
7893 case AST_MEDIA_TYPE_VIDEO:
7896 case AST_MEDIA_TYPE_TEXT:
7899 case AST_MEDIA_TYPE_IMAGE:
7902 ast_log(LOG_WARNING,
"Unknown or unsupported media type: %s\n",
7924 rtp->
f.
data.ptr = read_area + hdrlen;
7931 && ((
int)seqno - (prev_seqno + 1) > 0)
7932 && ((
int)seqno - (prev_seqno + 1) < 10)) {
7933 unsigned char *data = rtp->
f.
data.ptr;
7943 unsigned char *data = rtp->
f.
data.ptr;
7944 unsigned char *header_end;
7945 int num_generations;
7948 int diff =(int)seqno - (prev_seqno+1);
7952 header_end = memchr(data, ((*data) & 0x7f), rtp->
f.
datalen);
7953 if (header_end == NULL) {
7958 header_length = header_end -
data;
7959 num_generations = header_length / 4;
7960 len = header_length;
7963 for (x = 0; x < num_generations; x++)
7964 len += data[x * 4 + 3];
7971 }
else if (diff > num_generations && diff < 10) {
7976 data = rtp->
f.
data.ptr;
7981 for ( x = 0; x < num_generations - diff; x++)
7982 len += data[x * 4 + 3];
7992 ast_frame_byteswap_be(&rtp->
f);
7994 calc_rxstamp_and_jitter(&rtp->
f.
delivery, rtp, timestamp, mark);
8001 if (!rtp->lastividtimestamp)
8002 rtp->lastividtimestamp = timestamp;
8003 calc_rxstamp_and_jitter(&rtp->
f.
delivery, rtp, timestamp, mark);
8006 rtp->
f.
samples = timestamp - rtp->lastividtimestamp;
8007 rtp->lastividtimestamp = timestamp;
8014 if (!rtp->lastitexttimestamp)
8015 rtp->lastitexttimestamp = timestamp;
8016 rtp->
f.
samples = timestamp - rtp->lastitexttimestamp;
8017 rtp->lastitexttimestamp = timestamp;
8021 ast_log(LOG_WARNING,
"Unknown or unsupported media type: %s\n",
8032 struct rtp_drop_packets_data {
8034 unsigned int use_random_num;
8036 unsigned int use_random_interval;
8039 unsigned int num_to_drop;
8041 unsigned int num_dropped;
8044 struct timeval interval;
8046 struct timeval next;
8053 static struct rtp_drop_packets_data drop_packets_data;
8055 static void drop_packets_data_update(
struct timeval tv)
8064 drop_packets_data.num_dropped = drop_packets_data.use_random_num ?
8065 ast_random() % drop_packets_data.num_to_drop : 0;
8073 if (drop_packets_data.use_random_interval) {
8076 &drop_packets_data.interval) * ((
double)(ast_random() % 100 + 1) / 100),
8077 TIME_UNIT_MICROSECOND);
8079 drop_packets_data.next =
ast_tvadd(tv, interval);
8081 drop_packets_data.next =
ast_tvadd(tv, drop_packets_data.interval);
8085 static int should_drop_packets(
struct ast_sockaddr *addr)
8089 if (!drop_packets_data.num_to_drop) {
8098 (drop_packets_data.port ?
8106 if (drop_packets_data.num_dropped < drop_packets_data.num_to_drop) {
8107 ++drop_packets_data.num_dropped;
8116 if (
ast_tvzero(drop_packets_data.interval)) {
8118 drop_packets_data.num_to_drop = 0;
8123 if (
ast_tvcmp(tv, drop_packets_data.next) == -1) {
8133 drop_packets_data_update(tv);
8146 int res, hdrlen = 12, version, payloadtype;
8148 size_t read_area_size =
sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET;
8149 unsigned int *rtpheader = (
unsigned int*)(read_area), seqno, ssrc, timestamp, prev_seqno;
8153 unsigned int bundled;
8164 if ((res =
rtp_recvfrom(instance, read_area, read_area_size, 0,
8166 if (res == RTP_DTLS_ESTABLISHED) {
8172 ast_assert(errno != EBADF);
8173 if (errno != EAGAIN) {
8174 ast_log(LOG_WARNING,
"RTP Read error: %s. Hanging up.\n",
8175 (errno) ? strerror(errno) :
"Unspecified");
8187 if (rtcp_mux(rtp, read_area)) {
8195 for (i = 0; i < res; ++i) {
8196 if (read_area[i] !=
'\0') {
8197 ast_log(LOG_WARNING,
"RTP Read too short\n");
8205 seqno = ntohl(rtpheader[0]);
8209 if (!(version = (seqno & 0xC0000000) >> 30)) {
8210 struct sockaddr_in addr_tmp;
8219 ast_debug_stun(1,
"(%p) STUN cannot do for non IPv4 address %s\n",
8237 ssrc = ntohl(rtpheader[2]);
8248 if (child != instance) {
8306 ast_verb(4,
"%p -- Strict RTP learning complete - Locking on source address %s\n",
8322 rtp_learning_seq_init(&rtp->rtp_source_learn, seqno);
8335 ast_verb(4,
"%p -- Strict RTP switching to RTP target address %s as source\n",
8338 rtp_learning_seq_init(&rtp->rtp_source_learn, seqno);
8348 if (rtp->rtp_source_learn.
stream_type == AST_MEDIA_TYPE_UNKNOWN) {
8354 ast_verb(4,
"%p -- Strict RTP qualifying stream type: %s\n",
8357 if (!rtp_learning_rtp_seq_update(&rtp->rtp_source_learn, seqno)) {
8359 ast_verb(4,
"%p -- Strict RTP switching source address to %s\n",
8362 rtp_learning_seq_init(&rtp->rtp_source_learn, seqno);
8366 ast_debug_rtp(1,
"(%p) RTP %p -- Received packet from %s, dropping due to strict RTP protection. Will switch to it in %d packets.\n",
8374 rtp_learning_seq_init(&rtp->rtp_source_learn, seqno);
8375 ast_debug_rtp(1,
"(%p) RTP %p -- Received packet from %s, dropping due to strict RTP protection. Qualifying new stream.\n",
8394 ast_debug_rtp(1,
"(%p) RTP %p -- Received packet from %s, dropping due to strict RTP protection.\n",
8396 #ifdef TEST_FRAMEWORK
8398 static int strict_rtp_test_event = 1;
8399 if (strict_rtp_test_event) {
8402 strict_rtp_test_event = 0;
8407 case STRICT_RTP_OPEN:
8421 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
8422 if (ast_debug_rtp_packet_is_allowed)
8423 ast_debug(0,
"(%p) RTP NAT: Got audio from other end. Now sending to address %s\n",
8429 payloadtype = (seqno & 0x7f0000) >> 16;
8431 timestamp = ntohl(rtpheader[1]);
8434 if (should_drop_packets(&addr)) {
8435 ast_debug(0,
"(%p) RTP: drop received packet from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6d)\n",
8441 if (rtp_debug_test_addr(&addr)) {
8442 ast_verbose(
"Got RTP packet from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6d)\n",
8444 payloadtype, seqno, timestamp, res - hdrlen);
8458 frame = ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled);
8473 frame = ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled);
8480 ast_debug_rtp(2,
"(%p) RTP Packet with sequence number '%d' on instance is no longer missing\n",
8488 frame = ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled);
8498 frame =
ast_frdup(ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled));
8513 frame =
ast_frdup(ast_rtp_interpret(instance, srtp, &addr, payload->
buf, payload->
size, prev_seqno, bundled));
8523 ast_debug_rtp(2,
"(%p) RTP pulled buffered packet with sequence number '%d' to additionally return\n",
8524 instance, frame->
seqno);
8534 }
else if ((((seqno - rtp->
expectedrxseqno) > 100) && timestamp > rtp->lastividtimestamp) ||
8544 if (rtp->rtp_source_learn.
stream_type == AST_MEDIA_TYPE_VIDEO) {
8545 ast_debug_rtp(2,
"(%p) RTP source has wild gap or packet loss, sending FIR\n",
8547 rtp_write_rtcp_fir(instance, rtp, &remote_address);
8559 frame =
ast_frdup(ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled));
8563 ast_debug_rtp(2,
"(%p) RTP inserted just received packet with sequence number '%d' in correct order\n",
8584 frame =
ast_frdup(ast_rtp_interpret(instance, srtp, &addr, payload->
buf, payload->
size, prev_seqno, bundled));
8588 ast_debug_rtp(2,
"(%p) RTP emptying queue and returning packet with sequence number '%d'\n",
8589 instance, frame->
seqno);
8606 frame = ast_rtp_interpret(instance, srtp, &addr, read_area, res, prev_seqno, bundled);
8613 ast_debug_rtp(2,
"(%p) RTP adding just received packet with sequence number '%d' to end of dumped queue\n",
8648 ast_debug_rtp(2,
"(%p) RTP received an old packet with sequence number '%d', dropping it\n",
8653 ast_debug_rtp(2,
"(%p) RTP received a duplicate transmission of packet with sequence number '%d', dropping it\n",
8661 unsigned int missing_seqnos_added = 0;
8663 ast_debug_rtp(2,
"(%p) RTP received an out of order packet with sequence number '%d' while expecting '%d' from the future\n",
8666 payload =
ast_malloc(
sizeof(*payload) + res);
8677 payload->
size = res;
8678 memcpy(payload->
buf, rtpheader, res);
8690 if (!remove_failed) {
8691 ast_debug_rtp(2,
"(%p) RTP packet with sequence number '%d' is no longer missing\n",
8700 missing_seqno = seqno;
8701 while (remove_failed) {
8705 if (missing_seqno < 0) {
8706 missing_seqno = 65535;
8710 if (missing_seqno == prev_seqno) {
8738 ast_debug_rtp(2,
"(%p) RTP added missing sequence number '%d'\n",
8739 instance, missing_seqno);
8742 missing_seqnos_added++;
8767 rtcpheader =
ast_malloc(
sizeof(*rtcpheader) + data_size);
8769 ast_debug_rtcp(1,
"(%p) RTCP failed to allocate memory for NACK\n", instance);
8773 memset(rtcpheader, 0, data_size);
8775 res = ast_rtcp_generate_compound_prefix(instance, rtcpheader, rtcp_report, &sr);
8777 if (res == 0 || res == 1) {
8783 res = ast_rtcp_generate_nack(instance, rtcpheader + packet_len);
8786 ast_debug_rtcp(1,
"(%p) RTCP failed to construct NACK, stopping here\n", instance);
8792 res =
rtcp_sendto(instance, rtcpheader, packet_len, 0, &remote_address, &ice);
8794 ast_debug_rtcp(1,
"(%p) RTCP failed to send NACK request out\n", instance);
8796 ast_debug_rtcp(2,
"(%p) RTCP sending a NACK request to get missing packets\n", instance);
8798 ast_rtcp_calculate_sr_rr_statistics(instance, rtcp_report, remote_address, ice, sr);
8815 if (rtp->rtcp && rtp->rtcp->type == value) {
8816 ast_debug_rtcp(1,
"(%p) RTCP ignoring duplicate property\n", instance);
8821 rtp->rtcp =
ast_calloc(1,
sizeof(*rtp->rtcp));
8826 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
8827 rtp->rtcp->dtls.timeout_timer = -1;
8832 rtp->rtcp->type = value;
8849 ast_free(rtp->rtcp->local_addr_str);
8851 if (!rtp->rtcp->local_addr_str) {
8852 ast_free(rtp->rtcp);
8863 create_new_socket(
"RTCP",
8867 AF_INET6 : -1)) < 0) {
8868 ast_debug_rtcp(1,
"(%p) RTCP failed to create a new socket\n", instance);
8869 ast_free(rtp->rtcp->local_addr_str);
8870 ast_free(rtp->rtcp);
8877 ast_debug_rtcp(1,
"(%p) RTCP failed to setup RTP instance\n", instance);
8878 close(rtp->rtcp->
s);
8879 ast_free(rtp->rtcp->local_addr_str);
8880 ast_free(rtp->rtcp);
8884 #ifdef HAVE_PJPROJECT
8889 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
8890 dtls_setup_rtcp(instance);
8903 if (rtp->rtcp->
s > -1 && rtp->rtcp->
s != rtp->s) {
8904 close(rtp->rtcp->
s);
8906 rtp->rtcp->
s = rtp->s;
8909 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
8910 if (rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
8911 SSL_free(rtp->rtcp->dtls.ssl);
8913 rtp->rtcp->dtls.ssl = rtp->dtls.ssl;
8921 if (rtp->rtcp->
schedid > -1) {
8922 ao2_unlock(instance);
8928 ast_debug_rtcp(1,
"(%p) RTCP failed to tear down RTCP\n", instance);
8936 ao2_unlock(instance);
8940 ast_debug_rtcp(1,
"(%p) RTCP failed to tear down transport-cc feedback\n", instance);
8947 if (rtp->rtcp->
s > -1 && rtp->rtcp->
s != rtp->s) {
8948 close(rtp->rtcp->
s);
8950 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
8951 ao2_unlock(instance);
8952 dtls_srtp_stop_timeout_timer(instance, rtp, 1);
8955 if (rtp->rtcp->dtls.ssl && rtp->rtcp->dtls.ssl != rtp->dtls.ssl) {
8956 SSL_free(rtp->rtcp->dtls.ssl);
8959 ast_free(rtp->rtcp->local_addr_str);
8960 ast_free(rtp->rtcp);
9000 return rtcp ? (rtp->rtcp ? rtp->rtcp->
s : -1) : rtp->s;
9022 ast_debug_rtcp(1,
"(%p) RTCP setting address on RTP instance\n", instance);
9033 ast_free(rtp->rtcp->local_addr_str);
9054 ast_verb(4,
"%p -- Strict RTP learning after remote address set to: %s\n",
9076 ao2_unlock(instance);
9097 rtp->red->
t140red.
data.ptr = &rtp->red->t140red_data;
9099 rtp->red->
ti = buffer_time;
9100 rtp->red->
num_gen = generations;
9101 rtp->red->hdrlen = generations * 4 + 1;
9103 for (x = 0; x < generations; x++) {
9104 rtp->red->
pt[x] = payloads[x];
9105 rtp->red->
pt[x] |= 1 << 7;
9106 rtp->red->t140red_data[x*4] = rtp->red->
pt[x];
9108 rtp->red->t140red_data[x*4] = rtp->red->
pt[x] = payloads[x];
9118 struct rtp_red *red = rtp->red;
9126 const unsigned char *primary = red->
buf_data;
9129 if (primary[0] == 0x08 || primary[0] == 0x0a || primary[0] == 0x0d) {
9133 primary = frame->
data.ptr;
9134 if (primary[0] == 0x08 || primary[0] == 0x0a || primary[0] == 0x0d) {
9154 ao2_lock(instance0);
9155 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT | FLAG_REQ_LOCAL_BRIDGE_BIT);
9156 if (rtp->smoother) {
9157 ast_smoother_free(rtp->smoother);
9158 rtp->smoother = NULL;
9172 ao2_unlock(instance0);
9263 struct sockaddr_in suggestion_tmp;
9280 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
9281 ao2_unlock(instance);
9284 dtls_srtp_stop_timeout_timer(instance, rtp, 0);
9286 dtls_srtp_stop_timeout_timer(instance, rtp, 1);
9293 if (rtp->rtcp && rtp->rtcp->
schedid > -1) {
9294 ao2_unlock(instance);
9304 ao2_unlock(instance);
9313 ao2_unlock(instance);
9322 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
9340 unsigned int *rtpheader;
9342 int res, payload = 0;
9356 level = 127 - (level & 0x7f);
9361 rtpheader = (
unsigned int *)data;
9362 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->
seqno));
9363 rtpheader[1] = htonl(rtp->lastts);
9364 rtpheader[2] = htonl(rtp->
ssrc);
9367 res =
rtp_sendto(instance, (
void *) rtpheader, hdrlen + 1, 0, &remote_address, &ice);
9370 ast_log(LOG_ERROR,
"RTP Comfort Noise Transmission error to %s: %s\n",
ast_sockaddr_stringify(&remote_address), strerror(errno));
9374 if (rtp_debug_test_addr(&remote_address)) {
9375 ast_verbose(
"Sent Comfort Noise RTP packet to %s%s (type %-2.2d, seq %-6.6d, ts %-6.6u, len %-6.6d)\n",
9377 ice ?
" (via ICE)" :
"",
9419 ao2_unlock(instance);
9428 if (mapping->
instance == instance) {
9441 static void ast_rtp_set_stream_num(
struct ast_rtp_instance *instance,
int stream_num)
9450 switch (extension) {
9467 if (child_rtp->
bundled == parent) {
9481 ao2_unlock(child_rtp->
bundled);
9490 rtp_allocate_transport(child, child_rtp);
9497 rtp_deallocate_transport(child, child_rtp);
9512 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
9517 dtls_srtp_add_local_ssrc(parent_rtp, parent, 0, child_rtp->
ssrc, 0);
9533 #ifdef HAVE_PJPROJECT
9534 static void stunaddr_resolve_callback(
const struct ast_dns_query *query)
9538 const char *stunaddr_resolved_str;
9540 if (!store_stunaddr_resolved(query)) {
9541 ast_log(LOG_WARNING,
"Failed to resolve stunaddr '%s'. Cancelling recurring resolution.\n", stunaddr_name);
9545 if (DEBUG_ATLEAST(2)) {
9546 ast_rwlock_rdlock(&stunaddr_lock);
9548 ast_rwlock_unlock(&stunaddr_lock);
9550 ast_debug_stun(2,
"Resolved stunaddr '%s' to '%s'. Lowest TTL = %d.\n",
9552 stunaddr_resolved_str,
9557 ast_log(LOG_WARNING,
"Resolution for stunaddr '%s' returned TTL = 0. Recurring resolution was cancelled.\n",
ast_dns_query_get_name(query));
9561 static int store_stunaddr_resolved(
const struct ast_dns_query *query)
9571 if (rr_type == ns_t_a && data_size == 4) {
9572 ast_rwlock_wrlock(&stunaddr_lock);
9573 memcpy(&stunaddr.sin_addr, data, data_size);
9574 stunaddr.sin_family = AF_INET;
9575 ast_rwlock_unlock(&stunaddr_lock);
9579 ast_debug_stun(3,
"Unrecognized rr_type '%u' or data_size '%zu' from DNS query for stunaddr '%s'\n",
9587 static void clean_stunaddr(
void) {
9588 if (stunaddr_resolver) {
9590 ast_log(LOG_ERROR,
"Failed to cancel recurring DNS resolution of previous stunaddr.\n");
9592 ao2_ref(stunaddr_resolver, -1);
9593 stunaddr_resolver = NULL;
9595 ast_rwlock_wrlock(&stunaddr_lock);
9596 memset(&stunaddr, 0,
sizeof(stunaddr));
9597 ast_rwlock_unlock(&stunaddr_lock);
9601 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
9608 #ifdef HAVE_PJPROJECT
9614 ast_debug_dtls(3,
"(%p) DTLS - ast_rtp_activate rtp=%p - setup and perform DTLS'\n", instance, rtp);
9616 dtls_perform_setup(&rtp->dtls);
9617 dtls_perform_handshake(instance, &rtp->dtls, 0);
9620 dtls_perform_setup(&rtp->rtcp->dtls);
9621 dtls_perform_handshake(instance, &rtp->rtcp->dtls, 1);
9631 char *debughost = NULL;
9632 char *debugport = NULL;
9635 ast_cli(a->fd,
"Lookup failed for '%s'\n", arg);
9638 rtpdebugport = (!ast_strlen_zero(debugport) && debugport[0] !=
'0');
9639 ast_cli(a->fd,
"RTP Packet Debugging Enabled for address: %s\n",
9641 ast_debug_category_set_sublevel(AST_LOG_CATEGORY_RTP_PACKET, AST_LOG_CATEGORY_ENABLED);
9648 char *debughost = NULL;
9649 char *debugport = NULL;
9652 ast_cli(a->fd,
"Lookup failed for '%s'\n", arg);
9655 rtcpdebugport = (!ast_strlen_zero(debugport) && debugport[0] !=
'0');
9656 ast_cli(a->fd,
"RTCP Packet Debugging Enabled for address: %s\n",
9658 ast_debug_category_set_sublevel(AST_LOG_CATEGORY_RTCP_PACKET, AST_LOG_CATEGORY_ENABLED);
9666 e->
command =
"rtp set debug {on|off|ip}";
9668 "Usage: rtp set debug {on|off|ip host[:port]}\n"
9669 " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
9670 " specified, limit the dumped packets to those to and from\n"
9671 " the specified 'host' with optional port.\n";
9677 if (a->argc == e->
args) {
9678 if (!strncasecmp(a->argv[e->
args-1],
"on", 2)) {
9679 ast_debug_category_set_sublevel(AST_LOG_CATEGORY_RTP_PACKET, AST_LOG_CATEGORY_ENABLED);
9681 ast_cli(a->fd,
"RTP Packet Debugging Enabled\n");
9683 }
else if (!strncasecmp(a->argv[e->
args-1],
"off", 3)) {
9684 ast_debug_category_set_sublevel(AST_LOG_CATEGORY_RTP_PACKET, AST_LOG_CATEGORY_DISABLED);
9685 ast_cli(a->fd,
"RTP Packet Debugging Disabled\n");
9688 }
else if (a->argc == e->
args +1) {
9689 return rtp_do_debug_ip(a);
9692 return CLI_SHOWUSAGE;
9698 #ifdef HAVE_PJPROJECT
9699 struct sockaddr_in stunaddr_copy;
9703 e->
command =
"rtp show settings";
9705 "Usage: rtp show settings\n"
9706 " Display RTP configuration settings\n";
9713 return CLI_SHOWUSAGE;
9716 ast_cli(a->fd,
"\n\nGeneral Settings:\n");
9717 ast_cli(a->fd,
"----------------\n");
9718 ast_cli(a->fd,
" Port start: %d\n", rtpstart);
9719 ast_cli(a->fd,
" Port end: %d\n",
rtpend);
9721 ast_cli(a->fd,
" Checksums: %s\n",
AST_CLI_YESNO(nochecksums == 0));
9723 ast_cli(a->fd,
" DTMF Timeout: %d\n", dtmftimeout);
9730 ast_cli(a->fd,
" Replay Protect: %s\n",
AST_CLI_YESNO(srtp_replay_protection));
9731 #ifdef HAVE_PJPROJECT
9732 ast_cli(a->fd,
" ICE support: %s\n",
AST_CLI_YESNO(icesupport));
9734 ast_rwlock_rdlock(&stunaddr_lock);
9735 memcpy(&stunaddr_copy, &stunaddr,
sizeof(stunaddr));
9736 ast_rwlock_unlock(&stunaddr_lock);
9737 ast_cli(a->fd,
" STUN address: %s:%d\n",
ast_inet_ntoa(stunaddr_copy.sin_addr), htons(stunaddr_copy.sin_port));
9747 e->
command =
"rtcp set debug {on|off|ip}";
9749 "Usage: rtcp set debug {on|off|ip host[:port]}\n"
9750 " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
9751 " specified, limit the dumped packets to those to and from\n"
9752 " the specified 'host' with optional port.\n";
9758 if (a->argc == e->
args) {
9759 if (!strncasecmp(a->argv[e->
args-1],
"on", 2)) {
9760 ast_debug_category_set_sublevel(AST_LOG_CATEGORY_RTCP_PACKET, AST_LOG_CATEGORY_ENABLED);
9762 ast_cli(a->fd,
"RTCP Packet Debugging Enabled\n");
9764 }
else if (!strncasecmp(a->argv[e->
args-1],
"off", 3)) {
9765 ast_debug_category_set_sublevel(AST_LOG_CATEGORY_RTCP_PACKET, AST_LOG_CATEGORY_DISABLED);
9766 ast_cli(a->fd,
"RTCP Packet Debugging Disabled\n");
9769 }
else if (a->argc == e->
args +1) {
9770 return rtcp_do_debug_ip(a);
9773 return CLI_SHOWUSAGE;
9780 e->
command =
"rtcp set stats {on|off}";
9782 "Usage: rtcp set stats {on|off}\n"
9783 " Enable/Disable dumping of RTCP stats.\n";
9789 if (a->argc != e->
args)
9790 return CLI_SHOWUSAGE;
9792 if (!strncasecmp(a->argv[e->
args-1],
"on", 2))
9794 else if (!strncasecmp(a->argv[e->
args-1],
"off", 3))
9797 return CLI_SHOWUSAGE;
9799 ast_cli(a->fd,
"RTCP Stats %s\n",
rtcpstats ?
"Enabled" :
"Disabled");
9805 static unsigned int use_random(
struct ast_cli_args *a,
int pos,
unsigned int index)
9807 return pos >= index && !ast_strlen_zero(a->argv[index - 1]) &&
9808 !strcasecmp(a->argv[index - 1],
"random");
9813 static const char *
const completions_2[] = {
"stop",
"<N>", NULL };
9814 static const char *
const completions_3[] = {
"random",
"incoming packets", NULL };
9815 static const char *
const completions_5[] = {
"on",
"every", NULL };
9816 static const char *
const completions_units[] = {
"random",
"usec",
"msec",
"sec",
"min", NULL };
9818 unsigned int use_random_num = 0;
9819 unsigned int use_random_interval = 0;
9820 unsigned int num_to_drop = 0;
9821 unsigned int interval = 0;
9822 const char *interval_s = NULL;
9823 const char *unit_s = NULL;
9825 const char *addr_s = NULL;
9831 "Usage: rtp drop [stop|[<N> [random] incoming packets[ every <N> [random] {usec|msec|sec|min}][ on <ip[:port]>]]\n"
9832 " Drop RTP incoming packets.\n";
9835 use_random_num = use_random(a, a->pos, 4);
9836 use_random_interval = use_random(a, a->pos, 8 + use_random_num) ||
9837 use_random(a, a->pos, 10 + use_random_num);
9839 switch (a->pos - use_random_num - use_random_interval) {
9847 if (!strcasecmp(a->argv[a->pos - 2],
"on")) {
9853 if (!strcasecmp(a->argv[a->pos - 2 - use_random_interval],
"every")) {
9854 return ast_cli_complete(a->word, completions_units + use_random_interval, a->n);
9858 if (!strcasecmp(a->argv[a->pos - 3 - use_random_interval],
"every")) {
9868 return CLI_SHOWUSAGE;
9871 use_random_num = use_random(a, a->argc, 4);
9872 use_random_interval = use_random(a, a->argc, 8 + use_random_num) ||
9873 use_random(a, a->argc, 10 + use_random_num);
9875 if (!strcasecmp(a->argv[2],
"stop")) {
9877 }
else if (a->argc < 5) {
9878 return CLI_SHOWUSAGE;
9880 ast_cli(a->fd,
"%s is not a valid number of packets to drop\n", a->argv[2]);
9882 }
else if (a->argc - use_random_num == 5) {
9884 }
else if (a->argc - use_random_num >= 7 && !strcasecmp(a->argv[5 + use_random_num],
"on")) {
9886 addr_s = a->argv[6 + use_random_num];
9887 if (a->argc - use_random_num - use_random_interval == 10 &&
9888 !strcasecmp(a->argv[7 + use_random_num],
"every")) {
9890 interval_s = a->argv[8 + use_random_num];
9891 unit_s = a->argv[9 + use_random_num + use_random_interval];
9893 }
else if (a->argc - use_random_num >= 8 && !strcasecmp(a->argv[5 + use_random_num],
"every")) {
9895 interval_s = a->argv[6 + use_random_num];
9896 unit_s = a->argv[7 + use_random_num + use_random_interval];
9897 if (a->argc == 10 + use_random_num + use_random_interval &&
9898 !strcasecmp(a->argv[8 + use_random_num + use_random_interval],
"on")) {
9900 addr_s = a->argv[9 + use_random_num + use_random_interval];
9903 return CLI_SHOWUSAGE;
9906 if (a->argc - use_random_num >= 8 && !interval_s && !addr_s) {
9907 return CLI_SHOWUSAGE;
9911 ast_cli(a->fd,
"%s is not a valid interval number\n", interval_s);
9915 memset(&addr, 0,
sizeof(addr));
9917 ast_cli(a->fd,
"%s is not a valid hostname[:port]\n", addr_s);
9921 drop_packets_data.use_random_num = use_random_num;
9922 drop_packets_data.use_random_interval = use_random_interval;
9923 drop_packets_data.num_to_drop = num_to_drop;
9935 AST_CLI_DEFINE(handle_cli_rtp_set_debug,
"Enable/Disable RTP debugging"),
9936 AST_CLI_DEFINE(handle_cli_rtp_settings,
"Display RTP settings"),
9937 AST_CLI_DEFINE(handle_cli_rtcp_set_debug,
"Enable/Disable RTCP debugging"),
9938 AST_CLI_DEFINE(handle_cli_rtcp_set_stats,
"Enable/Disable RTCP stats"),
9940 AST_CLI_DEFINE(handle_cli_rtp_drop_incoming_packets,
"Drop RTP incoming packets"),
9950 #ifdef HAVE_PJPROJECT
9953 int acl_subscription_flag = 0;
9957 if (!cfg || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
9972 srtp_replay_protection = DEFAULT_SRTP_REPLAY_PROTECTION;
9982 #ifdef HAVE_PJPROJECT
9983 icesupport = DEFAULT_ICESUPPORT;
9984 stun_software_attribute = DEFAULT_STUN_SOFTWARE_ATTRIBUTE;
9985 turnport = DEFAULT_TURN_PORT;
9987 turnaddr = pj_str(NULL);
9988 turnusername = pj_str(NULL);
9989 turnpassword = pj_str(NULL);
9993 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
9994 dtls_mtu = DEFAULT_DTLS_MTU;
9997 if ((s = ast_variable_retrieve(cfg,
"general",
"rtpstart"))) {
10004 if ((s = ast_variable_retrieve(cfg,
"general",
"rtpend"))) {
10011 if ((s = ast_variable_retrieve(cfg,
"general",
"rtcpinterval"))) {
10020 if ((s = ast_variable_retrieve(cfg,
"general",
"rtpchecksums"))) {
10025 ast_log(LOG_WARNING,
"Disabling RTP checksums is not supported on this operating system!\n");
10028 if ((s = ast_variable_retrieve(cfg,
"general",
"dtmftimeout"))) {
10029 dtmftimeout = atoi(s);
10030 if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
10031 ast_log(LOG_WARNING,
"DTMF timeout of '%d' outside range, using default of '%d' instead\n",
10036 if ((s = ast_variable_retrieve(cfg,
"general",
"strictrtp"))) {
10039 }
else if (!strcasecmp(s,
"seqno")) {
10045 if ((s = ast_variable_retrieve(cfg,
"general",
"probation"))) {
10047 ast_log(LOG_WARNING,
"Value for 'probation' could not be read, using default of '%d' instead\n",
10048 DEFAULT_LEARNING_MIN_SEQUENTIAL);
10053 if ((s = ast_variable_retrieve(cfg,
"general",
"srtpreplayprotection"))) {
10054 srtp_replay_protection =
ast_true(s);
10056 #ifdef HAVE_PJPROJECT
10057 if ((s = ast_variable_retrieve(cfg,
"general",
"icesupport"))) {
10060 if ((s = ast_variable_retrieve(cfg,
"general",
"stun_software_attribute"))) {
10061 stun_software_attribute =
ast_true(s);
10063 if ((s = ast_variable_retrieve(cfg,
"general",
"stunaddr"))) {
10064 char *hostport, *host, *port;
10065 unsigned int port_parsed = STANDARD_STUN_PORT;
10070 if (!
ast_parse_arg(hostport, PARSE_ADDR, &stunaddr_parsed)) {
10071 ast_debug_stun(3,
"stunaddr = '%s' does not need name resolution\n",
10076 ast_rwlock_wrlock(&stunaddr_lock);
10078 ast_rwlock_unlock(&stunaddr_lock);
10081 ast_parse_arg(port, PARSE_UINT32|PARSE_IN_RANGE, &port_parsed, 1, 65535);
10083 stunaddr.sin_port = htons(port_parsed);
10086 &stunaddr_resolve_callback, NULL);
10087 if (!stunaddr_resolver) {
10088 ast_log(LOG_ERROR,
"Failed to setup recurring DNS resolution of stunaddr '%s'",
10092 ast_log(LOG_ERROR,
"Failed to parse stunaddr '%s'", hostport);
10095 if ((s = ast_variable_retrieve(cfg,
"general",
"turnaddr"))) {
10096 struct sockaddr_in addr;
10097 addr.sin_port = htons(DEFAULT_TURN_PORT);
10099 ast_log(LOG_WARNING,
"Invalid TURN server address: %s\n", s);
10101 pj_strdup2_with_null(pool, &turnaddr,
ast_inet_ntoa(addr.sin_addr));
10104 turnport = ntohs(addr.sin_port);
10107 if ((s = ast_variable_retrieve(cfg,
"general",
"turnusername"))) {
10108 pj_strdup2_with_null(pool, &turnusername, s);
10110 if ((s = ast_variable_retrieve(cfg,
"general",
"turnpassword"))) {
10111 pj_strdup2_with_null(pool, &turnpassword, s);
10115 for (var = ast_variable_browse(cfg,
"ice_host_candidates"); var; var = var->
next) {
10117 unsigned int include_local_address = 0;
10124 ast_log(LOG_WARNING,
"Invalid local ICE host address: %s\n", var->
name);
10128 sep = strchr(var->
value,
',');
10133 include_local_address = strcmp(sep,
"include_local_address") == 0;
10137 ast_log(LOG_WARNING,
"Invalid advertised ICE host address: %s\n", var->
value);
10141 if (!(candidate =
ast_calloc(1,
sizeof(*candidate)))) {
10142 ast_log(LOG_ERROR,
"Failed to allocate ICE host candidate mapping.\n");
10146 candidate->include_local = include_local_address;
10155 ast_rwlock_wrlock(&ice_acl_lock);
10156 ast_rwlock_wrlock(&stun_acl_lock);
10161 for (var = ast_variable_browse(cfg,
"general"); var; var = var->
next) {
10162 const char* sense = NULL;
10164 if (strncasecmp(var->
name,
"ice_", 4) == 0) {
10165 sense = var->
name + 4;
10167 }
else if (strncasecmp(var->
name,
"stun_", 5) == 0) {
10168 sense = var->
name + 5;
10174 if (strcasecmp(sense,
"blacklist") == 0) {
10178 if (strcasecmp(sense,
"acl") && strcasecmp(sense,
"permit") && strcasecmp(sense,
"deny")) {
10184 ast_rwlock_unlock(&ice_acl_lock);
10185 ast_rwlock_unlock(&stun_acl_lock);
10187 if (acl_subscription_flag && !acl_change_sub) {
10188 acl_change_sub = stasis_subscribe(
ast_security_topic(), acl_change_stasis_cb, NULL);
10191 }
else if (!acl_subscription_flag && acl_change_sub) {
10195 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP)
10196 if ((s = ast_variable_retrieve(cfg,
"general",
"dtls_mtu"))) {
10197 if ((sscanf(s,
"%d", &dtls_mtu) != 1) || dtls_mtu < 256) {
10198 ast_log(LOG_WARNING,
"Value for 'dtls_mtu' could not be read, using default of '%d' instead\n",
10200 dtls_mtu = DEFAULT_DTLS_MTU;
10209 if (rtpstart & 1) {
10211 ast_log(LOG_WARNING,
"Odd start value for RTP port in rtp.conf, rounding up to %d\n", rtpstart);
10214 if (rtpstart >=
rtpend) {
10215 ast_log(LOG_WARNING,
"Unreasonable values for RTP start/end port in rtp.conf\n");
10219 ast_verb(2,
"RTP Allocating from port range %d -> %d\n", rtpstart,
rtpend);
10223 static int reload_module(
void)
10229 #ifdef HAVE_PJPROJECT
10230 static void rtp_terminate_pjproject(
void)
10255 static int load_module(
void)
10257 #ifdef HAVE_PJPROJECT
10263 if (pj_init() != PJ_SUCCESS) {
10267 if (pjlib_util_init() != PJ_SUCCESS) {
10268 rtp_terminate_pjproject();
10272 if (pjnath_init() != PJ_SUCCESS) {
10273 rtp_terminate_pjproject();
10279 pool = pj_pool_create(&
cachingpool.factory,
"timer", 512, 512, NULL);
10281 if (pj_timer_heap_create(pool, 100, &
timer_heap) != PJ_SUCCESS) {
10282 rtp_terminate_pjproject();
10286 if (pj_lock_create_recursive_mutex(pool,
"rtp%p", &lock) != PJ_SUCCESS) {
10287 rtp_terminate_pjproject();
10291 pj_timer_heap_set_lock(
timer_heap, lock, PJ_TRUE);
10294 rtp_terminate_pjproject();
10300 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP) && defined(HAVE_OPENSSL_BIO_METHOD)
10301 dtls_bio_methods = BIO_meth_new(BIO_TYPE_BIO,
"rtp write");
10302 if (!dtls_bio_methods) {
10303 #ifdef HAVE_PJPROJECT
10304 rtp_terminate_pjproject();
10308 BIO_meth_set_write(dtls_bio_methods, dtls_bio_write);
10309 BIO_meth_set_ctrl(dtls_bio_methods, dtls_bio_ctrl);
10310 BIO_meth_set_create(dtls_bio_methods, dtls_bio_new);
10311 BIO_meth_set_destroy(dtls_bio_methods, dtls_bio_free);
10314 if (ast_rtp_engine_register(&asterisk_rtp_engine)) {
10315 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP) && defined(HAVE_OPENSSL_BIO_METHOD)
10316 BIO_meth_free(dtls_bio_methods);
10318 #ifdef HAVE_PJPROJECT
10319 rtp_terminate_pjproject();
10325 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP) && defined(HAVE_OPENSSL_BIO_METHOD)
10326 BIO_meth_free(dtls_bio_methods);
10328 #ifdef HAVE_PJPROJECT
10330 rtp_terminate_pjproject();
10340 static int unload_module(
void)
10345 #if defined(HAVE_OPENSSL) && (OPENSSL_VERSION_NUMBER >= 0x10001000L) && !defined(OPENSSL_NO_SRTP) && defined(HAVE_OPENSSL_BIO_METHOD)
10346 if (dtls_bio_methods) {
10347 BIO_meth_free(dtls_bio_methods);
10351 #ifdef HAVE_PJPROJECT
10354 rtp_terminate_pjproject();
10357 rtp_unload_acl(&ice_acl_lock, &ice_acl);
10358 rtp_unload_acl(&stun_acl_lock, &stun_acl);
10365 AST_MODULE_INFO(
ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER,
"Asterisk RTP Stack",
10366 .support_level = AST_MODULE_SUPPORT_CORE,
10367 .load = load_module,
10368 .unload = unload_module,
10369 .reload = reload_module,
10371 #ifdef HAVE_PJPROJECT
10372 .requires =
"res_pjproject",
static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data)
static struct ast_rtp_instance * rtp_find_instance_by_media_source_ssrc(struct ast_rtp_instance *instance, struct ast_rtp *rtp, unsigned int ssrc)
#define AST_VECTOR_FREE(vec)
Deallocates this vector.
struct stasis_message_type * ast_rtp_rtcp_sent_type(void)
Message type for an RTCP message sent from this Asterisk instance.
struct ast_variable * next
struct ast_rtp_instance * instance
The RTP instance this SSRC belongs to.
#define AST_THREADSTORAGE(name)
Define a thread storage variable.
double local_normdevrxploss
static char * generate_random_string(char *buf, size_t size)
Generate 32 byte random string (stolen from chan_sip.c)
An object that represents data sent during a SR/RR RTCP report.
static int rtp_reload(int reload, int by_external_config)
#define DEFAULT_STRICT_RTP
Main Channel structure associated with a channel.
Structure used for mapping an incoming SSRC to an RTP instance.
double reported_stdev_jitter
static void ast_rtp_ice_start(struct ast_rtp_instance *instance)
#define ast_frdup(fr)
Copies a frame.
#define AST_VECTOR_ADD_SORTED(vec, elem, cmp)
Add an element into a sorted vector.
ssize_t ast_sendto(int sockfd, const void *buf, size_t len, int flags, const struct ast_sockaddr *dest_addr)
Wrapper around sendto(2) that uses ast_sockaddr.
struct rtp_transport_wide_cc_statistics::@478 packet_statistics
ast_rtp_dtls_verify
DTLS verification settings.
double reported_stdev_lost
int(* set_configuration)(struct ast_rtp_instance *instance, const struct ast_rtp_dtls_cfg *dtls_cfg)
Security Event Reporting API.
#define AST_LIST_LOCK(head)
Locks a list.
const struct ast_dns_record * ast_dns_record_get_next(const struct ast_dns_record *record)
Get the next DNS record.
struct ast_rtp_payload_type * ast_rtp_codecs_get_payload(struct ast_rtp_codecs *codecs, int payload)
Retrieve rx payload mapped information by payload type.
List of ICE host candidate mappings.
Asterisk locking-related definitions:
Asterisk main include file. File version handling, generic pbx functions.
Data buffer containing fixed number of data payloads.
#define AST_LIST_FIRST(head)
Returns the first entry contained in a list.
const char * ast_dns_record_get_data(const struct ast_dns_record *record)
Retrieve the raw DNS record.
static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1)
int ao2_container_count(struct ao2_container *c)
Returns the number of elements in a container.
enum strict_rtp_state strict_rtp_state
ast_suseconds_t ast_time_tv_to_usec(const struct timeval *tv)
Convert a timeval structure to microseconds.
struct ast_data_buffer * ast_data_buffer_alloc(ast_data_buffer_free_callback free_fn, size_t size)
Allocate a data buffer.
void * ast_data_buffer_remove(struct ast_data_buffer *buffer, size_t pos)
Remove a data payload from the data buffer.
void * ast_threadstorage_get(struct ast_threadstorage *ts, size_t init_size)
Retrieve thread storage.
struct ast_json * ast_json_pack(char const *format,...)
Helper for creating complex JSON values.
int ast_rtp_instance_extmap_get_id(struct ast_rtp_instance *instance, enum ast_rtp_extension extension)
Retrieve the id for an RTP extension.
const char * ast_dns_query_get_name(const struct ast_dns_query *query)
Get the name queried in a DNS query.
unsigned int feedback_count
int ast_parse_arg(const char *arg, enum ast_parse_flags flags, void *p_result,...)
The argument parsing routine.
static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
unsigned int rxjitter_count
int ast_sockaddr_parse(struct ast_sockaddr *addr, const char *str, int flags)
Parse an IPv4 or IPv6 address string.
static int rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
Structure for storing RTP packets for retransmission.
double remote_normdevjitter
#define AST_VECTOR_REMOVE_CMP_UNORDERED(vec, value, cmp, cleanup)
Remove an element from a vector that matches the given comparison.
int ast_find_ourip(struct ast_sockaddr *ourip, const struct ast_sockaddr *bindaddr, int family)
Find our IP address.
#define AST_RTP_RTCP_FMT_NACK
int ast_cli_unregister_multiple(struct ast_cli_entry *e, int len)
Unregister multiple commands.
Statistics information (used for transport-cc)
unsigned int ast_sec2samp(double _seconds, int _rate)
Returns the number of samples at _rate in the duration in _seconds.
#define DEFAULT_DTMF_TIMEOUT
static void ast_sockaddr_copy(struct ast_sockaddr *dst, const struct ast_sockaddr *src)
Copies the data from one ast_sockaddr to another.
static struct ast_rtp_instance * __rtp_find_instance_by_ssrc(struct ast_rtp_instance *instance, struct ast_rtp *rtp, unsigned int ssrc, int source)
static int ast_rtcp_write(const void *data)
Write a RTCP packet to the far end.
void ast_json_unref(struct ast_json *value)
Decrease refcount on value. If refcount reaches zero, value is freed.
static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp)
static int compare_by_value(int elem, int value)
Helper function to compare an elem in a vector by value.
#define AST_RTP_RTCP_FMT_PLI
#define MISSING_SEQNOS_ADDED_TRIGGER
struct ast_rtp_instance * owner
The RTP instance owning us (used for debugging purposes) We don't hold a reference to the instance be...
RTP learning mode tracking information.
static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
unsigned int rxlost_count
Structure which contains ioqueue thread information.
struct ast_rtp_codecs * ast_rtp_instance_get_codecs(struct ast_rtp_instance *instance)
Get the codecs structure of an RTP instance.
struct ast_data_buffer * send_buffer
descriptor for a cli entry.
Packet statistics (used for transport-cc)
#define AST_LIST_UNLOCK(head)
Attempts to unlock a list.
double reported_minjitter
double remote_stdevjitter
#define ast_socket_nonblock(domain, type, protocol)
Create a non-blocking socket.
struct ast_sockaddr proposed_address
#define AST_RWLIST_RDLOCK(head)
Read locks a list.
static pj_caching_pool cachingpool
Pool factory used by pjlib to allocate memory.
int ast_sockaddr_ipv4_mapped(const struct ast_sockaddr *addr, struct ast_sockaddr *ast_mapped)
Convert an IPv4-mapped IPv6 address into an IPv4 address.
#define ao2_container_alloc_list(ao2_options, container_options, sort_fn, cmp_fn)
Allocate and initialize a list container.
const char * ast_codec_media_type2str(enum ast_media_type type)
Conversion function to take a media type and turn it into a string.
struct ast_config * ast_config_load2(const char *filename, const char *who_asked, struct ast_flags flags)
Load a config file.
Structure for variables, used for configurations and for channel variables.
static void rtp_learning_start(struct ast_rtp *rtp)
Start the strictrtp learning mode.
static pj_pool_t * pool
Global memory pool for configuration and timers.
#define AST_VECTOR_APPEND(vec, elem)
Append an element to a vector, growing the vector if needed.
static ast_rwlock_t stunaddr_lock
#define RTCP_MIN_INTERVALMS
#define MAX_TIMESTAMP_SKEW
struct timeval ast_time_create_by_unit_str(unsigned long val, const char *unit)
Convert the given unit value, and create a timeval object from it.
static struct ast_sockaddr address
Address for UDPTL.
static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
static void ice_wrap_dtor(void *vdoomed)
ao2 ICE wrapper object destructor.
Universally unique identifier support.
int ast_tvzero(const struct timeval t)
Returns true if the argument is 0,0.
int terminate
Termination request.
struct ast_rtp_instance * bundled
An object that represents data received in a feedback report.
#define AST_LIST_NEXT(elm, field)
Returns the next entry in the list after the given entry.
static int ioqueue_worker_thread(void *data)
Worker thread for ioqueue and timerheap.
struct ast_rtp_rtcp_report_block * report_block[0]
struct stasis_message_type * stasis_message_type(const struct stasis_message *msg)
Get the message type for a stasis_message.
int stasis_subscription_set_filter(struct stasis_subscription *subscription, enum stasis_subscription_message_filter filter)
Set the message type filtering level on a subscription.
#define AST_RWLIST_WRLOCK(head)
Write locks a list.
struct stasis_message_type * ast_named_acl_change_type(void)
a stasis_message_type for changes against a named ACL or the set of all named ACLs ...
static struct ast_rtp_instance * rtp_find_instance_by_packet_source_ssrc(struct ast_rtp_instance *instance, struct ast_rtp *rtp, unsigned int ssrc)
#define AST_SCHED_DEL_UNREF(sched, id, refcall)
schedule task to get deleted and call unref function
#define MAXIMUM_RTP_SEND_BUFFER_SIZE
size_t ast_dns_record_get_data_size(const struct ast_dns_record *record)
Retrieve the size of the raw DNS record.
#define ast_cli_register_multiple(e, len)
Register multiple commands.
unsigned int rtp_passthrough
void ao2_iterator_destroy(struct ao2_iterator *iter)
Destroy a container iterator.
struct ast_srtp * ast_rtp_instance_get_srtp(struct ast_rtp_instance *instance, int rtcp)
Obtain the SRTP instance associated with an RTP instance.
struct timeval ast_tvnow(void)
Returns current timeval. Meant to replace calls to gettimeofday().
ast_rtp_extension
Known RTP extensions.
A report block within a SR/RR report.
Wrapper for an ast_acl linked list.
#define SSRC_MAPPING_ELEM_CMP(elem, value)
SSRC mapping comparator for AST_VECTOR_REMOVE_CMP_UNORDERED()
static const char * ast_rtp_ice_get_ufrag(struct ast_rtp_instance *instance)
#define ast_debug_ice(sublevel,...)
Log debug level ICE information.
void ast_rtp_instance_set_last_tx(struct ast_rtp_instance *rtp, time_t time)
Set the last RTP transmission time.
optional_ts last_end_timestamp
int64_t ast_tvdiff_ms(struct timeval end, struct timeval start)
Computes the difference (in milliseconds) between two struct timeval instances.
#define ast_strdup(str)
A wrapper for strdup()
struct rtp_transport_wide_cc_statistics transport_wide_cc
struct ast_rtp_rtcp_feedback_remb remb
static int timer_worker_thread(void *data)
Worker thread for timerheap.
int ast_sockaddr_cmp(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares two ast_sockaddr structures.
static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
enum ast_acl_sense ast_apply_acl_nolog(struct ast_acl_list *acl_list, const struct ast_sockaddr *addr)
Apply a set of rules to a given IP address, don't log failure.
int ast_rtp_instance_add_srtp_policy(struct ast_rtp_instance *instance, struct ast_srtp_policy *remote_policy, struct ast_srtp_policy *local_policy, int rtcp)
Add or replace the SRTP policies for the given RTP instance.
#define AST_LIST_REMOVE(head, elm, field)
Removes a specific entry from a list.
static void ast_rtp_update_source(struct ast_rtp_instance *instance)
struct ast_data_buffer * recv_buffer
struct ao2_container * ice_active_remote_candidates
int ast_stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
handle an incoming STUN message.
Structure for an ICE candidate.
void ast_free_ptr(void *ptr)
free() wrapper
void ast_pjproject_caching_pool_init(pj_caching_pool *cp, const pj_pool_factory_policy *policy, pj_size_t max_capacity)
Initialize the caching pool factory.
static int ast_rtp_destroy(struct ast_rtp_instance *instance)
Socket address structure.
Asterisk internal frame definitions.
int ast_bind(int sockfd, const struct ast_sockaddr *addr)
Wrapper around bind(2) that uses struct ast_sockaddr.
int ast_sockaddr_cmp_addr(const struct ast_sockaddr *a, const struct ast_sockaddr *b)
Compares the addresses of two ast_sockaddr structures.
unsigned int expected_prior
static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username)
#define RTCP_MAX_INTERVALMS
int ast_rtp_codecs_payload_code_tx(struct ast_rtp_codecs *codecs, int asterisk_format, const struct ast_format *format, int code)
Retrieve a tx mapped payload type based on whether it is an Asterisk format and the code...
unsigned int ast_rtp_codecs_get_framing(struct ast_rtp_codecs *codecs)
Get the framing used for a set of codecs.
static void ast_rtp_ice_stop(struct ast_rtp_instance *instance)
static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
struct stasis_message_type * ast_rtp_rtcp_received_type(void)
Message type for an RTCP message received from some external source.
struct ast_frame_subclass subclass
static void pj_thread_register_check(void)
Function used to check if the calling thread is registered with pjlib. If it is not it will be regist...
pj_thread_t * thread
The thread handling the queue and timer heap.
const char * ast_rtp_instance_get_channel_id(struct ast_rtp_instance *instance)
Get the unique ID of the channel that owns this RTP instance.
static void ast_sockaddr_setnull(struct ast_sockaddr *addr)
Sets address addr to null.
int args
This gets set in ast_cli_register()
struct ast_dns_query_recurring * ast_dns_resolve_recurring(const char *name, int rr_type, int rr_class, ast_dns_resolve_callback callback, void *data)
Asynchronously resolve a DNS query, and continue resolving it according to the lowest TTL available...
static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
struct ao2_container * ice_proposed_remote_candidates
static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
int ast_data_buffer_put(struct ast_data_buffer *buffer, size_t pos, void *payload)
Place a data payload at a position in the data buffer.
char * ast_cli_complete(const char *word, const char *const choices[], int pos)
#define AST_RED_MAX_GENERATION
#define AST_RWLIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a read/write list of specified type, statically initialized...
static int ast_sockaddr_isnull(const struct ast_sockaddr *addr)
Checks if the ast_sockaddr is null. "null" in this sense essentially means uninitialized, or having a 0 length.
#define ao2_bump(obj)
Bump refcount on an AO2 object by one, returning the object.
#define ast_sockaddr_port(addr)
Get the port number of a socket address.
enum ast_rtp_ice_candidate_type type
struct ast_rtp_ioqueue_thread * ioqueue
void * ao2_object_get_lockaddr(void *obj)
Return the mutex lock address of an object.
int ast_dns_resolve_recurring_cancel(struct ast_dns_query_recurring *recurring)
Cancel an asynchronous recurring DNS resolution.
Configuration File Parser.
static const char * ast_rtp_ice_get_password(struct ast_rtp_instance *instance)
struct ast_sockaddr rtp_loop
int ast_ouraddrfor(const struct ast_sockaddr *them, struct ast_sockaddr *us)
Get our local IP address when contacting a remote host.
Handle unaligned data access.
int ast_sockaddr_is_any(const struct ast_sockaddr *addr)
Determine if the address type is unspecified, or "any" address.
static void cleanup(void)
Clean up any old apps that we don't need any more.
char cname[AST_UUID_STR_LEN]
int ast_dns_result_get_lowest_ttl(const struct ast_dns_result *result)
Retrieve the lowest TTL from a result.
#define AST_VECTOR_INIT(vec, size)
Initialize a vector.
unsigned int rxoctetcount
int ast_sockaddr_split_hostport(char *str, char **host, char **port, int flags)
Splits a string into its host and port components.
struct ast_sockaddr rtcp_loop
General Asterisk PBX channel definitions.
#define AST_VECTOR_GET_ADDR(vec, idx)
Get an address of element in a vector.
#define AST_SCHED_DEL(sched, id)
Remove a scheduler entry.
double accumulated_transit
#define AST_FRIENDLY_OFFSET
Offset into a frame's data buffer.
#define ast_sockaddr_from_sin(addr, sin)
Converts a struct sockaddr_in to a struct ast_sockaddr.
int ast_rtp_engine_unregister(struct ast_rtp_engine *engine)
Unregister an RTP engine.
void ast_rtp_instance_set_data(struct ast_rtp_instance *instance, void *data)
Set the data portion of an RTP instance.
#define AST_VECTOR_ELEM_CLEANUP_NOOP(elem)
Vector element cleanup that does nothing.
static void ast_rtp_ice_candidate_destroy(void *obj)
Destructor for locally created ICE candidates.
static int ice_reset_session(struct ast_rtp_instance *instance)
unsigned int last_extended_seqno
#define ast_strdupa(s)
duplicate a string in memory from the stack
double reported_normdev_lost
int ast_stun_request(int s, struct sockaddr_in *dst, const char *username, struct sockaddr_in *answer)
Generic STUN request.
struct ast_sockaddr ice_original_rtp_addr
ast_rtp_ice_role
ICE role during negotiation.
Access Control of various sorts.
static struct ao2_container * codecs
Registered codecs.
static struct ast_sockaddr rtpdebugaddr
static void rtp_add_candidates_to_ice(struct ast_rtp_instance *instance, struct ast_rtp *rtp, struct ast_sockaddr *addr, int port, int component, int transport)
#define ao2_ref(o, delta)
Reference/unreference an object and return the old refcount.
static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
structure to hold extensions
Asterisk internal frame definitions.
static struct ast_sockaddr rtcpdebugaddr
#define MAXIMUM_RTP_RECV_BUFFER_SIZE
static void ast_rtp_ice_set_authentication(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
Conversion utility functions.
char channel_uniqueid[MAX_CHANNEL_ID]
struct timeval ast_samp2tv(unsigned int _nsamp, unsigned int _rate)
Returns a timeval corresponding to the duration of n samples at rate r. Useful to convert samples to ...
ast_rtp_ice_component_type
ICE component types.
static void ast_rtp_ice_change_components(struct ast_rtp_instance *instance, int num_components)
unsigned int dtmf_samplerate_ms
static struct ast_acl_list * stun_acl
#define AST_RTP_RTCP_RTPFB
unsigned int ast_codec_samples_count(struct ast_frame *frame)
Get the number of samples contained within a frame.
double reported_normdev_mes
enum ast_rtp_dtls_hash hash
double local_stdevrxploss
#define ast_malloc(len)
A wrapper for malloc()
#define ast_debug(level,...)
Log a DEBUG message.
struct ast_rtp::@480 ssrc_mapping
#define AST_VECTOR(name, type)
Define a vector structure.
#define AST_LIST_REMOVE_HEAD(head, field)
Removes and returns the head entry from a list.
unsigned int themssrc_valid
static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
void * ast_data_buffer_get(const struct ast_data_buffer *buffer, size_t pos)
Retrieve a data payload from the data buffer.
static struct ast_acl_list * ice_acl
void ast_rtp_publish_rtcp_message(struct ast_rtp_instance *rtp, struct stasis_message_type *message_type, struct ast_rtp_rtcp_report *report, struct ast_json *blob)
Publish an RTCP message to Stasis Message Bus API.
unsigned int txoctetcount
static void ast_rtp_stop(struct ast_rtp_instance *instance)
#define STRICT_RTP_LEARN_TIMEOUT
Strict RTP learning timeout time in milliseconds.
Structure to describe a channel "technology", ie a channel driver See for examples: ...
struct ast_sockaddr relay_address
Core PBX routines and definitions.
double remote_normdevrxploss
struct ast_rtp_rtcp_report * ast_rtp_rtcp_report_alloc(unsigned int report_blocks)
Allocate an ao2 ref counted instance of ast_rtp_rtcp_report.
Structure that represents the optional DTLS SRTP support within an RTP engine.
static int ast_rtp_bundle(struct ast_rtp_instance *child, struct ast_rtp_instance *parent)
unsigned int last_transit_time_samples
static struct ast_frame * ast_rtcp_interpret(struct ast_rtp_instance *instance, struct ast_srtp *srtp, const unsigned char *rtcpdata, size_t size, struct ast_sockaddr *addr)
int ast_rtp_instance_set_local_address(struct ast_rtp_instance *instance, const struct ast_sockaddr *address)
Set the address that we are expecting to receive RTP on.
#define AST_LIST_HEAD_STATIC(name, type)
Defines a structure to be used to hold a list of specified type, statically initialized.
The result of a DNS query.
#define ast_test_suite_event_notify(s, f,...)
static int timer_terminate
Used to tell the timer thread to terminate.
ast_frame_type
Frame types.
ast_rtp_dtls_setup
DTLS setup types.
#define ast_debug_stun(sublevel,...)
Log debug level STUN information.
The AMI - Asterisk Manager Interface - is a TCP protocol created to manage Asterisk with third-party ...
#define AST_LIST_HEAD_NOLOCK(name, type)
Defines a structure to be used to hold a list of specified type (with no lock).
static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
double ast_samp2sec(unsigned int _nsamp, unsigned int _rate)
Returns the duration in seconds of _nsamp samples at rate _rate.
static pj_thread_t * timer_thread
Thread executing the timer heap.
enum ast_rtp_dtls_setup default_setup
void(* set_authentication)(struct ast_rtp_instance *instance, const char *ufrag, const char *password)
int ast_tvcmp(struct timeval _a, struct timeval _b)
Compress two struct timeval instances returning -1, 0, 1 if the first arg is smaller, equal or greater to the second.
#define AST_LIST_INSERT_TAIL(head, elm, field)
Appends a list entry to the tail of a list.
unsigned int reported_lost_count
unsigned int ice_media_started
int attribute_pure ast_true(const char *val)
Make sure something is true. Determine if a string containing a boolean value is "true". This function checks to see whether a string passed to it is an indication of an "true" value. It checks to see if the string is "yes", "true", "y", "t", "on" or "1".
#define DEFAULT_RTP_START
unsigned int reported_lost
unsigned int rxoctetcount
unsigned int received_prior
static void ast_rtp_ice_add_cand(struct ast_rtp_instance *instance, struct ast_rtp *rtp, unsigned comp_id, unsigned transport_id, pj_ice_cand_type type, pj_uint16_t local_pref, const pj_sockaddr_t *addr, const pj_sockaddr_t *base_addr, const pj_sockaddr_t *rel_addr, int addr_len)
enum ast_rtp_dtls_verify verify
static void host_candidate_overrides_clear(void)
Helper function which clears the ICE host candidate mapping.
#define ast_sockaddr_set_port(addr, port)
Sets the port number of a socket address.
#define ast_sockaddr_from_sockaddr(addr, sa)
Converts a struct sockaddr to a struct ast_sockaddr.
ast_rtp_dtls_connection
DTLS connection states.
static struct ast_frame * ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
struct ast_dns_result * ast_dns_query_get_result(const struct ast_dns_query *query)
Get the result information for a DNS query.
int ast_set_qos(int sockfd, int tos, int cos, const char *desc)
Set type of service.
struct ast_acl_list * ast_free_acl_list(struct ast_acl_list *acl)
Free a list of ACLs.
#define ast_rtp_instance_set_remote_address(instance, address)
Set the address of the remote endpoint that we are sending RTP to.
unsigned int remote_seed_rx_rtp_ts
static struct ast_frame * ast_rtcp_read(struct ast_rtp_instance *instance)
enum ast_rtp_ice_component_type id
unsigned int dtmf_timeout
#define AST_PJPROJECT_INIT_LOG_LEVEL()
Get maximum log level pjproject was compiled with.
struct ast_format * ast_rtp_codecs_get_preferred_format(struct ast_rtp_codecs *codecs)
Retrieve rx preferred format.
struct timeval ast_tvadd(struct timeval a, struct timeval b)
Returns the sum of two timevals a + b.
unsigned int ast_rtp_instance_get_ssrc(struct ast_rtp_instance *rtp)
Retrieve the local SSRC value that we will be using.
static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
static char * ast_sockaddr_stringify(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() with default format.
ssize_t ast_recvfrom(int sockfd, void *buf, size_t len, int flags, struct ast_sockaddr *src_addr)
Wrapper around recvfrom(2) that uses struct ast_sockaddr.
char * ast_skip_blanks(const char *str)
Gets a pointer to the first non-whitespace character in a string.
static const char * ast_rtp_get_cname(struct ast_rtp_instance *instance)
#define ast_strndup(str, len)
A wrapper for strndup()
static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp, int *via_ice, int use_srtp)
pj_ioqueue_t * ioqueue
Ioqueue which polls on sockets.
#define AST_RTP_RTCP_FMT_TRANSPORT_WIDE_CC
ast_rtp_dtls_hash
DTLS fingerprint hashes.
static int ast_rtp_rtcp_handle_nack(struct ast_rtp_instance *instance, unsigned int *nackdata, unsigned int position, unsigned int length)
void ast_pjproject_caching_pool_destroy(pj_caching_pool *cp)
Destroy caching pool factory and all cached pools.
#define AST_RTP_RTCP_FMT_FIR
#define AST_LIST_TRAVERSE(head, var, field)
Loops over (traverses) the entries in a list.
#define AST_LIST_ENTRY(type)
Declare a forward link structure inside a list entry.
#define AST_LIST_INSERT_HEAD(head, elm, field)
Inserts a list entry at the head of a list.
static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level)
generate comfort noice (CNG)
Internal DNS structure definitions.
#define AST_RTP_CISCO_DTMF
double reported_maxjitter
static void update_address_with_ice_candidate(pj_ice_sess *ice, enum ast_rtp_ice_component_type component, struct ast_sockaddr *cand_address)
Helper function which updates an ast_sockaddr with the candidate used for the component.
static struct ao2_container * ast_rtp_ice_get_local_candidates(struct ast_rtp_instance *instance)
enum ast_rtp_ice_role role
const char * ast_inet_ntoa(struct in_addr ia)
thread-safe replacement for inet_ntoa().
union ast_frame::@224 data
Structure defining an RTCP session.
#define RTCP_DEFAULT_INTERVALMS
#define ast_calloc(num, len)
A wrapper for calloc()
#define AST_VECTOR_RESET(vec, cleanup)
Reset vector.
void * ast_rtp_instance_get_data(struct ast_rtp_instance *instance)
Get the data portion of an RTP instance.
enum ast_media_type stream_type
unsigned int reported_mes_count
static unsigned int ast_rtp_get_ssrc(struct ast_rtp_instance *instance)
struct ast_rtp::@479 missing_seqno
unsigned int frame_ending
struct ast_sockaddr strict_rtp_address
#define DEFAULT_RTP_RECV_BUFFER_SIZE
unsigned char pt[AST_RED_MAX_GENERATION]
char * ast_uuid_generate_str(char *buf, size_t size)
Generate a UUID string.
static void ast_rtp_set_remote_ssrc(struct ast_rtp_instance *instance, unsigned int ssrc)
struct stasis_subscription * stasis_unsubscribe_and_join(struct stasis_subscription *subscription)
Cancel a subscription, blocking until the last message is processed.
int ast_sched_del(struct ast_sched_context *con, int id) attribute_warn_unused_result
Deletes a scheduled event.
Module has failed to load, may be in an inconsistent state.
const struct ast_dns_record * ast_dns_result_get_records(const struct ast_dns_result *result)
Get the first record of a DNS Result.
#define ast_frisolate(fr)
Makes a frame independent of any static storage.
unsigned int ephemeral_cert
struct ao2_container * ice_local_candidates
int ast_str_to_uint(const char *str, unsigned int *res)
Convert the given string to an unsigned integer.
#define AST_VECTOR_GET_CMP(vec, value, cmp)
Get an element from a vector that matches the given comparison.
int ast_sched_add(struct ast_sched_context *con, int when, ast_sched_cb callback, const void *data) attribute_warn_unused_result
Adds a scheduled event.
void ast_rtp_instance_get_local_address(struct ast_rtp_instance *instance, struct ast_sockaddr *address)
Get the local address that we are expecting RTP on.
Structure used to handle boolean flags.
unsigned int dtmf_duration
#define AST_VECTOR_REMOVE_CMP_ORDERED(vec, value, cmp, cleanup)
Remove an element from a vector that matches the given comparison while maintaining order...
int ast_rtp_get_rate(const struct ast_format *format)
Retrieve the sample rate of a format according to RTP specifications.
unsigned int lastsrtxcount
static void ast_rtp_ice_add_remote_candidate(struct ast_rtp_instance *instance, const struct ast_rtp_engine_ice_candidate *candidate)
#define DEFAULT_RTP_SEND_BUFFER_SIZE
static void ast_rtp_change_source(struct ast_rtp_instance *instance)
struct ast_frame ast_null_frame
static int learning_min_duration
#define ast_debug_dtls(sublevel,...)
Log debug level DTLS information.
static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance, struct ast_rtp_instance *instance1, unsigned int *rtpheader, int len, int hdrlen)
int ast_rtp_codecs_payload_code_tx_sample_rate(struct ast_rtp_codecs *codecs, int asterisk_format, const struct ast_format *format, int code, unsigned int sample_rate)
Retrieve a tx mapped payload type based on whether it is an Asterisk format and the code...
unsigned int txoctetcount
#define AST_LIST_HEAD_INIT_NOLOCK(head)
Initializes a list head structure.
unsigned char buf_data[64000]
static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
static void rtp_ioqueue_thread_remove(struct ast_rtp_ioqueue_thread *ioqueue)
Removal function for ioqueue thread, determines if it should be terminated and destroyed.
unsigned char len[AST_RED_MAX_GENERATION]
static struct stasis_subscription * acl_change_sub
#define ao2_replace(dst, src)
Replace one object reference with another cleaning up the original.
pj_turn_state_t turn_state
When we need to walk through a container, we use an ao2_iterator to keep track of the current positio...
#define ast_debug_rtp(sublevel,...)
Log debug level RTP information.
Structure for rwlock and tracking information.
static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
Standard Command Line Interface.
void ast_copy_string(char *dst, const char *src, size_t size)
Size-limited null-terminating string copy.
void ast_append_acl(const char *sense, const char *stuff, struct ast_acl_list **path, int *error, int *named_acl_flag)
Add a rule to an ACL struct.
#define S_OR(a, b)
returns the equivalent of logic or for strings: first one if not empty, otherwise second one...
struct timeval ast_tv(ast_time_t sec, ast_suseconds_t usec)
Returns a timeval from sec, usec.
size_t ast_data_buffer_count(const struct ast_data_buffer *buffer)
Return the number of payloads in a data buffer.
unsigned int remote_seed_rx_rtp_ts_stable
int attribute_pure ast_false(const char *val)
Make sure something is false. Determine if a string containing a boolean value is "false"...
struct ast_rtp_instance * ast_rtp_instance_get_bridged(struct ast_rtp_instance *instance)
Get the other RTP instance that an instance is bridged to.
void ast_rtp_instance_get_requested_target_address(struct ast_rtp_instance *instance, struct ast_sockaddr *address)
Get the requested target address of the remote endpoint.
int ast_rtp_instance_get_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property)
Get the value of an RTP instance property.
static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
Structure which contains ICE host candidate mapping information.
static int learning_min_sequential
int ast_sockaddr_is_ipv4(const struct ast_sockaddr *addr)
Determine if the address is an IPv4 address.
pj_pool_t * pool
Pool used by the thread.
static struct ast_rtp_ioqueue_thread * rtp_ioqueue_thread_get_or_create(void)
Finder and allocator for an ioqueue thread.
int stasis_subscription_accept_message_type(struct stasis_subscription *subscription, const struct stasis_message_type *type)
Indicate to a subscription that we are interested in a message type.
static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
static void rtp_ioqueue_thread_destroy(struct ast_rtp_ioqueue_thread *ioqueue)
Destroyer for ioqueue thread.
Data structure associated with a single frame of data.
int ast_rtp_codecs_find_payload_code(struct ast_rtp_codecs *codecs, int payload)
Search for the tx payload type in the ast_rtp_codecs structure.
#define AST_RTP_RTCP_PSFB
enum ast_srtp_suite suite
double remote_stdevrxploss
Structure that represents the optional ICE support within an RTP engine.
struct ast_sockaddr bind_address
Abstract JSON element (object, array, string, int, ...).
Options provided by main asterisk program.
unsigned int ssrc
The received SSRC.
static void ast_rtp_ice_lite(struct ast_rtp_instance *instance)
struct stasis_topic * ast_security_topic(void)
A stasis_topic which publishes messages for security related issues.
double ast_tv2double(const struct timeval *tv)
Returns a double corresponding to the number of seconds in the timeval tv.
struct timeval ast_tvsub(struct timeval a, struct timeval b)
Returns the difference of two timevals a - b.
int64_t ast_tvdiff_us(struct timeval end, struct timeval start)
Computes the difference (in microseconds) between two struct timeval instances.
void ast_rtp_instance_set_prop(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
Set the value of an RTP instance property.
static int red_write(const void *data)
Write t140 redundancy frame.
#define ast_sockaddr_to_sin(addr, sin)
Converts a struct ast_sockaddr to a struct sockaddr_in.
ast_media_type
Types of media.
#define AST_RWLIST_UNLOCK(head)
Attempts to unlock a read/write based list.
unsigned int reported_jitter_count
enum ast_frame_type frametype
struct ast_sockaddr address
#define AST_CLI_YESNO(x)
Return Yes or No depending on the argument.
enum ast_rtp_dtmf_mode dtmfmode
#define CALC_LEARNING_MIN_DURATION(count)
Calculate the min learning duration in ms.
double local_normdevjitter
struct timeval ast_time_create_by_unit(unsigned long val, enum TIME_UNIT unit)
Convert the given unit value, and create a timeval object from it.
static pj_timer_heap_t * timer_heap
Global timer heap.
struct ast_format * format
static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int *ice)
unsigned int ice_num_components
#define ast_debug_rtcp(sublevel,...)
Log debug level RTCP information.
void ast_config_destroy(struct ast_config *cfg)
Destroys a config.
void ast_data_buffer_resize(struct ast_data_buffer *buffer, size_t size)
Resize a data buffer.
unsigned int rtcp_passthrough
int ast_sockaddr_pj_sockaddr_cmp(const struct ast_sockaddr *addr, const pj_sockaddr *pjaddr)
Compare an ast_sockaddr to a pj_sockaddr.
int ast_dns_record_get_rr_type(const struct ast_dns_record *record)
Get the resource record type of a DNS record.
int ast_cli_completion_add(char *value)
Add a result to a request for completion options.
enum ast_media_type ast_rtp_codecs_get_stream_type(struct ast_rtp_codecs *codecs)
Determine the type of RTP stream media from the codecs mapped.
static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
#define ASTERISK_GPL_KEY
The text the key() function should return.
Pluggable RTP Architecture.
static int find_by_value(int elem, int value)
Helper function to find an elem in a vector by value.
Asterisk module definitions.
unsigned int count
Current number of descriptors being waited on.
int rr_type
Resource record type.
#define RAII_VAR(vartype, varname, initval, dtor)
Declare a variable that will call a destructor function when it goes out of scope.
#define ast_rtp_instance_get_remote_address(instance, address)
Get the address of the remote endpoint that we are sending RTP to.
unsigned short seedrxseqno
struct ao2_iterator ao2_iterator_init(struct ao2_container *c, int flags) attribute_warn_unused_result
Create an iterator for a container.
size_t ast_data_buffer_max(const struct ast_data_buffer *buffer)
Return the maximum number of payloads a data buffer can hold.
unsigned int asymmetric_codec
static double calc_media_experience_score(struct ast_rtp_instance *instance, double normdevrtt, double normdev_rxjitter, double stdev_rxjitter, double normdev_rxlost)
Calculate a "media experience score" based on given data.
#define RTP_IGNORE_FIRST_PACKETS_COUNT
static void ast_rtp_ice_turn_request(struct ast_rtp_instance *instance, enum ast_rtp_ice_component_type component, enum ast_transport transport, const char *server, unsigned int port, const char *username, const char *password)
int ast_sockaddr_is_ipv6(const struct ast_sockaddr *addr)
Determine if this is an IPv6 address.
#define AST_VECTOR_SIZE(vec)
Get the number of elements in a vector.
int ast_rtp_instance_set_incoming_source_address(struct ast_rtp_instance *instance, const struct ast_sockaddr *address)
Set the incoming source address of the remote endpoint that we are sending RTP to.
DNS Recurring Resolution API.
int ast_sockaddr_to_pj_sockaddr(const struct ast_sockaddr *addr, pj_sockaddr *pjaddr)
Fill a pj_sockaddr from an ast_sockaddr.
double reported_stdev_mes
static char * ast_sockaddr_stringify_host(const struct ast_sockaddr *addr)
Wrapper around ast_sockaddr_stringify_fmt() to return an address only, suitable for a URL (with brack...
void ast_frame_free(struct ast_frame *frame, int cache)
Frees a frame or list of frames.
DTLS configuration structure.
void ast_data_buffer_free(struct ast_data_buffer *buffer)
Free a data buffer (and all held data payloads)
static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1)
#define AST_RTP_RTCP_FMT_REMB
double reported_normdev_jitter
pj_timer_heap_t * timerheap
Timer heap for scheduled items.
#define ao2_link(container, obj)
Add an object to a container.
static void ast_rtp_ice_set_role(struct ast_rtp_instance *instance, enum ast_rtp_ice_role role)