2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
22 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
24 * \author Mark Spencer <markster@digium.com>
26 * \note RTP is defined in RFC 3550.
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40 #include <netinet/in.h>
42 #include <sys/socket.h>
43 #include <arpa/inet.h>
46 #include "asterisk/rtp.h"
47 #include "asterisk/frame.h"
48 #include "asterisk/logger.h"
49 #include "asterisk/options.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/acl.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/config.h"
54 #include "asterisk/lock.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/cli.h"
57 #include "asterisk/unaligned.h"
58 #include "asterisk/utils.h"
60 #define MAX_TIMESTAMP_SKEW 640
62 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
63 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
64 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
65 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
67 #define RTCP_PT_FUR 192
68 #define RTCP_PT_SR 200
69 #define RTCP_PT_RR 201
70 #define RTCP_PT_SDES 202
71 #define RTCP_PT_BYE 203
72 #define RTCP_PT_APP 204
76 #define DEFAULT_DTMF_TIMEOUT 3000 /*!< samples */
78 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
80 static int rtpstart = 0; /*!< First port for RTP sessions (set in rtp.conf) */
81 static int rtpend = 0; /*!< Last port for RTP sessions (set in rtp.conf) */
82 static int rtpdebug = 0; /*!< Are we debugging? */
83 static int rtcpdebug = 0; /*!< Are we debugging RTCP? */
84 static int rtcpstats = 0; /*!< Are we debugging RTCP? */
85 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
86 static int stundebug = 0; /*!< Are we debugging stun? */
87 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
88 static struct sockaddr_in rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
90 static int nochecksums = 0;
94 * \brief Structure representing a RTP session.
96 * RTP session is defined on page 9 of RFC 3550: "An association among a set of participants communicating with RTP. A participant may be involved in multiple RTP sessions at the same time [...]"
99 /*! \brief The value of each payload format mapping: */
100 struct rtpPayloadType {
101 int isAstFormat; /*!< whether the following code is an AST_FORMAT */
106 /*! \brief RTP session description */
111 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
112 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
113 unsigned int themssrc; /*!< Their SSRC */
116 unsigned int lastdigitts;
117 unsigned int lastrxts;
118 unsigned int lastividtimestamp;
119 unsigned int lastovidtimestamp;
120 unsigned int lasteventseqn;
121 int lastrxseqno; /*!< Last received sequence number */
122 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
123 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
124 unsigned int rxcount; /*!< How many packets have we received? */
125 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
126 unsigned int txcount; /*!< How many packets have we sent? */
127 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
128 unsigned int cycles; /*!< Shifted count of sequence number cycles */
129 double rxjitter; /*!< Interarrival jitter at the moment */
130 double rxtransit; /*!< Relative transit time for previous packet */
131 unsigned int lasteventendseqn;
135 unsigned int dtmfduration;
138 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
139 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
140 struct timeval rxcore;
141 struct timeval txcore;
142 double drxcore; /*!< The double representation of the first received packet */
143 struct timeval lastrx; /*!< timeval when we last received a packet */
144 struct timeval dtmfmute;
145 struct ast_smoother *smoother;
147 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
148 unsigned short rxseqno;
149 struct sched_context *sched;
150 struct io_context *io;
152 ast_rtp_callback callback;
153 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
154 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
155 int rtp_lookup_code_cache_code;
156 int rtp_lookup_code_cache_result;
157 struct ast_rtcp *rtcp;
160 /* Forward declarations */
161 static int ast_rtcp_write(void *data);
162 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
163 static int ast_rtcp_write_sr(void *data);
164 static int ast_rtcp_write_rr(void *data);
165 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
167 #define FLAG_3389_WARNING (1 << 0)
168 #define FLAG_NAT_ACTIVE (3 << 1)
169 #define FLAG_NAT_INACTIVE (0 << 1)
170 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
171 #define FLAG_HAS_DTMF (1 << 3)
174 * \brief Structure defining an RTCP session.
176 * The concept "RTCP session" is not defined in RFC 3550, but since
177 * this structure is analogous to ast_rtp, which tracks a RTP session,
178 * it is logical to think of this as a RTCP session.
180 * RTCP packet is defined on page 9 of RFC 3550.
184 int s; /*!< Socket */
185 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
186 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
187 unsigned int soc; /*!< What they told us */
188 unsigned int spc; /*!< What they told us */
189 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
190 struct timeval rxlsr; /*!< Time when we got their last SR */
191 struct timeval txlsr; /*!< Time when we sent or last SR*/
192 unsigned int expected_prior; /*!< no. packets in previous interval */
193 unsigned int received_prior; /*!< no. packets received in previous interval */
194 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
195 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
196 unsigned int sr_count; /*!< number of SRs we've sent */
197 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
198 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
199 double rtt; /*!< Last reported rtt */
200 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
201 unsigned int reported_lost; /*!< Reported lost packets in their RR */
202 char quality[AST_MAX_USER_FIELD];
211 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
213 /* XXX Maybe stun belongs in another file if it ever has use outside of RTP */
215 unsigned short msgtype;
216 unsigned short msglen;
218 unsigned char ies[0];
219 } __attribute__((packed));
224 unsigned char value[0];
225 } __attribute__((packed));
228 unsigned char unused;
229 unsigned char family;
232 } __attribute__((packed));
234 #define STUN_IGNORE (0)
235 #define STUN_ACCEPT (1)
237 #define STUN_BINDREQ 0x0001
238 #define STUN_BINDRESP 0x0101
239 #define STUN_BINDERR 0x0111
240 #define STUN_SECREQ 0x0002
241 #define STUN_SECRESP 0x0102
242 #define STUN_SECERR 0x0112
244 #define STUN_MAPPED_ADDRESS 0x0001
245 #define STUN_RESPONSE_ADDRESS 0x0002
246 #define STUN_CHANGE_REQUEST 0x0003
247 #define STUN_SOURCE_ADDRESS 0x0004
248 #define STUN_CHANGED_ADDRESS 0x0005
249 #define STUN_USERNAME 0x0006
250 #define STUN_PASSWORD 0x0007
251 #define STUN_MESSAGE_INTEGRITY 0x0008
252 #define STUN_ERROR_CODE 0x0009
253 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
254 #define STUN_REFLECTED_FROM 0x000b
256 static const char *stun_msg2str(int msg)
260 return "Binding Request";
262 return "Binding Response";
264 return "Binding Error Response";
266 return "Shared Secret Request";
268 return "Shared Secret Response";
270 return "Shared Secret Error Response";
272 return "Non-RFC3489 Message";
275 static const char *stun_attr2str(int msg)
278 case STUN_MAPPED_ADDRESS:
279 return "Mapped Address";
280 case STUN_RESPONSE_ADDRESS:
281 return "Response Address";
282 case STUN_CHANGE_REQUEST:
283 return "Change Request";
284 case STUN_SOURCE_ADDRESS:
285 return "Source Address";
286 case STUN_CHANGED_ADDRESS:
287 return "Changed Address";
292 case STUN_MESSAGE_INTEGRITY:
293 return "Message Integrity";
294 case STUN_ERROR_CODE:
296 case STUN_UNKNOWN_ATTRIBUTES:
297 return "Unknown Attributes";
298 case STUN_REFLECTED_FROM:
299 return "Reflected From";
301 return "Non-RFC3489 Attribute";
305 const char *username;
306 const char *password;
309 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
312 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
313 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
314 switch(ntohs(attr->attr)) {
316 state->username = (const char *) (attr->value);
319 state->password = (const char *) (attr->value);
323 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
324 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
329 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
331 int size = sizeof(**attr) + strlen(s);
333 (*attr)->attr = htons(attrval);
334 (*attr)->len = htons(strlen(s));
335 memcpy((*attr)->value, s, strlen(s));
336 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
342 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
344 int size = sizeof(**attr) + 8;
345 struct stun_addr *addr;
347 (*attr)->attr = htons(attrval);
348 (*attr)->len = htons(8);
349 addr = (struct stun_addr *)((*attr)->value);
352 addr->port = sin->sin_port;
353 addr->addr = sin->sin_addr.s_addr;
354 (*attr) = (struct stun_attr *)((*attr)->value + 8);
360 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
362 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
363 (struct sockaddr *)dst, sizeof(*dst));
366 static void stun_req_id(struct stun_header *req)
370 req->id.id[x] = ast_random();
373 size_t ast_rtp_alloc_size(void)
375 return sizeof(struct ast_rtp);
378 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
380 struct stun_header *req;
381 unsigned char reqdata[1024];
383 struct stun_attr *attr;
385 req = (struct stun_header *)reqdata;
388 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
391 attr = (struct stun_attr *)req->ies;
393 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
394 req->msglen = htons(reqlen);
395 req->msgtype = htons(STUN_BINDREQ);
396 stun_send(rtp->s, suggestion, req);
399 static int stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len)
401 struct stun_header *resp, *hdr = (struct stun_header *)data;
402 struct stun_attr *attr;
403 struct stun_state st;
404 int ret = STUN_IGNORE;
405 unsigned char respdata[1024];
406 int resplen, respleft;
408 if (len < sizeof(struct stun_header)) {
410 ast_log(LOG_DEBUG, "Runt STUN packet (only %zd, wanting at least %zd)\n", len, sizeof(struct stun_header));
414 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), ntohs(hdr->msglen));
415 if (ntohs(hdr->msglen) > len - sizeof(struct stun_header)) {
417 ast_log(LOG_DEBUG, "Scrambled STUN packet length (got %d, expecting %zd)\n", ntohs(hdr->msglen), len - sizeof(struct stun_header));
419 len = ntohs(hdr->msglen);
420 data += sizeof(struct stun_header);
421 memset(&st, 0, sizeof(st));
423 if (len < sizeof(struct stun_attr)) {
425 ast_log(LOG_DEBUG, "Runt Attribute (got %zd, expecting %zd)\n", len, sizeof(struct stun_attr));
428 attr = (struct stun_attr *)data;
429 if (ntohs(attr->len) > len) {
431 ast_log(LOG_DEBUG, "Inconsistent Attribute (length %d exceeds remaining msg len %zd)\n", ntohs(attr->len), len);
434 if (stun_process_attr(&st, attr)) {
436 ast_log(LOG_DEBUG, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
439 /* Clear attribute in case previous entry was a string */
441 data += ntohs(attr->len) + sizeof(struct stun_attr);
442 len -= ntohs(attr->len) + sizeof(struct stun_attr);
444 /* Null terminate any string */
446 resp = (struct stun_header *)respdata;
448 respleft = sizeof(respdata) - sizeof(struct stun_header);
452 attr = (struct stun_attr *)resp->ies;
454 switch(ntohs(hdr->msgtype)) {
457 ast_verbose("STUN Bind Request, username: %s\n",
458 st.username ? st.username : "<none>");
460 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
461 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
462 resp->msglen = htons(resplen);
463 resp->msgtype = htons(STUN_BINDRESP);
464 stun_send(s, src, resp);
469 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
475 /*! \brief List of current sessions */
476 static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
478 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
480 unsigned int sec, usec, frac;
481 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
483 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
488 int ast_rtp_fd(struct ast_rtp *rtp)
493 int ast_rtcp_fd(struct ast_rtp *rtp)
500 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
502 unsigned int interval;
503 /*! \todo XXX Do a more reasonable calculation on this one
504 * Look in RFC 3550 Section A.7 for an example*/
505 interval = rtcpinterval;
509 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
514 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
516 rtp->callback = callback;
519 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
524 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
526 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
529 static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
531 char iabuf[INET_ADDRSTRLEN];
533 if (ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
535 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
537 rtp->dtmfduration = 0;
538 return &ast_null_frame;
541 ast_log(LOG_DEBUG, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
542 if (rtp->resp == 'X') {
543 rtp->f.frametype = AST_FRAME_CONTROL;
544 rtp->f.subclass = AST_CONTROL_FLASH;
546 rtp->f.frametype = AST_FRAME_DTMF;
547 rtp->f.subclass = rtp->resp;
554 rtp->dtmfduration = 0;
559 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
563 if (rtpdebugaddr.sin_addr.s_addr) {
564 if (((ntohs(rtpdebugaddr.sin_port) != 0)
565 && (rtpdebugaddr.sin_port != addr->sin_port))
566 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
572 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
576 if (rtcpdebugaddr.sin_addr.s_addr) {
577 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
578 && (rtcpdebugaddr.sin_port != addr->sin_port))
579 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
586 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
590 struct ast_frame *f = NULL;
591 event = ntohl(*((unsigned int *)(data)));
593 if (option_debug > 2 || rtpdebug)
594 ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
597 } else if (event < 11) {
599 } else if (event < 12) {
601 } else if (event < 16) {
602 resp = 'A' + (event - 12);
603 } else if (event < 17) {
606 if (rtp->resp && (rtp->resp != resp)) {
610 rtp->dtmfcount = dtmftimeout;
615 * \brief Process RTP DTMF and events according to RFC 2833.
617 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
625 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
628 unsigned int event_end;
629 unsigned int duration;
631 struct ast_frame *f = NULL;
633 event = ntohl(*((unsigned int *)(data)));
635 event_end = ntohl(*((unsigned int *)(data)));
638 duration = ntohl(*((unsigned int *)(data)));
640 if (rtpdebug || option_debug > 2)
641 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
644 } else if (event < 11) {
646 } else if (event < 12) {
648 } else if (event < 16) {
649 resp = 'A' + (event - 12);
650 } else if (event < 17) { /* Event 16: Hook flash */
653 if (rtp->resp && (rtp->resp != resp)) {
655 } else if (event_end & 0x80) {
657 if (rtp->lasteventendseqn != seqno) {
659 rtp->lasteventendseqn = seqno;
665 } else if (rtp->resp && rtp->dtmfduration && (duration < rtp->dtmfduration)) {
668 if (!(event_end & 0x80))
670 rtp->dtmfcount = dtmftimeout;
671 rtp->dtmfduration = duration;
676 * \brief Process Comfort Noise RTP.
678 * This is incomplete at the moment.
681 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
683 struct ast_frame *f = NULL;
684 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
685 totally help us out becuase we don't have an engine to keep it going and we are not
686 guaranteed to have it every 20ms or anything */
688 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
690 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
691 char iabuf[INET_ADDRSTRLEN];
693 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
694 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
695 ast_set_flag(rtp, FLAG_3389_WARNING);
698 /* Must have at least one byte */
702 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
703 rtp->f.datalen = len - 1;
704 rtp->f.offset = AST_FRIENDLY_OFFSET;
705 memcpy(rtp->f.data, data + 1, len - 1);
711 rtp->f.frametype = AST_FRAME_CNG;
712 rtp->f.subclass = data[0] & 0x7f;
713 rtp->f.datalen = len - 1;
715 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
720 static int rtpread(int *id, int fd, short events, void *cbdata)
722 struct ast_rtp *rtp = cbdata;
724 f = ast_rtp_read(rtp);
727 rtp->callback(rtp, f, rtp->data);
732 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
735 int position, i, packetwords;
737 struct sockaddr_in sin;
738 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
739 char iabuf[INET_ADDRSTRLEN];
740 unsigned int *rtcpheader;
752 struct ast_frame *f = &ast_null_frame;
754 if (!rtp || !rtp->rtcp)
755 return &ast_null_frame;
759 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
760 0, (struct sockaddr *)&sin, &len);
761 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
765 ast_log(LOG_WARNING, "RTCP Read error: %s\n", strerror(errno));
768 return &ast_null_frame;
771 packetwords = res / 4;
774 /* Send to whoever sent to us */
775 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
776 (rtp->rtcp->them.sin_port != sin.sin_port)) {
777 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
778 if (option_debug || rtpdebug)
779 ast_log(LOG_DEBUG, "RTCP NAT: Got RTCP from other end. Now sending to address %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
783 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
785 /* Process a compound packet */
787 while (position < packetwords) {
789 length = ntohl(rtcpheader[i]);
790 pt = (length & 0xff0000) >> 16;
791 rc = (length & 0x1f000000) >> 24;
794 if ((i + length) > packetwords) {
795 ast_log(LOG_WARNING, "RTCP Read too short\n");
796 return &ast_null_frame;
799 if (rtcp_debug_test_addr(&sin)) {
800 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
801 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
802 ast_verbose("Reception reports: %d\n", rc);
803 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
806 i += 2; /* Advance past header and ssrc */
810 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
811 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
812 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
813 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff) >> 16); /* Going to LSR in RR*/
815 if (rtcp_debug_test_addr(&sin)) {
816 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
817 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
818 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
823 /* Intentional fall through */
825 /* This is the place to calculate RTT */
826 /* Don't handle multiple reception reports (rc > 1) yet */
827 gettimeofday(&now, NULL);
828 timeval2ntp(now, &msw, &lsw);
829 /* Use the one we sent them in our SR instead, rtcp->txlsr could have been rewritten if the dlsr is large */
830 if (ntohl(rtcpheader[i + 4])) { /* We must have the LSR */
831 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
832 a = (double)((comp & 0xffff0000) >> 16) + (double)((double)(comp & 0xffff)/1000000.);
833 lsr = (double)((ntohl(rtcpheader[i + 4]) & 0xffff0000) >> 16) + (double)((double)(ntohl(rtcpheader[i + 4]) & 0xffff) / 1000000.);
834 dlsr = (double)(ntohl(rtcpheader[i + 5])/65536.);
835 rtt = a - dlsr - lsr;
836 rtp->rtcp->accumulated_transit += rtt;
837 rtp->rtcp->rtt = rtt;
838 if (rtp->rtcp->maxrtt<rtt)
839 rtp->rtcp->maxrtt = rtt;
840 if (rtp->rtcp->minrtt>rtt)
841 rtp->rtcp->minrtt = rtt;
843 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
844 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
845 if (rtcp_debug_test_addr(&sin)) {
846 ast_verbose("Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
847 ast_verbose("Packets lost so far: %d\n", rtp->rtcp->reported_lost);
848 ast_verbose("Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
849 ast_verbose("Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
850 ast_verbose("Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
851 ast_verbose("Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
852 ast_verbose("DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
854 ast_verbose("RTT: %f(sec)\n", rtt);
858 if (rtcp_debug_test_addr(&sin))
859 ast_verbose("Received an RTCP Fast Update Request\n");
860 rtp->f.frametype = AST_FRAME_CONTROL;
861 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
869 if (rtcp_debug_test_addr(&sin))
870 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
873 if (rtcp_debug_test_addr(&sin))
874 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
877 ast_log(LOG_NOTICE, "Unknown RTCP packet (pt=%d) received from %s:%d\n", pt, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
880 position += (length + 1);
886 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
895 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
896 gettimeofday(&rtp->rxcore, NULL);
897 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
898 /* map timestamp to a real time */
899 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
900 rtp->rxcore.tv_sec -= timestamp / 8000;
901 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
902 /* Round to 0.1ms for nice, pretty timestamps */
903 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
904 if (rtp->rxcore.tv_usec < 0) {
905 /* Adjust appropriately if necessary */
906 rtp->rxcore.tv_usec += 1000000;
907 rtp->rxcore.tv_sec -= 1;
911 gettimeofday(&now,NULL);
912 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
913 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
914 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
915 if (tv->tv_usec >= 1000000) {
916 tv->tv_usec -= 1000000;
919 prog = (double)((timestamp-rtp->seedrxts)/8000.);
920 dtv = (double)rtp->drxcore + (double)(prog);
921 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
922 transit = current_time - dtv;
923 d = transit - rtp->rxtransit;
924 rtp->rxtransit = transit;
927 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
928 if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
929 rtp->rtcp->maxrxjitter = rtp->rxjitter;
930 if (rtp->rxjitter < rtp->rtcp->minrxjitter)
931 rtp->rtcp->minrxjitter = rtp->rxjitter;
934 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
937 struct sockaddr_in sin;
947 char iabuf[INET_ADDRSTRLEN];
949 unsigned int timestamp;
950 unsigned int *rtpheader;
951 struct rtpPayloadType rtpPT;
955 /* Cache where the header will go */
956 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
957 0, (struct sockaddr *)&sin, &len);
959 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
962 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
965 return &ast_null_frame;
969 ast_log(LOG_WARNING, "RTP Read too short\n");
970 return &ast_null_frame;
974 seqno = ntohl(rtpheader[0]);
976 /* Check RTP version */
977 version = (seqno & 0xC0000000) >> 30;
979 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res) == STUN_ACCEPT) &&
980 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
981 memcpy(&rtp->them, &sin, sizeof(rtp->them));
983 return &ast_null_frame;
987 return &ast_null_frame;
988 /* Ignore if the other side hasn't been given an address
990 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
991 return &ast_null_frame;
994 /* Send to whoever sent to us */
995 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
996 (rtp->them.sin_port != sin.sin_port)) {
999 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1000 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1003 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1004 if (option_debug || rtpdebug)
1005 ast_log(LOG_DEBUG, "RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port));
1009 payloadtype = (seqno & 0x7f0000) >> 16;
1010 padding = seqno & (1 << 29);
1011 mark = seqno & (1 << 23);
1012 ext = seqno & (1 << 28);
1014 timestamp = ntohl(rtpheader[1]);
1015 ssrc = ntohl(rtpheader[2]);
1017 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1018 if (option_verbose > 1)
1019 ast_verbose(VERBOSE_PREFIX_2 "Forcing Marker bit, because SSRC has changed\n");
1026 /* Remove padding bytes */
1027 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1031 /* RTP Extension present */
1033 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
1037 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1038 return &ast_null_frame;
1041 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1043 tseqno = rtp->lastrxseqno +1;
1045 if (rtp->rxcount==1) {
1046 /* This is the first RTP packet successfully received from source */
1047 rtp->seedrxseqno = seqno;
1050 if (rtp->rtcp->schedid < 1) {
1051 /* Schedule transmission of Receiver Report */
1052 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1055 if (tseqno > RTP_SEQ_MOD) { /* if tseqno is greater than RTP_SEQ_MOD it would indicate that the sender cycled */
1056 rtp->cycles += RTP_SEQ_MOD;
1057 ast_verbose("SEQNO cycled: %u\t%d\n", rtp->cycles, seqno);
1060 rtp->lastrxseqno = seqno;
1062 if (rtp->themssrc==0)
1063 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1065 if (rtp_debug_test_addr(&sin))
1066 ast_verbose("Got RTP packet from %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1067 ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1069 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1070 if (!rtpPT.isAstFormat) {
1071 struct ast_frame *f = NULL;
1073 /* This is special in-band data that's not one of our codecs */
1074 if (rtpPT.code == AST_RTP_DTMF) {
1075 /* It's special -- rfc2833 process it */
1076 if (rtp_debug_test_addr(&sin)) {
1077 unsigned char *data;
1079 unsigned int event_end;
1080 unsigned int duration;
1081 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1082 event = ntohl(*((unsigned int *)(data)));
1084 event_end = ntohl(*((unsigned int *)(data)));
1087 duration = ntohl(*((unsigned int *)(data)));
1089 ast_verbose("Got RTP RFC2833 from %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
1091 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
1092 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
1093 rtp->lasteventseqn = seqno;
1095 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1096 /* It's really special -- process it the Cisco way */
1097 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
1098 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1099 rtp->lasteventseqn = seqno;
1101 } else if (rtpPT.code == AST_RTP_CN) {
1103 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1105 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
1107 return f ? f : &ast_null_frame;
1109 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1110 rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : AST_FRAME_VIDEO;
1113 rtp->lastrxts = timestamp;
1115 rtp->rxseqno = seqno;
1117 if (rtp->dtmfcount) {
1119 printf("dtmfcount was %d\n", rtp->dtmfcount);
1121 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
1122 if (rtp->dtmfcount < 0)
1125 if (dtmftimeout != rtp->dtmfcount)
1126 printf("dtmfcount is %d\n", rtp->dtmfcount);
1129 rtp->lastrxts = timestamp;
1131 /* Send any pending DTMF */
1132 if (rtp->resp && !rtp->dtmfcount) {
1134 ast_log(LOG_DEBUG, "Sending pending DTMF\n");
1135 return send_dtmf(rtp);
1138 rtp->f.datalen = res - hdrlen;
1139 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1140 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1141 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
1142 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1143 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1144 ast_frame_byteswap_be(&rtp->f);
1145 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1146 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1147 rtp->f.has_timing_info = 1;
1148 rtp->f.ts = timestamp / 8;
1149 rtp->f.len = rtp->f.samples / 8;
1150 rtp->f.seqno = seqno;
1152 /* Video -- samples is # of samples vs. 90000 */
1153 if (!rtp->lastividtimestamp)
1154 rtp->lastividtimestamp = timestamp;
1155 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1156 rtp->lastividtimestamp = timestamp;
1157 rtp->f.delivery.tv_sec = 0;
1158 rtp->f.delivery.tv_usec = 0;
1160 rtp->f.subclass |= 0x1;
1167 /* The following array defines the MIME Media type (and subtype) for each
1168 of our codecs, or RTP-specific data type. */
1170 struct rtpPayloadType payloadType;
1174 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1175 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1176 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1177 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1178 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1179 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1180 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1181 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1182 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1183 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1184 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1185 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1186 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1187 {{0, AST_RTP_CN}, "audio", "CN"},
1188 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1189 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1190 {{1, AST_FORMAT_H261}, "video", "H261"},
1191 {{1, AST_FORMAT_H263}, "video", "H263"},
1192 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1193 {{1, AST_FORMAT_H264}, "video", "H264"},
1196 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1197 also, our own choices for dynamic payload types. This is our master
1198 table for transmission */
1199 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1200 [0] = {1, AST_FORMAT_ULAW},
1201 #ifdef USE_DEPRECATED_G726
1202 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1204 [3] = {1, AST_FORMAT_GSM},
1205 [4] = {1, AST_FORMAT_G723_1},
1206 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1207 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1208 [7] = {1, AST_FORMAT_LPC10},
1209 [8] = {1, AST_FORMAT_ALAW},
1210 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1211 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1212 [13] = {0, AST_RTP_CN},
1213 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1214 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1215 [18] = {1, AST_FORMAT_G729A},
1216 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1217 [26] = {1, AST_FORMAT_JPEG},
1218 [31] = {1, AST_FORMAT_H261},
1219 [34] = {1, AST_FORMAT_H263},
1220 [103] = {1, AST_FORMAT_H263_PLUS},
1221 [97] = {1, AST_FORMAT_ILBC},
1222 [99] = {1, AST_FORMAT_H264},
1223 [101] = {0, AST_RTP_DTMF},
1224 [110] = {1, AST_FORMAT_SPEEX},
1225 [111] = {1, AST_FORMAT_G726},
1226 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1229 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1235 for (i = 0; i < MAX_RTP_PT; ++i) {
1236 rtp->current_RTP_PT[i].isAstFormat = 0;
1237 rtp->current_RTP_PT[i].code = 0;
1240 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1241 rtp->rtp_lookup_code_cache_code = 0;
1242 rtp->rtp_lookup_code_cache_result = 0;
1245 void ast_rtp_pt_default(struct ast_rtp* rtp)
1249 /* Initialize to default payload types */
1250 for (i = 0; i < MAX_RTP_PT; ++i) {
1251 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1252 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1255 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1256 rtp->rtp_lookup_code_cache_code = 0;
1257 rtp->rtp_lookup_code_cache_result = 0;
1260 void ast_rtp_pt_copy(struct ast_rtp *dest, const struct ast_rtp *src)
1264 for (i=0; i < MAX_RTP_PT; ++i) {
1265 dest->current_RTP_PT[i].isAstFormat =
1266 src->current_RTP_PT[i].isAstFormat;
1267 dest->current_RTP_PT[i].code =
1268 src->current_RTP_PT[i].code;
1270 dest->rtp_lookup_code_cache_isAstFormat = 0;
1271 dest->rtp_lookup_code_cache_code = 0;
1272 dest->rtp_lookup_code_cache_result = 0;
1275 /*! \brief Get channel driver interface structure */
1276 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1278 struct ast_rtp_protocol *cur = NULL;
1280 AST_LIST_LOCK(&protos);
1281 AST_LIST_TRAVERSE(&protos, cur, list) {
1282 if (cur->type == chan->tech->type)
1285 AST_LIST_UNLOCK(&protos);
1290 int ast_rtp_early_bridge(struct ast_channel *dest, struct ast_channel *src)
1292 struct ast_rtp *destp, *srcp=NULL; /* Audio RTP Channels */
1293 struct ast_rtp *vdestp, *vsrcp=NULL; /* Video RTP channels */
1294 struct ast_rtp_protocol *destpr, *srcpr=NULL;
1298 ast_channel_lock(dest);
1300 while(ast_channel_trylock(src)) {
1301 ast_channel_unlock(dest);
1303 ast_channel_lock(dest);
1307 /* Find channel driver interfaces */
1308 destpr = get_proto(dest);
1310 srcpr = get_proto(src);
1313 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1314 ast_channel_unlock(dest);
1316 ast_channel_unlock(src);
1321 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src ? src->name : "<unspecified>");
1322 ast_channel_unlock(dest);
1324 ast_channel_unlock(src);
1328 /* Get audio and video interface (if native bridge is possible) */
1329 destp = destpr->get_rtp_info(dest);
1330 vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
1332 srcp = srcpr->get_rtp_info(src);
1333 vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
1336 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1338 /* Somebody doesn't want to play... */
1339 ast_channel_unlock(dest);
1341 ast_channel_unlock(src);
1344 if (srcpr && srcpr->get_codec)
1345 srccodec = srcpr->get_codec(src);
1348 /* Consider empty media as non-existant */
1349 if (srcp && !srcp->them.sin_addr.s_addr)
1351 /* Bridge media early */
1352 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, srcp ? ast_test_flag(srcp, FLAG_NAT_ACTIVE) : 0))
1353 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src ? src->name : "<unspecified>");
1354 ast_channel_unlock(dest);
1356 ast_channel_unlock(src);
1358 ast_log(LOG_DEBUG, "Setting early bridge SDP of '%s' with that of '%s'\n", dest->name, src ? src->name : "<unspecified>");
1362 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1364 struct ast_rtp *destp, *srcp; /* Audio RTP Channels */
1365 struct ast_rtp *vdestp, *vsrcp; /* Video RTP channels */
1366 struct ast_rtp_protocol *destpr, *srcpr;
1369 ast_channel_lock(dest);
1370 while(ast_channel_trylock(src)) {
1371 ast_channel_unlock(dest);
1373 ast_channel_lock(dest);
1376 /* Find channel driver interfaces */
1377 destpr = get_proto(dest);
1378 srcpr = get_proto(src);
1381 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1382 ast_channel_unlock(dest);
1383 ast_channel_unlock(src);
1388 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
1389 ast_channel_unlock(dest);
1390 ast_channel_unlock(src);
1394 /* Get audio and video interface (if native bridge is possible) */
1395 destp = destpr->get_rtp_info(dest);
1396 vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
1397 srcp = srcpr->get_rtp_info(src);
1398 vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
1400 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1401 if (!destp || !srcp) {
1402 /* Somebody doesn't want to play... */
1403 ast_channel_unlock(dest);
1404 ast_channel_unlock(src);
1407 ast_rtp_pt_copy(destp, srcp);
1408 if (vdestp && vsrcp)
1409 ast_rtp_pt_copy(vdestp, vsrcp);
1410 if (srcpr->get_codec)
1411 srccodec = srcpr->get_codec(src);
1416 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1417 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1419 ast_channel_unlock(dest);
1420 ast_channel_unlock(src);
1422 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1426 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1427 * By default, use the well-known value for this type (although it may
1428 * still be set to a different value by a subsequent "a=rtpmap:" line)
1430 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1432 if (pt < 0 || pt > MAX_RTP_PT)
1433 return; /* bogus payload type */
1435 if (static_RTP_PT[pt].code != 0)
1436 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1439 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1440 a SDP "a=rtpmap:" line. */
1441 void ast_rtp_set_rtpmap_type(struct ast_rtp* rtp, int pt,
1442 char* mimeType, char* mimeSubtype)
1446 if (pt < 0 || pt > MAX_RTP_PT)
1447 return; /* bogus payload type */
1449 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
1450 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1451 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1452 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1458 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
1459 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1460 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1461 int* astFormats, int* nonAstFormats) {
1464 *astFormats = *nonAstFormats = 0;
1465 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1466 if (rtp->current_RTP_PT[pt].isAstFormat) {
1467 *astFormats |= rtp->current_RTP_PT[pt].code;
1469 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
1474 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
1476 struct rtpPayloadType result;
1478 result.isAstFormat = result.code = 0;
1479 if (pt < 0 || pt > MAX_RTP_PT)
1480 return result; /* bogus payload type */
1482 /* Start with negotiated codecs */
1483 result = rtp->current_RTP_PT[pt];
1485 /* If it doesn't exist, check our static RTP type list, just in case */
1487 result = static_RTP_PT[pt];
1491 /*! \brief Looks up an RTP code out of our *static* outbound list */
1492 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
1496 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
1497 code == rtp->rtp_lookup_code_cache_code) {
1499 /* Use our cached mapping, to avoid the overhead of the loop below */
1500 return rtp->rtp_lookup_code_cache_result;
1503 /* Check the dynamic list first */
1504 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1505 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
1506 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1507 rtp->rtp_lookup_code_cache_code = code;
1508 rtp->rtp_lookup_code_cache_result = pt;
1513 /* Then the static list */
1514 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1515 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
1516 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1517 rtp->rtp_lookup_code_cache_code = code;
1518 rtp->rtp_lookup_code_cache_result = pt;
1525 char* ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code)
1530 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
1531 if (mimeTypes[i].payloadType.code == code && mimeTypes[i].payloadType.isAstFormat == isAstFormat)
1532 return mimeTypes[i].subtype;
1537 char *ast_rtp_lookup_mime_multiple(char *buf, int size, const int capability, const int isAstFormat)
1547 snprintf(end, size, "0x%x (", capability);
1554 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
1555 if (capability & format) {
1556 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format);
1557 snprintf(end, size, "%s|", name);
1565 snprintf(start, size, "nothing)");
1572 static int rtp_socket(void)
1576 s = socket(AF_INET, SOCK_DGRAM, 0);
1578 flags = fcntl(s, F_GETFL);
1579 fcntl(s, F_SETFL, flags | O_NONBLOCK);
1582 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
1589 * \brief Initialize a new RTCP session.
1591 * \returns The newly initialized RTCP session.
1593 static struct ast_rtcp *ast_rtcp_new(void)
1595 struct ast_rtcp *rtcp;
1597 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
1599 rtcp->s = rtp_socket();
1600 rtcp->us.sin_family = AF_INET;
1601 rtcp->them.sin_family = AF_INET;
1605 ast_log(LOG_WARNING, "Unable to allocate RTCP socket: %s\n", strerror(errno));
1612 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
1614 struct ast_rtp *rtp;
1619 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
1621 rtp->them.sin_family = AF_INET;
1622 rtp->us.sin_family = AF_INET;
1623 rtp->s = rtp_socket();
1624 rtp->ssrc = ast_random();
1625 rtp->seqno = ast_random() & 0xffff;
1626 ast_set_flag(rtp, FLAG_HAS_DTMF);
1629 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1632 if (sched && rtcpenable) {
1634 rtp->rtcp = ast_rtcp_new();
1637 /* Select a random port number in the range of possible RTP */
1638 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
1640 /* Save it for future references. */
1642 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1644 /* Must be an even port number by RTP spec */
1645 rtp->us.sin_port = htons(x);
1646 rtp->us.sin_addr = addr;
1647 /* If there's rtcp, initialize it as well. */
1649 rtp->rtcp->us.sin_port = htons(x + 1);
1650 /* Try to bind it/them. */
1651 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1652 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1655 /* Primary bind succeeded! Gotta recreate it */
1657 rtp->s = rtp_socket();
1659 if (errno != EADDRINUSE) {
1660 /* We got an error that wasn't expected, abort! */
1661 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1664 close(rtp->rtcp->s);
1670 /* The port was used, increment it (by two). */
1672 /* Did we go over the limit ? */
1674 /* then, start from the begingig. */
1675 x = (rtpstart + 1) & ~1;
1676 /* Check if we reached the place were we started. */
1677 if (x == startplace) {
1678 /* If so, there's no ports available. */
1679 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1682 close(rtp->rtcp->s);
1689 if (io && sched && callbackmode) {
1690 /* Operate this one in a callback mode */
1693 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1695 ast_rtp_pt_default(rtp);
1699 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1703 memset(&ia, 0, sizeof(ia));
1704 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1707 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1711 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1712 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1716 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1718 rtp->them.sin_port = them->sin_port;
1719 rtp->them.sin_addr = them->sin_addr;
1721 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1722 rtp->rtcp->them.sin_addr = them->sin_addr;
1727 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1729 if ((them->sin_family != AF_INET) ||
1730 (them->sin_port != rtp->them.sin_port) ||
1731 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
1732 them->sin_family = AF_INET;
1733 them->sin_port = rtp->them.sin_port;
1734 them->sin_addr = rtp->them.sin_addr;
1740 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1745 void ast_rtp_stop(struct ast_rtp *rtp)
1747 if (rtp->rtcp->schedid > 0) {
1748 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1749 rtp->rtcp->schedid = -1;
1752 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1753 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1755 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
1756 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
1760 void ast_rtp_reset(struct ast_rtp *rtp)
1762 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1763 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1764 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1766 rtp->lastdigitts = 0;
1768 rtp->lastividtimestamp = 0;
1769 rtp->lastovidtimestamp = 0;
1770 rtp->lasteventseqn = 0;
1771 rtp->lasteventendseqn = 0;
1772 rtp->lasttxformat = 0;
1773 rtp->lastrxformat = 0;
1775 rtp->dtmfduration = 0;
1780 char *ast_rtp_get_quality(struct ast_rtp *rtp)
1784 *themssrc their ssrc
1786 *rxjitter our calculated jitter(rx)
1787 *rxcount no. received packets
1788 *txjitter reported jitter of the other end
1789 *txcount transmitted packets
1790 *rlp remote lost packets
1793 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality), "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f", rtp->ssrc, rtp->themssrc, rtp->rtcp->expected_prior - rtp->rtcp->received_prior, rtp->rxjitter, rtp->rxcount, (double)rtp->rtcp->reported_jitter/65536., rtp->txcount, rtp->rtcp->reported_lost, rtp->rtcp->rtt);
1795 return rtp->rtcp->quality;
1798 void ast_rtp_destroy(struct ast_rtp *rtp)
1800 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
1801 /*Print some info on the call here */
1802 ast_verbose(" RTP-stats\n");
1803 ast_verbose("* Our Receiver:\n");
1804 ast_verbose(" SSRC: %u\n", rtp->themssrc);
1805 ast_verbose(" Received packets: %u\n", rtp->rxcount);
1806 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
1807 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
1808 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
1809 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
1810 ast_verbose("* Our Sender:\n");
1811 ast_verbose(" SSRC: %u\n", rtp->ssrc);
1812 ast_verbose(" Sent packets: %u\n", rtp->txcount);
1813 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
1814 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter);
1815 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
1816 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
1819 if (rtp->rtcp->schedid > 0) {
1820 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1821 rtp->rtcp->schedid = -1;
1825 ast_smoother_free(rtp->smoother);
1827 ast_io_remove(rtp->io, rtp->ioid);
1831 close(rtp->rtcp->s);
1838 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1842 if (ast_tvzero(rtp->txcore)) {
1843 rtp->txcore = ast_tvnow();
1844 /* Round to 20ms for nice, pretty timestamps */
1845 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1847 /* Use previous txcore if available */
1848 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
1849 ms = ast_tvdiff_ms(t, rtp->txcore);
1852 /* Use what we just got for next time */
1854 return (unsigned int) ms;
1857 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
1859 unsigned int *rtpheader;
1865 char iabuf[INET_ADDRSTRLEN];
1867 if ((digit <= '9') && (digit >= '0'))
1869 else if (digit == '*')
1871 else if (digit == '#')
1873 else if ((digit >= 'A') && (digit <= 'D'))
1874 digit = digit - 'A' + 12;
1875 else if ((digit >= 'a') && (digit <= 'd'))
1876 digit = digit - 'a' + 12;
1878 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
1881 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
1883 /* If we have no peer, return immediately */
1884 if (!rtp->them.sin_addr.s_addr)
1887 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1889 /* Get a pointer to the header */
1890 rtpheader = (unsigned int *)data;
1891 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
1892 rtpheader[1] = htonl(rtp->lastdigitts);
1893 rtpheader[2] = htonl(rtp->ssrc);
1894 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
1895 for (x = 0; x < 6; x++) {
1896 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1897 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
1899 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
1900 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1901 ntohs(rtp->them.sin_port), strerror(errno));
1902 if (rtp_debug_test_addr(&rtp->them))
1903 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1904 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1905 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
1907 /* Sequence number of last two end packets does not get incremented */
1910 /* Clear marker bit and set seqno */
1911 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
1912 /* For the last three packets, set the duration and the end bit */
1915 /* No, this is wrong... Do not increment lastdigitts, that's not according
1916 to the RFC, as best we can determine */
1917 rtp->lastdigitts++; /* or else the SPA3000 will click instead of beeping... */
1918 rtpheader[1] = htonl(rtp->lastdigitts);
1920 /* Make duration 800 (100ms) */
1921 rtpheader[3] |= htonl((800));
1922 /* Set the End bit */
1923 rtpheader[3] |= htonl((1 << 23));
1926 /*! \note Increment the digit timestamp by 120ms, to ensure that digits
1927 sent sequentially with no intervening non-digit packets do not
1928 get sent with the same timestamp, and that sequential digits
1929 have some 'dead air' in between them
1931 rtp->lastdigitts += 960;
1932 /* Increment the sequence number to reflect the last packet
1939 /* \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
1940 int ast_rtcp_send_h261fur(void *data)
1942 struct ast_rtp *rtp = data;
1945 rtp->rtcp->sendfur = 1;
1946 res = ast_rtcp_write(data);
1951 /*! \brief Send RTCP sender's report */
1952 static int ast_rtcp_write_sr(void *data)
1954 struct ast_rtp *rtp = data;
1958 unsigned int now_lsw;
1959 unsigned int now_msw;
1960 unsigned int *rtcpheader;
1962 unsigned int extended;
1963 unsigned int expected;
1964 unsigned int expected_interval;
1965 unsigned int received_interval;
1968 struct timeval dlsr;
1970 char iabuf[INET_ADDRSTRLEN];
1972 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
1975 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
1976 ast_verbose("RTCP SR transmission error, rtcp halted %s\n",strerror(errno));
1977 if (rtp->rtcp->schedid > 0)
1978 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1979 rtp->rtcp->schedid = -1;
1983 gettimeofday(&now, NULL);
1984 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
1985 rtcpheader = (unsigned int *)bdata;
1986 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
1987 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
1988 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
1989 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
1990 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
1991 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
1994 extended = rtp->cycles + rtp->lastrxseqno;
1995 expected = extended - rtp->seedrxseqno + 1;
1996 if (rtp->rxcount > expected)
1997 expected += rtp->rxcount - expected;
1998 lost = expected - rtp->rxcount;
1999 expected_interval = expected - rtp->rtcp->expected_prior;
2000 rtp->rtcp->expected_prior = expected;
2001 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2002 rtp->rtcp->received_prior = rtp->rxcount;
2003 lost_interval = expected_interval - received_interval;
2004 if (expected_interval == 0 || lost_interval <= 0)
2007 fraction = (lost_interval << 8) / expected_interval;
2008 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2009 rtcpheader[7] = htonl(rtp->themssrc);
2010 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2011 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2012 rtcpheader[10] = htonl((unsigned int)rtp->rxjitter);
2013 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2014 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2017 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2019 if (rtp->rtcp->sendfur) {
2020 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2021 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
2023 rtp->rtcp->sendfur = 0;
2026 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2027 /* it can change mid call, and SDES can't) */
2028 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2029 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2030 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2033 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2035 ast_log(LOG_ERROR, "RTCP SR transmission error to %s:%d, rtcp halted %s\n",ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port), strerror(errno));
2036 if (rtp->rtcp->schedid > 0)
2037 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2038 rtp->rtcp->schedid = -1;
2042 /* FIXME Don't need to get a new one */
2043 gettimeofday(&rtp->rtcp->txlsr, NULL);
2044 rtp->rtcp->sr_count++;
2046 rtp->rtcp->lastsrtxcount = rtp->txcount;
2048 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2049 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2050 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
2051 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2052 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
2053 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2054 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
2055 ast_verbose(" Report block:\n");
2056 ast_verbose(" Fraction lost: %u\n", fraction);
2057 ast_verbose(" Cumulative loss: %u\n", lost);
2058 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
2059 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
2060 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2065 /*! \brief Send RTCP recepient's report */
2066 static int ast_rtcp_write_rr(void *data)
2068 struct ast_rtp *rtp = data;
2072 unsigned int extended;
2073 unsigned int expected;
2074 unsigned int expected_interval;
2075 unsigned int received_interval;
2078 unsigned int *rtcpheader;
2080 char iabuf[INET_ADDRSTRLEN];
2081 struct timeval dlsr;
2084 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2087 if (!rtp->rtcp->them.sin_addr.s_addr) {
2088 ast_log(LOG_ERROR, "RTCP RR transmission error to, rtcp halted %s\n",strerror(errno));
2089 if (rtp->rtcp->schedid > 0)
2090 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2091 rtp->rtcp->schedid = -1;
2095 extended = rtp->cycles + rtp->lastrxseqno;
2096 expected = extended - rtp->seedrxseqno + 1;
2097 lost = expected - rtp->rxcount;
2098 expected_interval = expected - rtp->rtcp->expected_prior;
2099 rtp->rtcp->expected_prior = expected;
2100 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2101 rtp->rtcp->received_prior = rtp->rxcount;
2102 lost_interval = expected_interval - received_interval;
2103 if (expected_interval == 0 || lost_interval <= 0)
2106 fraction = (lost_interval << 8) / expected_interval;
2107 gettimeofday(&now, NULL);
2108 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2109 rtcpheader = (unsigned int *)bdata;
2110 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2111 rtcpheader[1] = htonl(rtp->ssrc);
2112 rtcpheader[2] = htonl(rtp->themssrc);
2113 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2114 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2115 rtcpheader[5] = htonl((unsigned int)rtp->rxjitter);
2116 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2117 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2119 if (rtp->rtcp->sendfur) {
2120 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2121 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
2123 rtp->rtcp->sendfur = 0;
2126 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2127 it can change mid call, and SDES can't) */
2128 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2129 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2130 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2133 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2136 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2137 /* Remove the scheduler */
2138 if (rtp->rtcp->schedid > 0)
2139 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2140 rtp->rtcp->schedid = -1;
2144 rtp->rtcp->rr_count++;
2146 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2147 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2148 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2149 " IA jitter: %.4f\n"
2150 " Their last SR: %u\n"
2151 " DLSR: %4.4f (sec)\n\n",
2152 ast_inet_ntoa(iabuf, sizeof(iabuf),
2153 rtp->rtcp->them.sin_addr),
2154 ntohs(rtp->rtcp->them.sin_port),
2155 rtp->ssrc, rtp->themssrc, fraction, lost,
2157 rtp->rtcp->themrxlsr,
2158 (double)(ntohl(rtcpheader[7])/65536.0));
2164 /*! \brief Write and RTCP packet to the far end
2165 * \note Decide if we are going to send an SR (with Reception Block) or RR
2166 * RR is sent if we have not sent any rtp packets in the previous interval */
2167 static int ast_rtcp_write(void *data)
2169 struct ast_rtp *rtp = data;
2172 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2173 res = ast_rtcp_write_sr(data);
2175 res = ast_rtcp_write_rr(data);
2180 /*! \brief generate comfort noice (CNG) */
2181 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2183 unsigned int *rtpheader;
2188 char iabuf[INET_ADDRSTRLEN];
2189 level = 127 - (level & 0x7f);
2190 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2192 /* If we have no peer, return immediately */
2193 if (!rtp->them.sin_addr.s_addr)
2196 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2198 /* Get a pointer to the header */
2199 rtpheader = (unsigned int *)data;
2200 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2201 rtpheader[1] = htonl(rtp->lastts);
2202 rtpheader[2] = htonl(rtp->ssrc);
2204 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2205 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2207 ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s:%d: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
2208 if (rtp_debug_test_addr(&rtp->them))
2209 ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %u, len %d)\n"
2210 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
2216 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2218 unsigned char *rtpheader;
2219 char iabuf[INET_ADDRSTRLEN];
2226 ms = calc_txstamp(rtp, &f->delivery);
2227 /* Default prediction */
2228 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
2229 pred = rtp->lastts + f->samples;
2231 /* Re-calculate last TS */
2232 rtp->lastts = rtp->lastts + ms * 8;
2233 if (ast_tvzero(f->delivery)) {
2234 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
2235 and if so, go with our prediction */
2236 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
2239 if (option_debug > 2)
2240 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2245 mark = f->subclass & 0x1;
2246 pred = rtp->lastovidtimestamp + f->samples;
2247 /* Re-calculate last TS */
2248 rtp->lastts = rtp->lastts + ms * 90;
2249 /* If it's close to our prediction, go for it */
2250 if (ast_tvzero(f->delivery)) {
2251 if (abs(rtp->lastts - pred) < 7200) {
2253 rtp->lastovidtimestamp += f->samples;
2255 if (option_debug > 2)
2256 ast_log(LOG_DEBUG, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, f->samples);
2257 rtp->lastovidtimestamp = rtp->lastts;
2261 /* If the timestamp for non-digit packets has moved beyond the timestamp
2262 for digits, update the digit timestamp.
2264 if (rtp->lastts > rtp->lastdigitts)
2265 rtp->lastdigitts = rtp->lastts;
2267 if (f->has_timing_info)
2268 rtp->lastts = f->ts * 8;
2270 /* Get a pointer to the header */
2271 rtpheader = (unsigned char *)(f->data - hdrlen);
2273 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
2274 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
2275 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
2277 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2278 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2280 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
2281 ast_log(LOG_DEBUG, "RTP Transmission error of packet %d to %s:%d: %s\n", rtp->seqno, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
2282 } else if ((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) {
2283 /* Only give this error message once if we are not RTP debugging */
2284 if (option_debug || rtpdebug)
2285 ast_log(LOG_DEBUG, "RTP NAT: Can't write RTP to private address %s:%d, waiting for other end to send audio...\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port));
2286 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
2290 rtp->txoctetcount +=(res - hdrlen);
2292 if (rtp->rtcp->schedid < 1)
2293 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
2296 if (rtp_debug_test_addr(&rtp->them))
2297 ast_verbose("Sent RTP packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2298 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
2306 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
2308 struct ast_frame *f;
2314 /* If we have no peer, return immediately */
2315 if (!rtp->them.sin_addr.s_addr)
2318 /* If there is no data length, return immediately */
2322 /* Make sure we have enough space for RTP header */
2323 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
2324 ast_log(LOG_WARNING, "RTP can only send voice and video\n");
2328 subclass = _f->subclass;
2329 if (_f->frametype == AST_FRAME_VIDEO)
2332 codec = ast_rtp_lookup_code(rtp, 1, subclass);
2334 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
2338 if (rtp->lasttxformat != subclass) {
2339 /* New format, reset the smoother */
2341 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
2342 rtp->lasttxformat = subclass;
2344 ast_smoother_free(rtp->smoother);
2345 rtp->smoother = NULL;
2350 case AST_FORMAT_SLINEAR:
2351 if (!rtp->smoother) {
2352 rtp->smoother = ast_smoother_new(320);
2354 if (!rtp->smoother) {
2355 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2358 ast_smoother_feed_be(rtp->smoother, _f);
2360 while((f = ast_smoother_read(rtp->smoother)))
2361 ast_rtp_raw_write(rtp, f, codec);
2363 case AST_FORMAT_ULAW:
2364 case AST_FORMAT_ALAW:
2365 if (!rtp->smoother) {
2366 rtp->smoother = ast_smoother_new(160);
2368 if (!rtp->smoother) {
2369 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2372 ast_smoother_feed(rtp->smoother, _f);
2374 while((f = ast_smoother_read(rtp->smoother)))
2375 ast_rtp_raw_write(rtp, f, codec);
2377 case AST_FORMAT_ADPCM:
2378 case AST_FORMAT_G726:
2379 if (!rtp->smoother) {
2380 rtp->smoother = ast_smoother_new(80);
2382 if (!rtp->smoother) {
2383 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2386 ast_smoother_feed(rtp->smoother, _f);
2388 while((f = ast_smoother_read(rtp->smoother)))
2389 ast_rtp_raw_write(rtp, f, codec);
2391 case AST_FORMAT_G729A:
2392 if (!rtp->smoother) {
2393 rtp->smoother = ast_smoother_new(20);
2395 ast_smoother_set_flags(rtp->smoother, AST_SMOOTHER_FLAG_G729);
2397 if (!rtp->smoother) {
2398 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
2401 ast_smoother_feed(rtp->smoother, _f);
2403 while((f = ast_smoother_read(rtp->smoother)))
2404 ast_rtp_raw_write(rtp, f, codec);
2406 case AST_FORMAT_GSM:
2407 if (!rtp->smoother) {
2408 rtp->smoother = ast_smoother_new(33);
2410 if (!rtp->smoother) {
2411 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
2414 ast_smoother_feed(rtp->smoother, _f);
2415 while((f = ast_smoother_read(rtp->smoother)))
2416 ast_rtp_raw_write(rtp, f, codec);
2418 case AST_FORMAT_ILBC:
2419 if (!rtp->smoother) {
2420 rtp->smoother = ast_smoother_new(50);
2422 if (!rtp->smoother) {
2423 ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
2426 ast_smoother_feed(rtp->smoother, _f);
2427 while((f = ast_smoother_read(rtp->smoother)))
2428 ast_rtp_raw_write(rtp, f, codec);
2431 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
2432 /* fall through to... */
2433 case AST_FORMAT_H261:
2434 case AST_FORMAT_H263:
2435 case AST_FORMAT_H263_PLUS:
2436 case AST_FORMAT_H264:
2437 case AST_FORMAT_G723_1:
2438 case AST_FORMAT_LPC10:
2439 case AST_FORMAT_SPEEX:
2440 /* Don't buffer outgoing frames; send them one-per-packet: */
2441 if (_f->offset < hdrlen) {
2446 ast_rtp_raw_write(rtp, f, codec);
2452 /*! \brief Unregister interface to channel driver */
2453 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
2455 AST_LIST_LOCK(&protos);
2456 AST_LIST_REMOVE(&protos, proto, list);
2457 AST_LIST_UNLOCK(&protos);
2460 /*! \brief Register interface to channel driver */
2461 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
2463 struct ast_rtp_protocol *cur;
2465 AST_LIST_LOCK(&protos);
2466 AST_LIST_TRAVERSE(&protos, cur, list) {
2467 if (!strcmp(cur->type, proto->type)) {
2468 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
2469 AST_LIST_UNLOCK(&protos);
2473 AST_LIST_INSERT_HEAD(&protos, proto, list);
2474 AST_LIST_UNLOCK(&protos);
2479 /*! \brief Bridge calls. If possible and allowed, initiate
2480 re-invite so the peers exchange media directly outside
2482 enum ast_bridge_result ast_rtp_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
2484 struct ast_frame *f;
2485 struct ast_channel *who, *other, *cs[3];
2486 struct ast_rtp *p0, *p1; /* Audio RTP Channels */
2487 struct ast_rtp *vp0, *vp1; /* Video RTP channels */
2488 struct ast_rtp_protocol *pr0, *pr1;
2489 struct sockaddr_in ac0, ac1;
2490 struct sockaddr_in vac0, vac1;
2491 struct sockaddr_in t0, t1;
2492 struct sockaddr_in vt0, vt1;
2493 char iabuf[INET_ADDRSTRLEN];
2496 int codec0,codec1, oldcodec0, oldcodec1;
2498 memset(&vt0, 0, sizeof(vt0));
2499 memset(&vt1, 0, sizeof(vt1));
2500 memset(&vac0, 0, sizeof(vac0));
2501 memset(&vac1, 0, sizeof(vac1));
2504 ast_channel_lock(c0);
2505 while(ast_channel_trylock(c1)) {
2506 ast_channel_unlock(c0);
2508 ast_channel_lock(c0);
2511 /* Find channel driver interfaces */
2512 pr0 = get_proto(c0);
2513 pr1 = get_proto(c1);
2515 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
2516 ast_channel_unlock(c0);
2517 ast_channel_unlock(c1);
2518 return AST_BRIDGE_FAILED;
2521 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
2522 ast_channel_unlock(c0);
2523 ast_channel_unlock(c1);
2524 return AST_BRIDGE_FAILED;
2527 /* Get channel specific interface structures */
2528 pvt0 = c0->tech_pvt;
2529 pvt1 = c1->tech_pvt;
2531 /* Get audio and video interface (if native bridge is possible) */
2532 p0 = pr0->get_rtp_info(c0);
2533 vp0 = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0) : NULL;
2534 p1 = pr1->get_rtp_info(c1);
2535 vp1 = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1) : NULL;
2537 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
2539 /* Somebody doesn't want to play... */
2540 ast_channel_unlock(c0);
2541 ast_channel_unlock(c1);
2542 return AST_BRIDGE_FAILED_NOWARN;
2545 if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2546 /* can't bridge, we are carrying DTMF for this channel and the bridge
2549 ast_channel_unlock(c0);
2550 ast_channel_unlock(c1);
2551 return AST_BRIDGE_FAILED_NOWARN;
2554 if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
2555 /* can't bridge, we are carrying DTMF for this channel and the bridge
2558 ast_channel_unlock(c0);
2559 ast_channel_unlock(c1);
2560 return AST_BRIDGE_FAILED_NOWARN;
2563 /* Get codecs from both sides */
2564 codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
2565 codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
2566 if (pr0->get_codec && pr1->get_codec) {
2567 /* Hey, we can't do reinvite if both parties speak different codecs */
2568 if (!(codec0 & codec1)) {
2570 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
2571 ast_channel_unlock(c0);
2572 ast_channel_unlock(c1);
2573 return AST_BRIDGE_FAILED_NOWARN;
2577 if (option_verbose > 2)
2578 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2580 /* Ok, we should be able to redirect the media. Start with one channel */
2581 if (pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
2582 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
2584 /* Store RTP peer */
2585 ast_rtp_get_peer(p1, &ac1);
2587 ast_rtp_get_peer(vp1, &vac1);
2589 /* Then test the other channel */
2590 if (pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
2591 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
2593 /* Store RTP peer */
2594 ast_rtp_get_peer(p0, &ac0);
2596 ast_rtp_get_peer(vp0, &vac0);
2598 ast_channel_unlock(c0);
2599 ast_channel_unlock(c1);
2600 /* External RTP Bridge up, now loop and see if something happes that force us to take the
2601 media back to Asterisk */
2608 /* Check if something changed... */
2609 if ((c0->tech_pvt != pvt0) ||
2610 (c1->tech_pvt != pvt1) ||
2611 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
2612 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
2613 if (c0->tech_pvt == pvt0) {
2614 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2615 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2617 if (c1->tech_pvt == pvt1) {
2618 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2619 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2621 return AST_BRIDGE_RETRY;
2623 /* Now check if they have changed address */
2624 ast_rtp_get_peer(p1, &t1);
2625 ast_rtp_get_peer(p0, &t0);
2627 codec0 = pr0->get_codec(c0);
2629 codec1 = pr1->get_codec(c1);
2631 ast_rtp_get_peer(vp1, &vt1);
2633 ast_rtp_get_peer(vp0, &vt0);
2634 if (inaddrcmp(&t1, &ac1) || (vp1 && inaddrcmp(&vt1, &vac1)) || (codec1 != oldcodec1)) {
2635 if (option_debug > 1) {
2636 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2637 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t1.sin_addr), ntohs(t1.sin_port), codec1);
2638 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
2639 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vt1.sin_addr), ntohs(vt1.sin_port), codec1);
2640 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2641 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
2642 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2643 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
2645 if (pr0->set_rtp_peer(c0, t1.sin_addr.s_addr ? p1 : NULL, vt1.sin_addr.s_addr ? vp1 : NULL, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
2646 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
2647 memcpy(&ac1, &t1, sizeof(ac1));
2648 memcpy(&vac1, &vt1, sizeof(vac1));
2651 if (inaddrcmp(&t0, &ac0) || (vp0 && inaddrcmp(&vt0, &vac0))) {
2653 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2654 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t0.sin_addr), ntohs(t0.sin_port), codec0);
2655 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2656 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
2658 if (pr1->set_rtp_peer(c1, t0.sin_addr.s_addr ? p0 : NULL, vt0.sin_addr.s_addr ? vp0 : NULL, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
2659 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
2660 memcpy(&ac0, &t0, sizeof(ac0));
2661 memcpy(&vac0, &vt0, sizeof(vac0));
2664 who = ast_waitfor_n(cs, 2, &timeoutms);
2667 return AST_BRIDGE_RETRY;
2669 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2670 /* check for hangup / whentohangup */
2671 if (ast_check_hangup(c0) || ast_check_hangup(c1))
2676 other = (who == c0) ? c1 : c0; /* the other channel */
2677 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
2678 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
2679 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
2680 /* breaking out of the bridge. */
2684 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
2685 if ((c0->tech_pvt == pvt0)) {
2686 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2687 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2689 if ((c1->tech_pvt == pvt1)) {
2690 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2691 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2693 return AST_BRIDGE_COMPLETE;
2694 } else if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2695 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
2696 (f->subclass == AST_CONTROL_VIDUPDATE)) {
2697 ast_indicate(other, f->subclass);
2702 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2703 return AST_BRIDGE_COMPLETE;
2706 if ((f->frametype == AST_FRAME_DTMF) ||
2707 (f->frametype == AST_FRAME_VOICE) ||
2708 (f->frametype == AST_FRAME_VIDEO)) {
2709 /* Forward voice or DTMF frames if they happen upon us */
2710 ast_write(other, f);
2714 /* Swap priority not that it's a big deal at this point */
2720 return AST_BRIDGE_FAILED;
2723 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
2726 struct ast_hostent ahp;
2727 char iabuf[INET_ADDRSTRLEN];
2732 return RESULT_SHOWUSAGE;
2734 p = strstr(arg, ":");
2740 hp = ast_gethostbyname(arg, &ahp);
2742 return RESULT_SHOWUSAGE;
2743 rtpdebugaddr.sin_family = AF_INET;
2744 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
2745 rtpdebugaddr.sin_port = htons(port);
2747 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr));
2749 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr), port);
2751 return RESULT_SUCCESS;
2754 static int rtcp_do_debug_ip(int fd, int argc, char *argv[])
2757 struct ast_hostent ahp;
2758 char iabuf[INET_ADDRSTRLEN];
2762 return RESULT_SHOWUSAGE;
2765 p = strstr(arg, ":");
2771 hp = ast_gethostbyname(arg, &ahp);
2773 return RESULT_SHOWUSAGE;
2774 rtcpdebugaddr.sin_family = AF_INET;
2775 memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
2776 rtcpdebugaddr.sin_port = htons(port);
2778 ast_cli(fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtcpdebugaddr.sin_addr));
2780 ast_cli(fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtcpdebugaddr.sin_addr), port);
2782 return RESULT_SUCCESS;
2785 static int rtp_do_debug(int fd, int argc, char *argv[])
2789 return RESULT_SHOWUSAGE;
2790 return rtp_do_debug_ip(fd, argc, argv);
2793 memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
2794 ast_cli(fd, "RTP Debugging Enabled\n");
2795 return RESULT_SUCCESS;
2798 static int rtcp_do_debug(int fd, int argc, char *argv[]) {
2801 return RESULT_SHOWUSAGE;
2802 return rtcp_do_debug_ip(fd, argc, argv);
2805 memset(&rtcpdebugaddr,0,sizeof(rtcpdebugaddr));
2806 ast_cli(fd, "RTCP Debugging Enabled\n");
2807 return RESULT_SUCCESS;
2810 static int rtcp_do_stats(int fd, int argc, char *argv[]) {
2812 return RESULT_SHOWUSAGE;
2815 ast_cli(fd, "RTCP Stats Enabled\n");
2816 return RESULT_SUCCESS;
2819 static int rtp_no_debug(int fd, int argc, char *argv[])
2822 return RESULT_SHOWUSAGE;
2824 ast_cli(fd,"RTP Debugging Disabled\n");
2825 return RESULT_SUCCESS;
2828 static int rtcp_no_debug(int fd, int argc, char *argv[])
2831 return RESULT_SHOWUSAGE;
2833 ast_cli(fd,"RTCP Debugging Disabled\n");
2834 return RESULT_SUCCESS;
2837 static int rtcp_no_stats(int fd, int argc, char *argv[])
2840 return RESULT_SHOWUSAGE;
2842 ast_cli(fd,"RTCP Stats Disabled\n");
2843 return RESULT_SUCCESS;
2847 static int stun_do_debug(int fd, int argc, char *argv[])
2850 return RESULT_SHOWUSAGE;
2853 ast_cli(fd, "STUN Debugging Enabled\n");
2854 return RESULT_SUCCESS;
2857 static int stun_no_debug(int fd, int argc, char *argv[])
2860 return RESULT_SHOWUSAGE;
2862 ast_cli(fd,"STUN Debugging Disabled\n");
2863 return RESULT_SUCCESS;
2867 static char debug_usage[] =
2868 "Usage: rtp debug [ip host[:port]]\n"
2869 " Enable dumping of all RTP packets to and from host.\n";
2871 static char no_debug_usage[] =
2872 "Usage: rtp no debug\n"
2873 " Disable all RTP debugging\n";
2875 static char stun_debug_usage[] =
2876 "Usage: stun debug\n"
2877 " Enable STUN (Simple Traversal of UDP through NATs) debugging\n";
2879 static char stun_no_debug_usage[] =
2880 "Usage: stun no debug\n"
2881 " Disable STUN debugging\n";
2884 static struct ast_cli_entry cli_debug_ip =
2885 {{ "rtp", "debug", "ip", NULL } , rtp_do_debug, "Enable RTP debugging on IP", debug_usage };
2887 static struct ast_cli_entry cli_debug =
2888 {{ "rtp", "debug", NULL } , rtp_do_debug, "Enable RTP debugging", debug_usage };
2890 static struct ast_cli_entry cli_no_debug =
2891 {{ "rtp", "no", "debug", NULL } , rtp_no_debug, "Disable RTP debugging", no_debug_usage };
2893 static char rtcp_debug_usage[] =
2894 "Usage: rtp rtcp debug [ip host[:port]]\n"
2895 " Enable dumping of all RTCP packets to and from host.\n";
2897 static char rtcp_no_debug_usage[] =
2898 "Usage: rtp rtcp no debug\n"
2899 " Disable all RTCP debugging\n";
2901 static char rtcp_stats_usage[] =
2902 "Usage: rtp rtcp stats\n"
2903 " Enable dumping of RTCP stats.\n";
2905 static char rtcp_no_stats_usage[] =
2906 "Usage: rtp rtcp no stats\n"
2907 " Disable all RTCP stats\n";
2909 static struct ast_cli_entry cli_debug_ip_rtcp =
2910 {{ "rtp", "rtcp", "debug", "ip", NULL } , rtcp_do_debug, "Enable RTCP debugging on IP", rtcp_debug_usage };
2912 static struct ast_cli_entry cli_debug_rtcp =
2913 {{ "rtp", "rtcp", "debug", NULL } , rtcp_do_debug, "Enable RTCP debugging", rtcp_debug_usage };
2915 static struct ast_cli_entry cli_no_debug_rtcp =
2916 {{ "rtp", "rtcp", "no", "debug", NULL } , rtcp_no_debug, "Disable RTCP debugging", rtcp_no_debug_usage };
2918 static struct ast_cli_entry cli_stats_rtcp =
2919 {{ "rtp", "rtcp", "stats", NULL } , rtcp_do_stats, "Enable RTCP stats", rtcp_stats_usage };
2921 static struct ast_cli_entry cli_no_stats_rtcp =
2922 {{ "rtp", "rtcp", "no", "stats", NULL } , rtcp_no_stats, "Disable RTCP stats", rtcp_no_stats_usage };
2924 static struct ast_cli_entry cli_stun_debug =
2925 {{ "stun", "debug", NULL } , stun_do_debug, "Enable STUN debugging", stun_debug_usage };
2927 static struct ast_cli_entry cli_stun_no_debug =
2928 {{ "stun", "no", "debug", NULL } , stun_no_debug, "Disable STUN debugging", stun_no_debug_usage };
2930 int ast_rtp_reload(void)
2932 struct ast_config *cfg;
2937 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2938 cfg = ast_config_load("rtp.conf");
2940 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
2942 if (rtpstart < 1024)
2944 if (rtpstart > 65535)
2947 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
2954 if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
2955 rtcpinterval = atoi(s);
2956 if (rtcpinterval == 0)
2957 rtcpinterval = 0; /* Just so we're clear... it's zero */
2958 if (rtcpinterval < RTCP_MIN_INTERVALMS)
2959 rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
2960 if (rtcpinterval > RTCP_MAX_INTERVALMS)
2961 rtcpinterval = RTCP_MAX_INTERVALMS;
2963 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
2971 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
2974 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
2975 dtmftimeout = atoi(s);
2976 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
2977 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
2978 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
2979 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2982 ast_config_destroy(cfg);
2984 if (rtpstart >= rtpend) {
2985 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
2989 if (option_verbose > 1)
2990 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
2994 /*! \brief Initialize the RTP system in Asterisk */
2995 void ast_rtp_init(void)
2997 ast_cli_register(&cli_debug);
2998 ast_cli_register(&cli_debug_ip);
2999 ast_cli_register(&cli_no_debug);
3001 ast_cli_register(&cli_debug_rtcp);
3002 ast_cli_register(&cli_debug_ip_rtcp);
3003 ast_cli_register(&cli_no_debug_rtcp);
3005 ast_cli_register(&cli_stats_rtcp);
3006 ast_cli_register(&cli_no_stats_rtcp);
3008 ast_cli_register(&cli_stun_debug);
3009 ast_cli_register(&cli_stun_no_debug);