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 */
110 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
111 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
112 unsigned int themssrc; /*!< Their SSRC */
115 unsigned int lastrxts;
116 unsigned int lastividtimestamp;
117 unsigned int lastovidtimestamp;
118 unsigned int lasteventseqn;
119 int lastrxseqno; /*!< Last received sequence number */
120 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
121 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
122 unsigned int rxcount; /*!< How many packets have we received? */
123 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
124 unsigned int txcount; /*!< How many packets have we sent? */
125 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
126 unsigned int cycles; /*!< Shifted count of sequence number cycles */
127 double rxjitter; /*!< Interarrival jitter at the moment */
128 double rxtransit; /*!< Relative transit time for previous packet */
131 /* DTMF Reception Variables */
133 unsigned int lasteventendseqn;
135 unsigned int dtmfduration;
136 /* DTMF Transmission Variables */
137 unsigned int lastdigitts;
142 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
143 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
144 struct timeval rxcore;
145 struct timeval txcore;
146 double drxcore; /*!< The double representation of the first received packet */
147 struct timeval lastrx; /*!< timeval when we last received a packet */
148 struct timeval dtmfmute;
149 struct ast_smoother *smoother;
151 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
152 unsigned short rxseqno;
153 struct sched_context *sched;
154 struct io_context *io;
156 ast_rtp_callback callback;
157 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
158 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
159 int rtp_lookup_code_cache_code;
160 int rtp_lookup_code_cache_result;
161 struct ast_rtcp *rtcp;
162 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
165 /* Forward declarations */
166 static int ast_rtcp_write(void *data);
167 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
168 static int ast_rtcp_write_sr(void *data);
169 static int ast_rtcp_write_rr(void *data);
170 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
171 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
172 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
173 static int bridge_p2p_rtcp_write(struct ast_rtp *rtp, unsigned int *rtcpheader, int len);
175 #define FLAG_3389_WARNING (1 << 0)
176 #define FLAG_NAT_ACTIVE (3 << 1)
177 #define FLAG_NAT_INACTIVE (0 << 1)
178 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
179 #define FLAG_HAS_DTMF (1 << 3)
180 #define FLAG_P2P_SENT_MARK (1 << 4)
181 #define FLAG_P2P_NEED_DTMF (1 << 5)
182 #define FLAG_CALLBACK_MODE (1 << 6)
183 #define FLAG_DTMF_COMPENSATE (1 << 7)
186 * \brief Structure defining an RTCP session.
188 * The concept "RTCP session" is not defined in RFC 3550, but since
189 * this structure is analogous to ast_rtp, which tracks a RTP session,
190 * it is logical to think of this as a RTCP session.
192 * RTCP packet is defined on page 9 of RFC 3550.
196 int s; /*!< Socket */
197 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
198 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
199 unsigned int soc; /*!< What they told us */
200 unsigned int spc; /*!< What they told us */
201 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
202 struct timeval rxlsr; /*!< Time when we got their last SR */
203 struct timeval txlsr; /*!< Time when we sent or last SR*/
204 unsigned int expected_prior; /*!< no. packets in previous interval */
205 unsigned int received_prior; /*!< no. packets received in previous interval */
206 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
207 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
208 unsigned int sr_count; /*!< number of SRs we've sent */
209 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
210 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
211 double rtt; /*!< Last reported rtt */
212 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
213 unsigned int reported_lost; /*!< Reported lost packets in their RR */
214 char quality[AST_MAX_USER_FIELD];
223 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
225 /* XXX Maybe stun belongs in another file if it ever has use outside of RTP */
227 unsigned short msgtype;
228 unsigned short msglen;
230 unsigned char ies[0];
231 } __attribute__((packed));
236 unsigned char value[0];
237 } __attribute__((packed));
240 unsigned char unused;
241 unsigned char family;
244 } __attribute__((packed));
246 #define STUN_IGNORE (0)
247 #define STUN_ACCEPT (1)
249 #define STUN_BINDREQ 0x0001
250 #define STUN_BINDRESP 0x0101
251 #define STUN_BINDERR 0x0111
252 #define STUN_SECREQ 0x0002
253 #define STUN_SECRESP 0x0102
254 #define STUN_SECERR 0x0112
256 #define STUN_MAPPED_ADDRESS 0x0001
257 #define STUN_RESPONSE_ADDRESS 0x0002
258 #define STUN_CHANGE_REQUEST 0x0003
259 #define STUN_SOURCE_ADDRESS 0x0004
260 #define STUN_CHANGED_ADDRESS 0x0005
261 #define STUN_USERNAME 0x0006
262 #define STUN_PASSWORD 0x0007
263 #define STUN_MESSAGE_INTEGRITY 0x0008
264 #define STUN_ERROR_CODE 0x0009
265 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
266 #define STUN_REFLECTED_FROM 0x000b
268 static const char *stun_msg2str(int msg)
272 return "Binding Request";
274 return "Binding Response";
276 return "Binding Error Response";
278 return "Shared Secret Request";
280 return "Shared Secret Response";
282 return "Shared Secret Error Response";
284 return "Non-RFC3489 Message";
287 static const char *stun_attr2str(int msg)
290 case STUN_MAPPED_ADDRESS:
291 return "Mapped Address";
292 case STUN_RESPONSE_ADDRESS:
293 return "Response Address";
294 case STUN_CHANGE_REQUEST:
295 return "Change Request";
296 case STUN_SOURCE_ADDRESS:
297 return "Source Address";
298 case STUN_CHANGED_ADDRESS:
299 return "Changed Address";
304 case STUN_MESSAGE_INTEGRITY:
305 return "Message Integrity";
306 case STUN_ERROR_CODE:
308 case STUN_UNKNOWN_ATTRIBUTES:
309 return "Unknown Attributes";
310 case STUN_REFLECTED_FROM:
311 return "Reflected From";
313 return "Non-RFC3489 Attribute";
317 const char *username;
318 const char *password;
321 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
324 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
325 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
326 switch(ntohs(attr->attr)) {
328 state->username = (const char *) (attr->value);
331 state->password = (const char *) (attr->value);
335 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
336 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
341 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
343 int size = sizeof(**attr) + strlen(s);
345 (*attr)->attr = htons(attrval);
346 (*attr)->len = htons(strlen(s));
347 memcpy((*attr)->value, s, strlen(s));
348 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
354 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
356 int size = sizeof(**attr) + 8;
357 struct stun_addr *addr;
359 (*attr)->attr = htons(attrval);
360 (*attr)->len = htons(8);
361 addr = (struct stun_addr *)((*attr)->value);
364 addr->port = sin->sin_port;
365 addr->addr = sin->sin_addr.s_addr;
366 (*attr) = (struct stun_attr *)((*attr)->value + 8);
372 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
374 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
375 (struct sockaddr *)dst, sizeof(*dst));
378 static void stun_req_id(struct stun_header *req)
382 req->id.id[x] = ast_random();
385 size_t ast_rtp_alloc_size(void)
387 return sizeof(struct ast_rtp);
390 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
392 struct stun_header *req;
393 unsigned char reqdata[1024];
395 struct stun_attr *attr;
397 req = (struct stun_header *)reqdata;
400 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
403 attr = (struct stun_attr *)req->ies;
405 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
406 req->msglen = htons(reqlen);
407 req->msgtype = htons(STUN_BINDREQ);
408 stun_send(rtp->s, suggestion, req);
411 static int stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len)
413 struct stun_header *resp, *hdr = (struct stun_header *)data;
414 struct stun_attr *attr;
415 struct stun_state st;
416 int ret = STUN_IGNORE;
417 unsigned char respdata[1024];
418 int resplen, respleft;
420 if (len < sizeof(struct stun_header)) {
422 ast_log(LOG_DEBUG, "Runt STUN packet (only %zd, wanting at least %zd)\n", len, sizeof(struct stun_header));
426 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), ntohs(hdr->msglen));
427 if (ntohs(hdr->msglen) > len - sizeof(struct stun_header)) {
429 ast_log(LOG_DEBUG, "Scrambled STUN packet length (got %d, expecting %zd)\n", ntohs(hdr->msglen), len - sizeof(struct stun_header));
431 len = ntohs(hdr->msglen);
432 data += sizeof(struct stun_header);
433 memset(&st, 0, sizeof(st));
435 if (len < sizeof(struct stun_attr)) {
437 ast_log(LOG_DEBUG, "Runt Attribute (got %zd, expecting %zd)\n", len, sizeof(struct stun_attr));
440 attr = (struct stun_attr *)data;
441 if (ntohs(attr->len) > len) {
443 ast_log(LOG_DEBUG, "Inconsistent Attribute (length %d exceeds remaining msg len %zd)\n", ntohs(attr->len), len);
446 if (stun_process_attr(&st, attr)) {
448 ast_log(LOG_DEBUG, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
451 /* Clear attribute in case previous entry was a string */
453 data += ntohs(attr->len) + sizeof(struct stun_attr);
454 len -= ntohs(attr->len) + sizeof(struct stun_attr);
456 /* Null terminate any string */
458 resp = (struct stun_header *)respdata;
460 respleft = sizeof(respdata) - sizeof(struct stun_header);
464 attr = (struct stun_attr *)resp->ies;
466 switch(ntohs(hdr->msgtype)) {
469 ast_verbose("STUN Bind Request, username: %s\n",
470 st.username ? st.username : "<none>");
472 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
473 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
474 resp->msglen = htons(resplen);
475 resp->msgtype = htons(STUN_BINDRESP);
476 stun_send(s, src, resp);
481 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
487 /*! \brief List of current sessions */
488 static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
490 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
492 unsigned int sec, usec, frac;
493 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
495 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
500 int ast_rtp_fd(struct ast_rtp *rtp)
505 int ast_rtcp_fd(struct ast_rtp *rtp)
512 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
514 unsigned int interval;
515 /*! \todo XXX Do a more reasonable calculation on this one
516 * Look in RFC 3550 Section A.7 for an example*/
517 interval = rtcpinterval;
521 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
526 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
528 rtp->callback = callback;
531 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
536 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
538 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
541 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
543 ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
546 static struct ast_frame *send_dtmf(struct ast_rtp *rtp, enum ast_frame_type type)
548 if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
549 (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
551 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
553 rtp->dtmfduration = 0;
554 return &ast_null_frame;
557 ast_log(LOG_DEBUG, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
558 if (rtp->resp == 'X') {
559 rtp->f.frametype = AST_FRAME_CONTROL;
560 rtp->f.subclass = AST_CONTROL_FLASH;
562 rtp->f.frametype = type;
563 rtp->f.subclass = rtp->resp;
573 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
577 if (rtpdebugaddr.sin_addr.s_addr) {
578 if (((ntohs(rtpdebugaddr.sin_port) != 0)
579 && (rtpdebugaddr.sin_port != addr->sin_port))
580 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
586 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
590 if (rtcpdebugaddr.sin_addr.s_addr) {
591 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
592 && (rtcpdebugaddr.sin_port != addr->sin_port))
593 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
600 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
604 struct ast_frame *f = NULL;
605 event = ntohl(*((unsigned int *)(data)));
607 if (option_debug > 2 || rtpdebug)
608 ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
611 } else if (event < 11) {
613 } else if (event < 12) {
615 } else if (event < 16) {
616 resp = 'A' + (event - 12);
617 } else if (event < 17) {
620 if (rtp->resp && (rtp->resp != resp)) {
621 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
624 rtp->dtmfcount = dtmftimeout;
629 * \brief Process RTP DTMF and events according to RFC 2833.
631 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
639 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
642 unsigned int event_end;
643 unsigned int duration;
645 struct ast_frame *f = NULL;
647 /* Figure out event, event end, and duration */
648 event = ntohl(*((unsigned int *)(data)));
650 event_end = ntohl(*((unsigned int *)(data)));
653 duration = ntohl(*((unsigned int *)(data)));
656 /* Print out debug if turned on */
657 if (rtpdebug || option_debug > 2)
658 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
660 /* Figure out what digit was pressed */
663 } else if (event < 11) {
665 } else if (event < 12) {
667 } else if (event < 16) {
668 resp = 'A' + (event - 12);
669 } else if (event < 17) { /* Event 16: Hook flash */
673 if ((!(rtp->resp) && (!(event_end & 0x80))) || (rtp->resp && rtp->resp != resp)) {
675 if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE))
676 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
677 } else if (event_end & 0x80 && rtp->lasteventendseqn != seqno && rtp->resp) {
678 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
679 f->samples = duration;
681 rtp->lasteventendseqn = seqno;
684 rtp->dtmfcount = dtmftimeout;
685 rtp->dtmfduration = duration;
691 * \brief Process Comfort Noise RTP.
693 * This is incomplete at the moment.
696 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
698 struct ast_frame *f = NULL;
699 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
700 totally help us out becuase we don't have an engine to keep it going and we are not
701 guaranteed to have it every 20ms or anything */
703 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
705 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
706 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
707 ast_inet_ntoa(rtp->them.sin_addr));
708 ast_set_flag(rtp, FLAG_3389_WARNING);
711 /* Must have at least one byte */
715 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
716 rtp->f.datalen = len - 1;
717 rtp->f.offset = AST_FRIENDLY_OFFSET;
718 memcpy(rtp->f.data, data + 1, len - 1);
724 rtp->f.frametype = AST_FRAME_CNG;
725 rtp->f.subclass = data[0] & 0x7f;
726 rtp->f.datalen = len - 1;
728 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
733 static int rtpread(int *id, int fd, short events, void *cbdata)
735 struct ast_rtp *rtp = cbdata;
737 f = ast_rtp_read(rtp);
740 rtp->callback(rtp, f, rtp->data);
745 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
748 int position, i, packetwords;
750 struct sockaddr_in sin;
751 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
752 unsigned int *rtcpheader;
764 struct ast_frame *f = &ast_null_frame;
766 if (!rtp || !rtp->rtcp)
767 return &ast_null_frame;
771 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
772 0, (struct sockaddr *)&sin, &len);
773 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
777 ast_log(LOG_WARNING, "RTCP Read error: %s\n", strerror(errno));
780 return &ast_null_frame;
783 packetwords = res / 4;
786 /* Send to whoever sent to us */
787 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
788 (rtp->rtcp->them.sin_port != sin.sin_port)) {
789 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
790 if (option_debug || rtpdebug)
791 ast_log(LOG_DEBUG, "RTCP NAT: Got RTCP from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
795 /* If we are P2P bridged to another RTP stream, send it directly over */
796 if (ast_rtp_get_bridged(rtp) && !bridge_p2p_rtcp_write(rtp, rtcpheader, res))
797 return &ast_null_frame;
800 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
802 /* Process a compound packet */
804 while (position < packetwords) {
806 length = ntohl(rtcpheader[i]);
807 pt = (length & 0xff0000) >> 16;
808 rc = (length & 0x1f000000) >> 24;
811 if ((i + length) > packetwords) {
812 ast_log(LOG_WARNING, "RTCP Read too short\n");
813 return &ast_null_frame;
816 if (rtcp_debug_test_addr(&sin)) {
817 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
818 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
819 ast_verbose("Reception reports: %d\n", rc);
820 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
823 i += 2; /* Advance past header and ssrc */
827 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
828 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
829 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
830 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff) >> 16); /* Going to LSR in RR*/
832 if (rtcp_debug_test_addr(&sin)) {
833 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
834 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
835 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
840 /* Intentional fall through */
842 /* This is the place to calculate RTT */
843 /* Don't handle multiple reception reports (rc > 1) yet */
844 gettimeofday(&now, NULL);
845 timeval2ntp(now, &msw, &lsw);
846 /* Use the one we sent them in our SR instead, rtcp->txlsr could have been rewritten if the dlsr is large */
847 if (ntohl(rtcpheader[i + 4])) { /* We must have the LSR */
848 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
849 a = (double)((comp & 0xffff0000) >> 16) + (double)((double)(comp & 0xffff)/1000000.);
850 lsr = (double)((ntohl(rtcpheader[i + 4]) & 0xffff0000) >> 16) + (double)((double)(ntohl(rtcpheader[i + 4]) & 0xffff) / 1000000.);
851 dlsr = (double)(ntohl(rtcpheader[i + 5])/65536.);
852 rtt = a - dlsr - lsr;
853 rtp->rtcp->accumulated_transit += rtt;
854 rtp->rtcp->rtt = rtt;
855 if (rtp->rtcp->maxrtt<rtt)
856 rtp->rtcp->maxrtt = rtt;
857 if (rtp->rtcp->minrtt>rtt)
858 rtp->rtcp->minrtt = rtt;
860 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
861 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
862 if (rtcp_debug_test_addr(&sin)) {
863 ast_verbose("Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
864 ast_verbose("Packets lost so far: %d\n", rtp->rtcp->reported_lost);
865 ast_verbose("Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
866 ast_verbose("Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
867 ast_verbose("Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
868 ast_verbose("Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
869 ast_verbose("DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
871 ast_verbose("RTT: %f(sec)\n", rtt);
875 if (rtcp_debug_test_addr(&sin))
876 ast_verbose("Received an RTCP Fast Update Request\n");
877 rtp->f.frametype = AST_FRAME_CONTROL;
878 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
886 if (rtcp_debug_test_addr(&sin))
887 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
890 if (rtcp_debug_test_addr(&sin))
891 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
894 ast_log(LOG_NOTICE, "Unknown RTCP packet (pt=%d) received from %s:%d\n", pt, ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
897 position += (length + 1);
903 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
912 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
913 gettimeofday(&rtp->rxcore, NULL);
914 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
915 /* map timestamp to a real time */
916 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
917 rtp->rxcore.tv_sec -= timestamp / 8000;
918 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
919 /* Round to 0.1ms for nice, pretty timestamps */
920 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
921 if (rtp->rxcore.tv_usec < 0) {
922 /* Adjust appropriately if necessary */
923 rtp->rxcore.tv_usec += 1000000;
924 rtp->rxcore.tv_sec -= 1;
928 gettimeofday(&now,NULL);
929 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
930 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
931 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
932 if (tv->tv_usec >= 1000000) {
933 tv->tv_usec -= 1000000;
936 prog = (double)((timestamp-rtp->seedrxts)/8000.);
937 dtv = (double)rtp->drxcore + (double)(prog);
938 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
939 transit = current_time - dtv;
940 d = transit - rtp->rxtransit;
941 rtp->rxtransit = transit;
944 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
945 if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
946 rtp->rtcp->maxrxjitter = rtp->rxjitter;
947 if (rtp->rxjitter < rtp->rtcp->minrxjitter)
948 rtp->rtcp->minrxjitter = rtp->rxjitter;
951 /*! \brief Perform a Packet2Packet RTCP write */
952 static int bridge_p2p_rtcp_write(struct ast_rtp *rtp, unsigned int *rtcpheader, int len)
954 struct ast_rtp *bridged = ast_rtp_get_bridged(rtp);
957 /* If RTCP is not present on the bridged RTP session, then ignore this */
961 /* Send the data out */
962 res = sendto(bridged->rtcp->s, (void *)rtcpheader, len, 0, (struct sockaddr *)&bridged->rtcp->them, sizeof(bridged->rtcp->them));
964 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE)))
965 ast_log(LOG_DEBUG, "RTCP Transmission error of packet to %s:%d: %s\n", ast_inet_ntoa(bridged->rtcp->them.sin_addr), ntohs(bridged->rtcp->them.sin_port), strerror(errno));
966 else if ((((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug)) && (option_debug || rtpdebug))
967 ast_log(LOG_DEBUG, "RTCP NAT: Can't write RTCP to private address %s:%d, waiting for other end to send first...\n", ast_inet_ntoa(bridged->rtcp->them.sin_addr), ntohs(bridged->rtcp->them.sin_port));
968 } else if (rtp_debug_test_addr(&bridged->rtcp->them))
969 ast_verbose("Sent RTCP P2P packet to %s:%d (len %-6.6u)\n", ast_inet_ntoa(bridged->rtcp->them.sin_addr), ntohs(bridged->rtcp->them.sin_port), len);
974 /*! \brief Perform a Packet2Packet RTP write */
975 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, unsigned int *rtpheader, int len, int hdrlen)
977 struct ast_rtp *bridged = ast_rtp_get_bridged(rtp);
978 int res = 0, payload = 0, bridged_payload = 0, version, padding, mark, ext;
979 struct rtpPayloadType rtpPT;
982 /* Get fields from packet */
983 seqno = ntohl(rtpheader[0]);
984 version = (seqno & 0xC0000000) >> 30;
985 payload = (seqno & 0x7f0000) >> 16;
986 padding = seqno & (1 << 29);
987 mark = seqno & (1 << 23);
988 ext = seqno & (1 << 28);
991 /* Check what the payload value should be */
992 rtpPT = ast_rtp_lookup_pt(rtp, payload);
994 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
995 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
998 /* Otherwise adjust bridged payload to match */
999 bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
1001 /* If the mark bit has not been sent yet... do it now */
1002 if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
1004 ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
1007 /* Reconstruct part of the packet */
1008 rtpheader[0] = htonl((version << 30) | (mark << 23) | (bridged_payload << 16) | (seqno));
1010 /* Send the packet back out */
1011 res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
1013 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1014 ast_log(LOG_DEBUG, "RTP Transmission error of packet to %s:%d: %s\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), strerror(errno));
1015 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1016 if (option_debug || rtpdebug)
1017 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(bridged->them.sin_addr), ntohs(bridged->them.sin_port));
1018 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1021 } else if (rtp_debug_test_addr(&bridged->them))
1022 ast_verbose("Sent RTP P2P packet to %s:%d (type %-2.2d, len %-6.6u)\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), bridged_payload, len - hdrlen);
1027 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
1030 struct sockaddr_in sin;
1041 unsigned int timestamp;
1042 unsigned int *rtpheader;
1043 struct rtpPayloadType rtpPT;
1045 /* If time is up, kill it */
1046 if (rtp->send_digit)
1047 ast_rtp_senddigit_continuation(rtp);
1051 /* Cache where the header will go */
1052 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
1053 0, (struct sockaddr *)&sin, &len);
1055 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
1057 if (errno != EAGAIN)
1058 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
1061 return &ast_null_frame;
1065 ast_log(LOG_WARNING, "RTP Read too short\n");
1066 return &ast_null_frame;
1070 seqno = ntohl(rtpheader[0]);
1072 /* Check RTP version */
1073 version = (seqno & 0xC0000000) >> 30;
1075 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res) == STUN_ACCEPT) &&
1076 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
1077 memcpy(&rtp->them, &sin, sizeof(rtp->them));
1079 return &ast_null_frame;
1082 /* If we don't have the other side's address, then ignore this */
1083 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1084 return &ast_null_frame;
1086 /* Send to whoever send to us if NAT is turned on */
1088 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1089 (rtp->them.sin_port != sin.sin_port)) {
1092 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1093 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1096 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1097 if (option_debug || rtpdebug)
1098 ast_log(LOG_DEBUG, "RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
1102 /* If we are bridged to another RTP stream, send direct */
1103 if (ast_rtp_get_bridged(rtp) && !bridge_p2p_rtp_write(rtp, rtpheader, res, hdrlen))
1104 return &ast_null_frame;
1107 return &ast_null_frame;
1109 payloadtype = (seqno & 0x7f0000) >> 16;
1110 padding = seqno & (1 << 29);
1111 mark = seqno & (1 << 23);
1112 ext = seqno & (1 << 28);
1114 timestamp = ntohl(rtpheader[1]);
1115 ssrc = ntohl(rtpheader[2]);
1117 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1118 if (option_debug || rtpdebug)
1119 ast_log(LOG_DEBUG, "Forcing Marker bit, because SSRC has changed\n");
1126 /* Remove padding bytes */
1127 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1131 /* RTP Extension present */
1133 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
1137 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1138 return &ast_null_frame;
1141 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1143 tseqno = rtp->lastrxseqno +1;
1145 if (rtp->rxcount==1) {
1146 /* This is the first RTP packet successfully received from source */
1147 rtp->seedrxseqno = seqno;
1150 if (rtp->rtcp && rtp->rtcp->schedid < 1) {
1151 /* Schedule transmission of Receiver Report */
1152 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1155 if (tseqno > RTP_SEQ_MOD) { /* if tseqno is greater than RTP_SEQ_MOD it would indicate that the sender cycled */
1156 rtp->cycles += RTP_SEQ_MOD;
1157 ast_verbose("SEQNO cycled: %u\t%d\n", rtp->cycles, seqno);
1160 rtp->lastrxseqno = seqno;
1162 if (rtp->themssrc==0)
1163 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1165 if (rtp_debug_test_addr(&sin))
1166 ast_verbose("Got RTP packet from %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1167 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1169 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1170 if (!rtpPT.isAstFormat) {
1171 struct ast_frame *f = NULL;
1173 /* This is special in-band data that's not one of our codecs */
1174 if (rtpPT.code == AST_RTP_DTMF) {
1175 /* It's special -- rfc2833 process it */
1176 if (rtp_debug_test_addr(&sin)) {
1177 unsigned char *data;
1179 unsigned int event_end;
1180 unsigned int duration;
1181 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1182 event = ntohl(*((unsigned int *)(data)));
1184 event_end = ntohl(*((unsigned int *)(data)));
1187 duration = ntohl(*((unsigned int *)(data)));
1189 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(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
1191 if (rtp->lasteventseqn <= seqno || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
1192 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
1193 rtp->lasteventseqn = seqno;
1195 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1196 /* It's really special -- process it the Cisco way */
1197 if (rtp->lasteventseqn <= seqno || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
1198 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1199 rtp->lasteventseqn = seqno;
1201 } else if (rtpPT.code == AST_RTP_CN) {
1203 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1205 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1207 return f ? f : &ast_null_frame;
1209 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1210 rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : AST_FRAME_VIDEO;
1213 rtp->lastrxts = timestamp;
1215 rtp->rxseqno = seqno;
1217 /* Record received timestamp as last received now */
1218 rtp->lastrxts = timestamp;
1221 rtp->f.datalen = res - hdrlen;
1222 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1223 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1224 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
1225 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1226 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1227 ast_frame_byteswap_be(&rtp->f);
1228 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1229 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1230 rtp->f.has_timing_info = 1;
1231 rtp->f.ts = timestamp / 8;
1232 rtp->f.len = rtp->f.samples / 8;
1233 rtp->f.seqno = seqno;
1235 /* Video -- samples is # of samples vs. 90000 */
1236 if (!rtp->lastividtimestamp)
1237 rtp->lastividtimestamp = timestamp;
1238 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1239 rtp->lastividtimestamp = timestamp;
1240 rtp->f.delivery.tv_sec = 0;
1241 rtp->f.delivery.tv_usec = 0;
1243 rtp->f.subclass |= 0x1;
1250 /* The following array defines the MIME Media type (and subtype) for each
1251 of our codecs, or RTP-specific data type. */
1253 struct rtpPayloadType payloadType;
1257 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1258 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1259 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1260 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1261 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1262 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1263 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1264 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1265 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1266 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1267 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1268 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
1269 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1270 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1271 {{0, AST_RTP_CN}, "audio", "CN"},
1272 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1273 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1274 {{1, AST_FORMAT_H261}, "video", "H261"},
1275 {{1, AST_FORMAT_H263}, "video", "H263"},
1276 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1277 {{1, AST_FORMAT_H264}, "video", "H264"},
1280 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1281 also, our own choices for dynamic payload types. This is our master
1282 table for transmission */
1283 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1284 [0] = {1, AST_FORMAT_ULAW},
1285 #ifdef USE_DEPRECATED_G726
1286 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1288 [3] = {1, AST_FORMAT_GSM},
1289 [4] = {1, AST_FORMAT_G723_1},
1290 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1291 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1292 [7] = {1, AST_FORMAT_LPC10},
1293 [8] = {1, AST_FORMAT_ALAW},
1294 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1295 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1296 [13] = {0, AST_RTP_CN},
1297 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1298 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1299 [18] = {1, AST_FORMAT_G729A},
1300 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1301 [26] = {1, AST_FORMAT_JPEG},
1302 [31] = {1, AST_FORMAT_H261},
1303 [34] = {1, AST_FORMAT_H263},
1304 [103] = {1, AST_FORMAT_H263_PLUS},
1305 [97] = {1, AST_FORMAT_ILBC},
1306 [99] = {1, AST_FORMAT_H264},
1307 [101] = {0, AST_RTP_DTMF},
1308 [110] = {1, AST_FORMAT_SPEEX},
1309 [111] = {1, AST_FORMAT_G726},
1310 [112] = {1, AST_FORMAT_G726_AAL2},
1311 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1314 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1320 for (i = 0; i < MAX_RTP_PT; ++i) {
1321 rtp->current_RTP_PT[i].isAstFormat = 0;
1322 rtp->current_RTP_PT[i].code = 0;
1325 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1326 rtp->rtp_lookup_code_cache_code = 0;
1327 rtp->rtp_lookup_code_cache_result = 0;
1330 void ast_rtp_pt_default(struct ast_rtp* rtp)
1334 /* Initialize to default payload types */
1335 for (i = 0; i < MAX_RTP_PT; ++i) {
1336 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1337 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1340 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1341 rtp->rtp_lookup_code_cache_code = 0;
1342 rtp->rtp_lookup_code_cache_result = 0;
1345 void ast_rtp_pt_copy(struct ast_rtp *dest, const struct ast_rtp *src)
1349 for (i=0; i < MAX_RTP_PT; ++i) {
1350 dest->current_RTP_PT[i].isAstFormat =
1351 src->current_RTP_PT[i].isAstFormat;
1352 dest->current_RTP_PT[i].code =
1353 src->current_RTP_PT[i].code;
1355 dest->rtp_lookup_code_cache_isAstFormat = 0;
1356 dest->rtp_lookup_code_cache_code = 0;
1357 dest->rtp_lookup_code_cache_result = 0;
1360 /*! \brief Get channel driver interface structure */
1361 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1363 struct ast_rtp_protocol *cur = NULL;
1365 AST_LIST_LOCK(&protos);
1366 AST_LIST_TRAVERSE(&protos, cur, list) {
1367 if (cur->type == chan->tech->type)
1370 AST_LIST_UNLOCK(&protos);
1375 int ast_rtp_early_bridge(struct ast_channel *dest, struct ast_channel *src)
1377 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1378 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1379 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1380 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED;
1381 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED;
1385 ast_channel_lock(dest);
1387 while(ast_channel_trylock(src)) {
1388 ast_channel_unlock(dest);
1390 ast_channel_lock(dest);
1394 /* Find channel driver interfaces */
1395 destpr = get_proto(dest);
1397 srcpr = get_proto(src);
1400 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1401 ast_channel_unlock(dest);
1403 ast_channel_unlock(src);
1408 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src ? src->name : "<unspecified>");
1409 ast_channel_unlock(dest);
1411 ast_channel_unlock(src);
1415 /* Get audio and video interface (if native bridge is possible) */
1416 audio_dest_res = destpr->get_rtp_info(dest, &destp);
1417 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
1419 audio_src_res = srcpr->get_rtp_info(src, &srcp);
1420 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
1423 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1424 if (audio_dest_res != AST_RTP_TRY_NATIVE) {
1425 /* Somebody doesn't want to play... */
1426 ast_channel_unlock(dest);
1428 ast_channel_unlock(src);
1431 if (audio_src_res == AST_RTP_TRY_NATIVE && srcpr->get_codec)
1432 srccodec = srcpr->get_codec(src);
1435 /* Consider empty media as non-existant */
1436 if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
1438 /* Bridge media early */
1439 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, srcp ? ast_test_flag(srcp, FLAG_NAT_ACTIVE) : 0))
1440 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src ? src->name : "<unspecified>");
1441 ast_channel_unlock(dest);
1443 ast_channel_unlock(src);
1445 ast_log(LOG_DEBUG, "Setting early bridge SDP of '%s' with that of '%s'\n", dest->name, src ? src->name : "<unspecified>");
1449 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1451 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1452 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1453 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1454 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED;
1455 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED;
1459 ast_channel_lock(dest);
1460 while(ast_channel_trylock(src)) {
1461 ast_channel_unlock(dest);
1463 ast_channel_lock(dest);
1466 /* Find channel driver interfaces */
1467 if (!(destpr = get_proto(dest))) {
1469 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1470 ast_channel_unlock(dest);
1471 ast_channel_unlock(src);
1474 if (!(srcpr = get_proto(src))) {
1476 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
1477 ast_channel_unlock(dest);
1478 ast_channel_unlock(src);
1482 /* Get audio and video interface (if native bridge is possible) */
1483 audio_dest_res = destpr->get_rtp_info(dest, &destp);
1484 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
1485 audio_src_res = srcpr->get_rtp_info(src, &srcp);
1486 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
1488 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1489 if (audio_dest_res != AST_RTP_TRY_NATIVE || audio_src_res != AST_RTP_TRY_NATIVE) {
1490 /* Somebody doesn't want to play... */
1491 ast_channel_unlock(dest);
1492 ast_channel_unlock(src);
1495 ast_rtp_pt_copy(destp, srcp);
1496 if (vdestp && vsrcp)
1497 ast_rtp_pt_copy(vdestp, vsrcp);
1498 if (srcpr->get_codec)
1499 srccodec = srcpr->get_codec(src);
1504 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1505 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1507 ast_channel_unlock(dest);
1508 ast_channel_unlock(src);
1510 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1514 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1515 * By default, use the well-known value for this type (although it may
1516 * still be set to a different value by a subsequent "a=rtpmap:" line)
1518 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1520 if (pt < 0 || pt > MAX_RTP_PT)
1521 return; /* bogus payload type */
1523 if (static_RTP_PT[pt].code != 0)
1524 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1527 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1528 * an SDP "a=rtpmap:" line.
1530 void ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
1531 char *mimeType, char *mimeSubtype,
1532 enum ast_rtp_options options)
1536 if (pt < 0 || pt > MAX_RTP_PT)
1537 return; /* bogus payload type */
1539 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1540 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1541 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1542 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1543 if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
1544 mimeTypes[i].payloadType.isAstFormat &&
1545 (options & AST_RTP_OPT_G726_NONSTANDARD))
1546 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
1552 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
1553 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1554 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1555 int* astFormats, int* nonAstFormats) {
1558 *astFormats = *nonAstFormats = 0;
1559 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1560 if (rtp->current_RTP_PT[pt].isAstFormat) {
1561 *astFormats |= rtp->current_RTP_PT[pt].code;
1563 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
1568 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
1570 struct rtpPayloadType result;
1572 result.isAstFormat = result.code = 0;
1573 if (pt < 0 || pt > MAX_RTP_PT)
1574 return result; /* bogus payload type */
1576 /* Start with negotiated codecs */
1577 result = rtp->current_RTP_PT[pt];
1579 /* If it doesn't exist, check our static RTP type list, just in case */
1581 result = static_RTP_PT[pt];
1585 /*! \brief Looks up an RTP code out of our *static* outbound list */
1586 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
1590 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
1591 code == rtp->rtp_lookup_code_cache_code) {
1593 /* Use our cached mapping, to avoid the overhead of the loop below */
1594 return rtp->rtp_lookup_code_cache_result;
1597 /* Check the dynamic list first */
1598 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1599 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
1600 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1601 rtp->rtp_lookup_code_cache_code = code;
1602 rtp->rtp_lookup_code_cache_result = pt;
1607 /* Then the static list */
1608 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1609 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
1610 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1611 rtp->rtp_lookup_code_cache_code = code;
1612 rtp->rtp_lookup_code_cache_result = pt;
1619 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
1620 enum ast_rtp_options options)
1624 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1625 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
1627 (code == AST_FORMAT_G726_AAL2) &&
1628 (options & AST_RTP_OPT_G726_NONSTANDARD))
1629 return "AAL2-G726-32";
1631 return mimeTypes[i].subtype;
1638 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
1639 const int isAstFormat, enum ast_rtp_options options)
1649 snprintf(end, size, "0x%x (", capability);
1656 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
1657 if (capability & format) {
1658 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
1660 snprintf(end, size, "%s|", name);
1668 snprintf(start, size, "nothing)");
1675 static int rtp_socket(void)
1679 s = socket(AF_INET, SOCK_DGRAM, 0);
1681 flags = fcntl(s, F_GETFL);
1682 fcntl(s, F_SETFL, flags | O_NONBLOCK);
1685 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
1692 * \brief Initialize a new RTCP session.
1694 * \returns The newly initialized RTCP session.
1696 static struct ast_rtcp *ast_rtcp_new(void)
1698 struct ast_rtcp *rtcp;
1700 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
1702 rtcp->s = rtp_socket();
1703 rtcp->us.sin_family = AF_INET;
1704 rtcp->them.sin_family = AF_INET;
1708 ast_log(LOG_WARNING, "Unable to allocate RTCP socket: %s\n", strerror(errno));
1715 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
1717 struct ast_rtp *rtp;
1722 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
1724 rtp->them.sin_family = AF_INET;
1725 rtp->us.sin_family = AF_INET;
1726 rtp->s = rtp_socket();
1727 rtp->ssrc = ast_random();
1728 rtp->seqno = ast_random() & 0xffff;
1729 ast_set_flag(rtp, FLAG_HAS_DTMF);
1732 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1735 if (sched && rtcpenable) {
1737 rtp->rtcp = ast_rtcp_new();
1740 /* Select a random port number in the range of possible RTP */
1741 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
1743 /* Save it for future references. */
1745 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1747 /* Must be an even port number by RTP spec */
1748 rtp->us.sin_port = htons(x);
1749 rtp->us.sin_addr = addr;
1750 /* If there's rtcp, initialize it as well. */
1752 rtp->rtcp->us.sin_port = htons(x + 1);
1753 /* Try to bind it/them. */
1754 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1755 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1758 /* Primary bind succeeded! Gotta recreate it */
1760 rtp->s = rtp_socket();
1762 if (errno != EADDRINUSE) {
1763 /* We got an error that wasn't expected, abort! */
1764 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1767 close(rtp->rtcp->s);
1773 /* The port was used, increment it (by two). */
1775 /* Did we go over the limit ? */
1777 /* then, start from the begingig. */
1778 x = (rtpstart + 1) & ~1;
1779 /* Check if we reached the place were we started. */
1780 if (x == startplace) {
1781 /* If so, there's no ports available. */
1782 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1785 close(rtp->rtcp->s);
1795 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1796 ast_set_flag(rtp, FLAG_CALLBACK_MODE);
1798 ast_rtp_pt_default(rtp);
1802 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1806 memset(&ia, 0, sizeof(ia));
1807 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1810 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1814 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1815 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1819 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1821 rtp->them.sin_port = them->sin_port;
1822 rtp->them.sin_addr = them->sin_addr;
1824 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1825 rtp->rtcp->them.sin_addr = them->sin_addr;
1830 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1832 if ((them->sin_family != AF_INET) ||
1833 (them->sin_port != rtp->them.sin_port) ||
1834 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
1835 them->sin_family = AF_INET;
1836 them->sin_port = rtp->them.sin_port;
1837 them->sin_addr = rtp->them.sin_addr;
1843 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1848 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
1850 return rtp->bridged;
1853 void ast_rtp_stop(struct ast_rtp *rtp)
1855 if (rtp->rtcp && rtp->rtcp->schedid > 0) {
1856 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1857 rtp->rtcp->schedid = -1;
1860 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1861 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1863 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
1864 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
1867 ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
1870 void ast_rtp_reset(struct ast_rtp *rtp)
1872 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1873 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1874 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1876 rtp->lastdigitts = 0;
1878 rtp->lastividtimestamp = 0;
1879 rtp->lastovidtimestamp = 0;
1880 rtp->lasteventseqn = 0;
1881 rtp->lasteventendseqn = 0;
1882 rtp->lasttxformat = 0;
1883 rtp->lastrxformat = 0;
1885 rtp->dtmfduration = 0;
1890 char *ast_rtp_get_quality(struct ast_rtp *rtp)
1894 *themssrc their ssrc
1896 *rxjitter our calculated jitter(rx)
1897 *rxcount no. received packets
1898 *txjitter reported jitter of the other end
1899 *txcount transmitted packets
1900 *rlp remote lost packets
1903 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);
1905 return rtp->rtcp->quality;
1908 void ast_rtp_destroy(struct ast_rtp *rtp)
1910 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
1911 /*Print some info on the call here */
1912 ast_verbose(" RTP-stats\n");
1913 ast_verbose("* Our Receiver:\n");
1914 ast_verbose(" SSRC: %u\n", rtp->themssrc);
1915 ast_verbose(" Received packets: %u\n", rtp->rxcount);
1916 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
1917 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
1918 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
1919 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
1920 ast_verbose("* Our Sender:\n");
1921 ast_verbose(" SSRC: %u\n", rtp->ssrc);
1922 ast_verbose(" Sent packets: %u\n", rtp->txcount);
1923 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
1924 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter);
1925 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
1926 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
1930 ast_smoother_free(rtp->smoother);
1932 ast_io_remove(rtp->io, rtp->ioid);
1936 if (rtp->rtcp->schedid > 0)
1937 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1938 close(rtp->rtcp->s);
1945 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1949 if (ast_tvzero(rtp->txcore)) {
1950 rtp->txcore = ast_tvnow();
1951 /* Round to 20ms for nice, pretty timestamps */
1952 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1954 /* Use previous txcore if available */
1955 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
1956 ms = ast_tvdiff_ms(t, rtp->txcore);
1959 /* Use what we just got for next time */
1961 return (unsigned int) ms;
1964 /* Convert DTMF digit into something usable */
1965 static int digit_convert(char digit)
1967 if ((digit <= '9') && (digit >= '0'))
1969 else if (digit == '*')
1971 else if (digit == '#')
1973 else if ((digit >= 'A') && (digit <= 'D'))
1974 digit = digit - 'A' + 12;
1975 else if ((digit >= 'a') && (digit <= 'd'))
1976 digit = digit - 'a' + 12;
1978 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
1984 /*! \brief Send begin frames for DTMF */
1985 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
1987 unsigned int *rtpheader;
1988 int hdrlen = 12, res = 0, i = 0, payload = 0;
1991 if (digit_convert(digit))
1994 /* If we have no peer, return immediately */
1995 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1998 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
2000 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2002 /* Get a pointer to the header */
2003 rtpheader = (unsigned int *)data;
2004 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2005 rtpheader[1] = htonl(rtp->lastdigitts);
2006 rtpheader[2] = htonl(rtp->ssrc);
2007 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
2009 for (i = 0; i < 2; i++) {
2010 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2012 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2013 ast_inet_ntoa(rtp->them.sin_addr),
2014 ntohs(rtp->them.sin_port), strerror(errno));
2015 if (rtp_debug_test_addr(&rtp->them))
2016 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2017 ast_inet_ntoa(rtp->them.sin_addr),
2018 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2019 /* Increment sequence number */
2021 /* Clear marker bit and set seqno */
2022 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2025 /* Since we received a begin, we can safely store the digit and disable any compensation */
2026 rtp->send_digit = digit;
2027 rtp->send_payload = payload;
2032 /*! \brief Send continuation frame for DTMF */
2033 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
2035 unsigned int *rtpheader;
2036 int hdrlen = 12, res = 0;
2039 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2042 /* Setup packet to send */
2043 rtpheader = (unsigned int *)data;
2044 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2045 rtpheader[1] = htonl(rtp->lastdigitts);
2046 rtpheader[2] = htonl(rtp->ssrc);
2047 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (0));
2048 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2051 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2053 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2054 ast_inet_ntoa(rtp->them.sin_addr),
2055 ntohs(rtp->them.sin_port), strerror(errno));
2056 if (rtp_debug_test_addr(&rtp->them))
2057 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2058 ast_inet_ntoa(rtp->them.sin_addr),
2059 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2061 /* Increment sequence number */
2067 /*! \brief Send end packets for DTMF */
2068 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
2070 unsigned int *rtpheader;
2071 int hdrlen = 12, res = 0, i = 0;
2074 /* If no address, then bail out */
2075 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2078 /* Convert our digit to the crazy RTP way */
2079 if (digit_convert(digit))
2082 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2084 rtpheader = (unsigned int *)data;
2085 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2086 rtpheader[1] = htonl(rtp->lastdigitts);
2087 rtpheader[2] = htonl(rtp->ssrc);
2088 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
2089 /* Send duration to 100ms */
2090 rtpheader[3] |= htonl((800));
2092 rtpheader[3] |= htonl((1 << 23));
2093 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2094 /* Send 3 termination packets */
2095 for (i = 0; i < 3; i++) {
2096 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2098 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2099 ast_inet_ntoa(rtp->them.sin_addr),
2100 ntohs(rtp->them.sin_port), strerror(errno));
2101 if (rtp_debug_test_addr(&rtp->them))
2102 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2103 ast_inet_ntoa(rtp->them.sin_addr),
2104 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2106 rtp->send_digit = 0;
2107 /* Increment lastdigitts */
2108 rtp->lastdigitts += 960;
2114 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
2115 int ast_rtcp_send_h261fur(void *data)
2117 struct ast_rtp *rtp = data;
2120 rtp->rtcp->sendfur = 1;
2121 res = ast_rtcp_write(data);
2126 /*! \brief Send RTCP sender's report */
2127 static int ast_rtcp_write_sr(void *data)
2129 struct ast_rtp *rtp = data;
2133 unsigned int now_lsw;
2134 unsigned int now_msw;
2135 unsigned int *rtcpheader;
2137 unsigned int extended;
2138 unsigned int expected;
2139 unsigned int expected_interval;
2140 unsigned int received_interval;
2143 struct timeval dlsr;
2146 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2149 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
2150 ast_verbose("RTCP SR transmission error, rtcp halted %s\n",strerror(errno));
2151 if (rtp->rtcp->schedid > 0)
2152 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2153 rtp->rtcp->schedid = -1;
2157 gettimeofday(&now, NULL);
2158 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
2159 rtcpheader = (unsigned int *)bdata;
2160 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
2161 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
2162 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
2163 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
2164 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
2165 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
2168 extended = rtp->cycles + rtp->lastrxseqno;
2169 expected = extended - rtp->seedrxseqno + 1;
2170 if (rtp->rxcount > expected)
2171 expected += rtp->rxcount - expected;
2172 lost = expected - rtp->rxcount;
2173 expected_interval = expected - rtp->rtcp->expected_prior;
2174 rtp->rtcp->expected_prior = expected;
2175 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2176 rtp->rtcp->received_prior = rtp->rxcount;
2177 lost_interval = expected_interval - received_interval;
2178 if (expected_interval == 0 || lost_interval <= 0)
2181 fraction = (lost_interval << 8) / expected_interval;
2182 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2183 rtcpheader[7] = htonl(rtp->themssrc);
2184 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2185 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2186 rtcpheader[10] = htonl((unsigned int)rtp->rxjitter);
2187 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2188 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2191 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2193 if (rtp->rtcp->sendfur) {
2194 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2195 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
2197 rtp->rtcp->sendfur = 0;
2200 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2201 /* it can change mid call, and SDES can't) */
2202 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2203 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2204 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2207 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2209 ast_log(LOG_ERROR, "RTCP SR transmission error to %s:%d, rtcp halted %s\n",ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port), strerror(errno));
2210 if (rtp->rtcp->schedid > 0)
2211 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2212 rtp->rtcp->schedid = -1;
2216 /* FIXME Don't need to get a new one */
2217 gettimeofday(&rtp->rtcp->txlsr, NULL);
2218 rtp->rtcp->sr_count++;
2220 rtp->rtcp->lastsrtxcount = rtp->txcount;
2222 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2223 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2224 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
2225 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2226 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
2227 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2228 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
2229 ast_verbose(" Report block:\n");
2230 ast_verbose(" Fraction lost: %u\n", fraction);
2231 ast_verbose(" Cumulative loss: %u\n", lost);
2232 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
2233 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
2234 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2239 /*! \brief Send RTCP recepient's report */
2240 static int ast_rtcp_write_rr(void *data)
2242 struct ast_rtp *rtp = data;
2246 unsigned int extended;
2247 unsigned int expected;
2248 unsigned int expected_interval;
2249 unsigned int received_interval;
2252 unsigned int *rtcpheader;
2254 struct timeval dlsr;
2257 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2260 if (!rtp->rtcp->them.sin_addr.s_addr) {
2261 ast_log(LOG_ERROR, "RTCP RR transmission error to, rtcp halted %s\n",strerror(errno));
2262 if (rtp->rtcp->schedid > 0)
2263 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2264 rtp->rtcp->schedid = -1;
2268 extended = rtp->cycles + rtp->lastrxseqno;
2269 expected = extended - rtp->seedrxseqno + 1;
2270 lost = expected - rtp->rxcount;
2271 expected_interval = expected - rtp->rtcp->expected_prior;
2272 rtp->rtcp->expected_prior = expected;
2273 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2274 rtp->rtcp->received_prior = rtp->rxcount;
2275 lost_interval = expected_interval - received_interval;
2276 if (expected_interval == 0 || lost_interval <= 0)
2279 fraction = (lost_interval << 8) / expected_interval;
2280 gettimeofday(&now, NULL);
2281 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2282 rtcpheader = (unsigned int *)bdata;
2283 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2284 rtcpheader[1] = htonl(rtp->ssrc);
2285 rtcpheader[2] = htonl(rtp->themssrc);
2286 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2287 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2288 rtcpheader[5] = htonl((unsigned int)rtp->rxjitter);
2289 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2290 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2292 if (rtp->rtcp->sendfur) {
2293 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2294 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
2296 rtp->rtcp->sendfur = 0;
2299 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2300 it can change mid call, and SDES can't) */
2301 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2302 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2303 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2306 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2309 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2310 /* Remove the scheduler */
2311 if (rtp->rtcp->schedid > 0)
2312 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2313 rtp->rtcp->schedid = -1;
2317 rtp->rtcp->rr_count++;
2319 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2320 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2321 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2322 " IA jitter: %.4f\n"
2323 " Their last SR: %u\n"
2324 " DLSR: %4.4f (sec)\n\n",
2325 ast_inet_ntoa(rtp->rtcp->them.sin_addr),
2326 ntohs(rtp->rtcp->them.sin_port),
2327 rtp->ssrc, rtp->themssrc, fraction, lost,
2329 rtp->rtcp->themrxlsr,
2330 (double)(ntohl(rtcpheader[7])/65536.0));
2336 /*! \brief Write and RTCP packet to the far end
2337 * \note Decide if we are going to send an SR (with Reception Block) or RR
2338 * RR is sent if we have not sent any rtp packets in the previous interval */
2339 static int ast_rtcp_write(void *data)
2341 struct ast_rtp *rtp = data;
2344 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2345 res = ast_rtcp_write_sr(data);
2347 res = ast_rtcp_write_rr(data);
2352 /*! \brief generate comfort noice (CNG) */
2353 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2355 unsigned int *rtpheader;
2360 level = 127 - (level & 0x7f);
2361 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2363 /* If we have no peer, return immediately */
2364 if (!rtp->them.sin_addr.s_addr)
2367 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2369 /* Get a pointer to the header */
2370 rtpheader = (unsigned int *)data;
2371 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2372 rtpheader[1] = htonl(rtp->lastts);
2373 rtpheader[2] = htonl(rtp->ssrc);
2375 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2376 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2378 ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s:%d: %s\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
2379 if (rtp_debug_test_addr(&rtp->them))
2380 ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %u, len %d)\n"
2381 , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
2387 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2389 unsigned char *rtpheader;
2396 ms = calc_txstamp(rtp, &f->delivery);
2397 /* Default prediction */
2398 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
2399 pred = rtp->lastts + f->samples;
2401 /* Re-calculate last TS */
2402 rtp->lastts = rtp->lastts + ms * 8;
2403 if (ast_tvzero(f->delivery)) {
2404 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
2405 and if so, go with our prediction */
2406 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
2409 if (option_debug > 2)
2410 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2415 mark = f->subclass & 0x1;
2416 pred = rtp->lastovidtimestamp + f->samples;
2417 /* Re-calculate last TS */
2418 rtp->lastts = rtp->lastts + ms * 90;
2419 /* If it's close to our prediction, go for it */
2420 if (ast_tvzero(f->delivery)) {
2421 if (abs(rtp->lastts - pred) < 7200) {
2423 rtp->lastovidtimestamp += f->samples;
2425 if (option_debug > 2)
2426 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);
2427 rtp->lastovidtimestamp = rtp->lastts;
2431 /* If the timestamp for non-digit packets has moved beyond the timestamp
2432 for digits, update the digit timestamp.
2434 if (rtp->lastts > rtp->lastdigitts)
2435 rtp->lastdigitts = rtp->lastts;
2437 if (f->has_timing_info)
2438 rtp->lastts = f->ts * 8;
2440 /* Get a pointer to the header */
2441 rtpheader = (unsigned char *)(f->data - hdrlen);
2443 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
2444 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
2445 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
2447 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2448 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2450 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
2451 ast_log(LOG_DEBUG, "RTP Transmission error of packet %d to %s:%d: %s\n", rtp->seqno, ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
2452 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
2453 /* Only give this error message once if we are not RTP debugging */
2454 if (option_debug || rtpdebug)
2455 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(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
2456 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
2460 rtp->txoctetcount +=(res - hdrlen);
2462 if (rtp->rtcp && rtp->rtcp->schedid < 1)
2463 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
2466 if (rtp_debug_test_addr(&rtp->them))
2467 ast_verbose("Sent RTP packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2468 ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
2476 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
2478 struct ast_frame *f;
2484 /* If we have no peer, return immediately */
2485 if (!rtp->them.sin_addr.s_addr)
2488 /* If there is no data length, return immediately */
2492 /* Make sure we have enough space for RTP header */
2493 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
2494 ast_log(LOG_WARNING, "RTP can only send voice and video\n");
2498 subclass = _f->subclass;
2499 if (_f->frametype == AST_FRAME_VIDEO)
2502 codec = ast_rtp_lookup_code(rtp, 1, subclass);
2504 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
2508 if (rtp->lasttxformat != subclass) {
2509 /* New format, reset the smoother */
2511 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
2512 rtp->lasttxformat = subclass;
2514 ast_smoother_free(rtp->smoother);
2515 rtp->smoother = NULL;
2520 case AST_FORMAT_SLINEAR:
2521 if (!rtp->smoother) {
2522 rtp->smoother = ast_smoother_new(320);
2524 if (!rtp->smoother) {
2525 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2528 ast_smoother_feed_be(rtp->smoother, _f);
2530 while((f = ast_smoother_read(rtp->smoother)))
2531 ast_rtp_raw_write(rtp, f, codec);
2533 case AST_FORMAT_ULAW:
2534 case AST_FORMAT_ALAW:
2535 if (!rtp->smoother) {
2536 rtp->smoother = ast_smoother_new(160);
2538 if (!rtp->smoother) {
2539 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2542 ast_smoother_feed(rtp->smoother, _f);
2544 while((f = ast_smoother_read(rtp->smoother)))
2545 ast_rtp_raw_write(rtp, f, codec);
2547 case AST_FORMAT_ADPCM:
2548 case AST_FORMAT_G726:
2549 case AST_FORMAT_G726_AAL2:
2550 if (!rtp->smoother) {
2551 rtp->smoother = ast_smoother_new(80);
2553 if (!rtp->smoother) {
2554 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2557 ast_smoother_feed(rtp->smoother, _f);
2559 while((f = ast_smoother_read(rtp->smoother)))
2560 ast_rtp_raw_write(rtp, f, codec);
2562 case AST_FORMAT_G729A:
2563 if (!rtp->smoother) {
2564 rtp->smoother = ast_smoother_new(20);
2566 ast_smoother_set_flags(rtp->smoother, AST_SMOOTHER_FLAG_G729);
2568 if (!rtp->smoother) {
2569 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
2572 ast_smoother_feed(rtp->smoother, _f);
2574 while((f = ast_smoother_read(rtp->smoother)))
2575 ast_rtp_raw_write(rtp, f, codec);
2577 case AST_FORMAT_GSM:
2578 if (!rtp->smoother) {
2579 rtp->smoother = ast_smoother_new(33);
2581 if (!rtp->smoother) {
2582 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
2585 ast_smoother_feed(rtp->smoother, _f);
2586 while((f = ast_smoother_read(rtp->smoother)))
2587 ast_rtp_raw_write(rtp, f, codec);
2589 case AST_FORMAT_ILBC:
2590 if (!rtp->smoother) {
2591 rtp->smoother = ast_smoother_new(50);
2593 if (!rtp->smoother) {
2594 ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
2597 ast_smoother_feed(rtp->smoother, _f);
2598 while((f = ast_smoother_read(rtp->smoother)))
2599 ast_rtp_raw_write(rtp, f, codec);
2602 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
2603 /* fall through to... */
2604 case AST_FORMAT_H261:
2605 case AST_FORMAT_H263:
2606 case AST_FORMAT_H263_PLUS:
2607 case AST_FORMAT_H264:
2608 case AST_FORMAT_G723_1:
2609 case AST_FORMAT_LPC10:
2610 case AST_FORMAT_SPEEX:
2611 /* Don't buffer outgoing frames; send them one-per-packet: */
2612 if (_f->offset < hdrlen) {
2617 ast_rtp_raw_write(rtp, f, codec);
2623 /*! \brief Unregister interface to channel driver */
2624 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
2626 AST_LIST_LOCK(&protos);
2627 AST_LIST_REMOVE(&protos, proto, list);
2628 AST_LIST_UNLOCK(&protos);
2631 /*! \brief Register interface to channel driver */
2632 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
2634 struct ast_rtp_protocol *cur;
2636 AST_LIST_LOCK(&protos);
2637 AST_LIST_TRAVERSE(&protos, cur, list) {
2638 if (!strcmp(cur->type, proto->type)) {
2639 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
2640 AST_LIST_UNLOCK(&protos);
2644 AST_LIST_INSERT_HEAD(&protos, proto, list);
2645 AST_LIST_UNLOCK(&protos);
2650 /*! \brief Bridge loop for true native bridge (reinvite) */
2651 static enum ast_bridge_result bridge_native_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp *p0, struct ast_rtp *p1, struct ast_rtp *vp0, struct ast_rtp *vp1, struct ast_rtp_protocol *pr0, struct ast_rtp_protocol *pr1, int codec0, int codec1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
2653 struct ast_frame *fr = NULL;
2654 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
2655 int oldcodec0 = codec0, oldcodec1 = codec1;
2656 struct sockaddr_in ac1 = {0,}, vac1 = {0,}, ac0 = {0,}, vac0 = {0,};
2657 struct sockaddr_in t1 = {0,}, vt1 = {0,}, t0 = {0,}, vt0 = {0,};
2659 /* Set it up so audio goes directly between the two endpoints */
2661 /* Test the first channel */
2662 if (!(pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))) {
2663 ast_rtp_get_peer(p1, &ac1);
2665 ast_rtp_get_peer(vp1, &vac1);
2667 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
2669 /* Test the second channel */
2670 if (!(pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))) {
2671 ast_rtp_get_peer(p0, &ac0);
2673 ast_rtp_get_peer(vp0, &vac0);
2675 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c1->name, c0->name);
2677 /* Now we can unlock and move into our loop */
2678 ast_channel_unlock(c0);
2679 ast_channel_unlock(c1);
2681 /* Throw our channels into the structure and enter the loop */
2686 /* Check if anything changed */
2687 if ((c0->tech_pvt != pvt0) ||
2688 (c1->tech_pvt != pvt1) ||
2689 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
2690 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
2691 if (c0->tech_pvt == pvt0)
2692 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2693 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2694 if (c1->tech_pvt == pvt1)
2695 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2696 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2697 return AST_BRIDGE_RETRY;
2700 /* Check if they have changed their address */
2701 ast_rtp_get_peer(p1, &t1);
2703 ast_rtp_get_peer(vp1, &vt1);
2705 codec1 = pr1->get_codec(c1);
2706 ast_rtp_get_peer(p0, &t0);
2708 ast_rtp_get_peer(vp0, &vt0);
2710 codec0 = pr0->get_codec(c0);
2711 if ((inaddrcmp(&t1, &ac1)) ||
2712 (vp1 && inaddrcmp(&vt1, &vac1)) ||
2713 (codec1 != oldcodec1)) {
2714 if (option_debug > 1) {
2715 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2716 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
2717 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
2718 c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
2719 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2720 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
2721 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2722 c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
2724 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)))
2725 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
2726 memcpy(&ac1, &t1, sizeof(ac1));
2727 memcpy(&vac1, &vt1, sizeof(vac1));
2730 if ((inaddrcmp(&t0, &ac0)) ||
2731 (vp0 && inaddrcmp(&vt0, &vac0))) {
2732 if (option_debug > 1) {
2733 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2734 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
2735 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2736 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
2738 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)))
2739 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
2740 memcpy(&ac0, &t0, sizeof(ac0));
2741 memcpy(&vac0, &vt0, sizeof(vac0));
2745 /* Wait for frame to come in on the channels */
2746 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
2748 return AST_BRIDGE_RETRY;
2750 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2751 if (ast_check_hangup(c0) || ast_check_hangup(c1))
2756 other = (who == c0) ? c1 : c0;
2757 if (!fr || ((fr->frametype == AST_FRAME_DTMF) &&
2758 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
2759 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
2760 /* Break out of bridge */
2764 ast_log(LOG_DEBUG, "Oooh, got a %s\n", fr ? "digit" : "hangup");
2765 if (c0->tech_pvt == pvt0)
2766 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2767 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2768 if (c1->tech_pvt == pvt1)
2769 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2770 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2771 return AST_BRIDGE_COMPLETE;
2772 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2773 if ((fr->subclass == AST_CONTROL_HOLD) ||
2774 (fr->subclass == AST_CONTROL_UNHOLD) ||
2775 (fr->subclass == AST_CONTROL_VIDUPDATE)) {
2776 ast_indicate(other, fr->subclass);
2781 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
2782 return AST_BRIDGE_COMPLETE;
2785 if ((fr->frametype == AST_FRAME_DTMF) ||
2786 (fr->frametype == AST_FRAME_VOICE) ||
2787 (fr->frametype == AST_FRAME_VIDEO)) {
2788 ast_write(other, fr);
2798 return AST_BRIDGE_FAILED;
2801 /*! \brief P2P RTP/RTCP Callback */
2802 static int p2p_rtp_callback(int *id, int fd, short events, void *cbdata)
2804 int res = 0, hdrlen = 12;
2805 struct sockaddr_in sin;
2807 unsigned int *header;
2808 struct ast_rtp *rtp = cbdata;
2809 int is_rtp = 0, is_rtcp = 0;
2815 if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
2818 header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
2820 /* Determine what this file descriptor is for */
2823 else if (rtp->rtcp && rtp->rtcp->s == fd)
2826 /* If NAT support is turned on, then see if we need to change their address */
2828 /* If this is for RTP, check that - if it's for RTCP, check that */
2830 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
2831 (rtp->them.sin_port != sin.sin_port)) {
2834 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
2835 if (option_debug || rtpdebug)
2836 ast_log(LOG_DEBUG, "P2P RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
2838 } else if (is_rtcp) {
2839 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
2840 (rtp->rtcp->them.sin_port != sin.sin_port)) {
2841 rtp->rtcp->them = sin;
2842 if (option_debug || rtpdebug)
2843 ast_log(LOG_DEBUG, "P2P RTCP NAT: Got RTCP from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2848 /* If this came from the RTP stream, write out via RTP - if it's RTCP, write out via RTCP */
2849 if (ast_rtp_get_bridged(rtp)) {
2851 bridge_p2p_rtp_write(rtp, header, res, hdrlen);
2853 bridge_p2p_rtcp_write(rtp, header, res);
2859 /*! \brief Helper function to switch a channel and RTP stream into callback mode */
2860 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int *fds, int **iod)
2862 /* If we need DTMF or we have no IO structure, then we can't do direct callback */
2863 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) || !rtp->io)
2866 /* If the RTP structure is already in callback mode, remove it temporarily */
2868 ast_io_remove(rtp->io, rtp->ioid);
2872 /* Steal the file descriptors from the channel and stash them away */
2873 fds[0] = chan->fds[0];
2874 fds[1] = chan->fds[1];
2878 /* Now, fire up callback mode */
2879 iod[0] = ast_io_add(rtp->io, fds[0], p2p_rtp_callback, AST_IO_IN, rtp);
2881 iod[1] = ast_io_add(rtp->io, fds[1], p2p_rtp_callback, AST_IO_IN, rtp);
2886 /*! \brief Helper function to switch a channel and RTP stream out of callback mode */
2887 static int p2p_callback_disable(struct ast_channel *chan, struct ast_rtp *rtp, int *fds, int **iod)
2889 ast_channel_lock(chan);
2890 /* Remove the callback from the IO context */
2891 ast_io_remove(rtp->io, iod[0]);
2892 ast_io_remove(rtp->io, iod[1]);
2893 /* Restore file descriptors */
2894 chan->fds[0] = fds[0];
2895 chan->fds[1] = fds[1];
2896 ast_channel_unlock(chan);
2897 /* Restore callback mode if previously used */
2898 if (ast_test_flag(rtp, FLAG_CALLBACK_MODE))
2899 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
2903 /*! \brief Bridge loop for partial native bridge (packet2packet) */
2904 static enum ast_bridge_result bridge_p2p_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp *p0, struct ast_rtp *p1, struct ast_rtp *vp0, struct ast_rtp *vp1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
2906 struct ast_frame *fr = NULL;
2907 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
2908 int p0_fds[2] = {-1, -1}, p1_fds[2] = {-1, -1};
2909 int *p0_iod[2] = {NULL, }, *p1_iod[2] = {NULL, };
2910 int p0_callback = 0, p1_callback = 0;
2911 enum ast_bridge_result res = AST_BRIDGE_FAILED;
2913 /* Okay, setup each RTP structure to do P2P forwarding */
2914 ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
2916 ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
2919 ast_clear_flag(vp0, FLAG_P2P_SENT_MARK);
2921 ast_clear_flag(vp1, FLAG_P2P_SENT_MARK);
2925 /* Activate callback modes if possible */
2926 p0_callback = p2p_callback_enable(c0, p0, &p0_fds[0], &p0_iod[0]);
2927 p1_callback = p2p_callback_enable(c1, p1, &p1_fds[0], &p1_iod[0]);
2929 /* Now let go of the channel locks and be on our way */
2930 ast_channel_unlock(c0);
2931 ast_channel_unlock(c1);
2933 /* Go into a loop forwarding frames until we don't need to anymore */
2938 /* Check if anything changed */
2939 if ((c0->tech_pvt != pvt0) ||
2940 (c1->tech_pvt != pvt1) ||
2941 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
2942 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
2943 res = AST_BRIDGE_RETRY;
2946 /* Wait on a channel to feed us a frame */
2947 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
2949 res = AST_BRIDGE_RETRY;
2953 ast_log(LOG_NOTICE, "Ooh, empty read...\n");
2954 if (ast_check_hangup(c0) || ast_check_hangup(c1))
2958 /* Read in frame from channel */
2960 other = (who == c0) ? c1 : c0;
2961 /* Dependong on the frame we may need to break out of our bridge */
2962 if (!fr || ((fr->frametype == AST_FRAME_DTMF) &&
2963 ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
2964 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
2965 /* Record received frame and who */
2969 ast_log(LOG_DEBUG, "Oooh, got a %s\n", fr ? "digit" : "hangup");
2970 res = AST_BRIDGE_COMPLETE;
2972 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2973 if ((fr->subclass == AST_CONTROL_HOLD) ||
2974 (fr->subclass == AST_CONTROL_UNHOLD) ||
2975 (fr->subclass == AST_CONTROL_VIDUPDATE)) {
2976 /* If we are going on hold, then break callback mode */
2977 if (fr->subclass == AST_CONTROL_HOLD) {
2979 p0_callback = p2p_callback_disable(c0, p0, &p0_fds[0], &p0_iod[0]);
2981 p1_callback = p2p_callback_disable(c1, p1, &p1_fds[0], &p1_iod[0]);
2982 } else if (fr->subclass == AST_CONTROL_UNHOLD) {
2983 /* If we are off hold, then go back to callback mode */
2984 p0_callback = p2p_callback_enable(c0, p0, &p0_fds[0], &p0_iod[0]);
2985 p1_callback = p2p_callback_enable(c1, p1, &p1_fds[0], &p1_iod[0]);
2987 ast_indicate(other, fr->subclass);
2992 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
2993 res = AST_BRIDGE_COMPLETE;
2997 /* If this is a DTMF, voice, or video frame write it to the other channel */
2998 if ((fr->frametype == AST_FRAME_DTMF) ||
2999 (fr->frametype == AST_FRAME_VOICE) ||
3000 (fr->frametype == AST_FRAME_VIDEO)) {
3001 ast_write(other, fr);
3011 /* If we are totally avoiding the core, then restore our link to it */
3013 p0_callback = p2p_callback_disable(c0, p0, &p0_fds[0], &p0_iod[0]);
3015 p1_callback = p2p_callback_disable(c1, p1, &p1_fds[0], &p1_iod[0]);
3017 /* Break out of the direct bridge */
3021 vp0->bridged = NULL;
3022 vp1->bridged = NULL;
3028 /*! \brief Bridge calls. If possible and allowed, initiate
3029 re-invite so the peers exchange media directly outside
3031 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)
3033 struct ast_rtp *p0 = NULL, *p1 = NULL; /* Audio RTP Channels */
3034 struct ast_rtp *vp0 = NULL, *vp1 = NULL; /* Video RTP channels */
3035 struct ast_rtp_protocol *pr0 = NULL, *pr1 = NULL;
3036 enum ast_rtp_get_result audio_p0_res = AST_RTP_GET_FAILED, video_p0_res = AST_RTP_GET_FAILED;
3037 enum ast_rtp_get_result audio_p1_res = AST_RTP_GET_FAILED, video_p1_res = AST_RTP_GET_FAILED;
3038 enum ast_bridge_result res = AST_BRIDGE_FAILED;
3039 int codec0 = 0, codec1 = 0;
3040 void *pvt0 = NULL, *pvt1 = NULL;
3043 ast_channel_lock(c0);
3044 while(ast_channel_trylock(c1)) {
3045 ast_channel_unlock(c0);
3047 ast_channel_lock(c0);
3050 /* Find channel driver interfaces */
3051 if (!(pr0 = get_proto(c0))) {
3052 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
3053 ast_channel_unlock(c0);
3054 ast_channel_unlock(c1);
3055 return AST_BRIDGE_FAILED;
3057 if (!(pr1 = get_proto(c1))) {
3058 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
3059 ast_channel_unlock(c0);
3060 ast_channel_unlock(c1);
3061 return AST_BRIDGE_FAILED;
3064 /* Get channel specific interface structures */
3065 pvt0 = c0->tech_pvt;
3066 pvt1 = c1->tech_pvt;
3068 /* Get audio and video interface (if native bridge is possible) */
3069 audio_p0_res = pr0->get_rtp_info(c0, &p0);
3070 video_p0_res = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
3071 audio_p1_res = pr1->get_rtp_info(c1, &p1);
3072 video_p1_res = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
3074 /* If we are carrying video, and both sides are not reinviting... then fail the native bridge */
3075 if (video_p0_res != AST_RTP_GET_FAILED && (audio_p0_res != AST_RTP_TRY_NATIVE || video_p0_res != AST_RTP_TRY_NATIVE))
3076 audio_p0_res = AST_RTP_GET_FAILED;
3077 if (video_p1_res != AST_RTP_GET_FAILED && (audio_p1_res != AST_RTP_TRY_NATIVE || video_p1_res != AST_RTP_TRY_NATIVE))
3078 audio_p1_res = AST_RTP_GET_FAILED;
3080 /* Check if a bridge is possible (partial/native) */
3081 if (audio_p0_res == AST_RTP_GET_FAILED || audio_p1_res == AST_RTP_GET_FAILED) {
3082 /* Somebody doesn't want to play... */
3083 ast_channel_unlock(c0);
3084 ast_channel_unlock(c1);
3085 return AST_BRIDGE_FAILED_NOWARN;
3088 /* If we need to feed DTMF frames into the core then only do a partial native bridge */
3089 if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
3090 ast_set_flag(p0, FLAG_P2P_NEED_DTMF);
3091 audio_p0_res = AST_RTP_TRY_PARTIAL;
3094 if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
3095 ast_set_flag(p1, FLAG_P2P_NEED_DTMF);
3096 audio_p1_res = AST_RTP_TRY_PARTIAL;
3099 /* Get codecs from both sides */
3100 codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
3101 codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
3102 if (pr0->get_codec && pr1->get_codec) {
3103 /* Hey, we can't do native bridging if both parties speak different codecs */
3104 if (!(codec0 & codec1)) {
3106 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
3107 ast_channel_unlock(c0);
3108 ast_channel_unlock(c1);
3109 return AST_BRIDGE_FAILED_NOWARN;
3113 /* If either side can only do a partial bridge, then don't try for a true native bridge */
3114 if (audio_p0_res == AST_RTP_TRY_PARTIAL || audio_p1_res == AST_RTP_TRY_PARTIAL) {
3115 if (option_verbose > 2)
3116 ast_verbose(VERBOSE_PREFIX_3 "Packet2Packet bridging %s and %s\n", c0->name, c1->name);
3117 res = bridge_p2p_loop(c0, c1, p0, p1, vp0, vp1, timeoutms, flags, fo, rc, pvt0, pvt1);
3119 if (option_verbose > 2)
3120 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
3121 res = bridge_native_loop(c0, c1, p0, p1, vp0, vp1, pr0, pr1, codec0, codec1, timeoutms, flags, fo, rc, pvt0, pvt1);
3127 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
3130 struct ast_hostent ahp;
3135 return RESULT_SHOWUSAGE;
3137 p = strstr(arg, ":");
3143 hp = ast_gethostbyname(arg, &ahp);
3145 return RESULT_SHOWUSAGE;
3146 rtpdebugaddr.sin_family = AF_INET;
3147 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
3148 rtpdebugaddr.sin_port = htons(port);
3150 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr.sin_addr));
3152 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr.sin_addr), port);
3154 return RESULT_SUCCESS;
3157 static int rtcp_do_debug_ip(int fd, int argc, char *argv[])
3160 struct ast_hostent ahp;
3164 return RESULT_SHOWUSAGE;
3167 p = strstr(arg, ":");
3173 hp = ast_gethostbyname(arg, &ahp);
3175 return RESULT_SHOWUSAGE;
3176 rtcpdebugaddr.sin_family = AF_INET;
3177 memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
3178 rtcpdebugaddr.sin_port = htons(port);
3180 ast_cli(fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
3182 ast_cli(fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
3184 return RESULT_SUCCESS;
3187 static int rtp_do_debug(int fd, int argc, char *argv[])
3191 return RESULT_SHOWUSAGE;
3192 return rtp_do_debug_ip(fd, argc, argv);
3195 memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
3196 ast_cli(fd, "RTP Debugging Enabled\n");
3197 return RESULT_SUCCESS;
3200 static int rtcp_do_debug(int fd, int argc, char *argv[]) {
3203 return RESULT_SHOWUSAGE;
3204 return rtcp_do_debug_ip(fd, argc, argv);
3207 memset(&rtcpdebugaddr,0,sizeof(rtcpdebugaddr));
3208 ast_cli(fd, "RTCP Debugging Enabled\n");
3209 return RESULT_SUCCESS;
3212 static int rtcp_do_stats(int fd, int argc, char *argv[]) {
3214 return RESULT_SHOWUSAGE;
3217 ast_cli(fd, "RTCP Stats Enabled\n");
3218 return RESULT_SUCCESS;
3221 static int rtp_no_debug(int fd, int argc, char *argv[])
3224 return RESULT_SHOWUSAGE;
3226 ast_cli(fd,"RTP Debugging Disabled\n");
3227 return RESULT_SUCCESS;
3230 static int rtcp_no_debug(int fd, int argc, char *argv[])
3233 return RESULT_SHOWUSAGE;
3235 ast_cli(fd,"RTCP Debugging Disabled\n");
3236 return RESULT_SUCCESS;
3239 static int rtcp_no_stats(int fd, int argc, char *argv[])
3242 return RESULT_SHOWUSAGE;
3244 ast_cli(fd,"RTCP Stats Disabled\n");
3245 return RESULT_SUCCESS;
3249 static int stun_do_debug(int fd, int argc, char *argv[])
3252 return RESULT_SHOWUSAGE;
3255 ast_cli(fd, "STUN Debugging Enabled\n");
3256 return RESULT_SUCCESS;
3259 static int stun_no_debug(int fd, int argc, char *argv[])
3262 return RESULT_SHOWUSAGE;
3264 ast_cli(fd,"STUN Debugging Disabled\n");
3265 return RESULT_SUCCESS;
3269 static char debug_usage[] =
3270 "Usage: rtp debug [ip host[:port]]\n"
3271 " Enable dumping of all RTP packets to and from host.\n";
3273 static char no_debug_usage[] =
3274 "Usage: rtp no debug\n"
3275 " Disable all RTP debugging\n";
3277 static char stun_debug_usage[] =
3278 "Usage: stun debug\n"
3279 " Enable STUN (Simple Traversal of UDP through NATs) debugging\n";
3281 static char stun_no_debug_usage[] =
3282 "Usage: stun no debug\n"
3283 " Disable STUN debugging\n";
3286 static struct ast_cli_entry cli_debug_ip =
3287 {{ "rtp", "debug", "ip", NULL } , rtp_do_debug, "Enable RTP debugging on IP", debug_usage };
3289 static struct ast_cli_entry cli_debug =
3290 {{ "rtp", "debug", NULL } , rtp_do_debug, "Enable RTP debugging", debug_usage };
3292 static struct ast_cli_entry cli_no_debug =
3293 {{ "rtp", "no", "debug", NULL } , rtp_no_debug, "Disable RTP debugging", no_debug_usage };
3295 static char rtcp_debug_usage[] =
3296 "Usage: rtp rtcp debug [ip host[:port]]\n"
3297 " Enable dumping of all RTCP packets to and from host.\n";
3299 static char rtcp_no_debug_usage[] =
3300 "Usage: rtp rtcp no debug\n"
3301 " Disable all RTCP debugging\n";
3303 static char rtcp_stats_usage[] =
3304 "Usage: rtp rtcp stats\n"
3305 " Enable dumping of RTCP stats.\n";
3307 static char rtcp_no_stats_usage[] =
3308 "Usage: rtp rtcp no stats\n"
3309 " Disable all RTCP stats\n";
3311 static struct ast_cli_entry cli_debug_ip_rtcp =
3312 {{ "rtp", "rtcp", "debug", "ip", NULL } , rtcp_do_debug, "Enable RTCP debugging on IP", rtcp_debug_usage };
3314 static struct ast_cli_entry cli_debug_rtcp =
3315 {{ "rtp", "rtcp", "debug", NULL } , rtcp_do_debug, "Enable RTCP debugging", rtcp_debug_usage };
3317 static struct ast_cli_entry cli_no_debug_rtcp =
3318 {{ "rtp", "rtcp", "no", "debug", NULL } , rtcp_no_debug, "Disable RTCP debugging", rtcp_no_debug_usage };
3320 static struct ast_cli_entry cli_stats_rtcp =
3321 {{ "rtp", "rtcp", "stats", NULL } , rtcp_do_stats, "Enable RTCP stats", rtcp_stats_usage };
3323 static struct ast_cli_entry cli_no_stats_rtcp =
3324 {{ "rtp", "rtcp", "no", "stats", NULL } , rtcp_no_stats, "Disable RTCP stats", rtcp_no_stats_usage };
3326 static struct ast_cli_entry cli_stun_debug =
3327 {{ "stun", "debug", NULL } , stun_do_debug, "Enable STUN debugging", stun_debug_usage };
3329 static struct ast_cli_entry cli_stun_no_debug =
3330 {{ "stun", "no", "debug", NULL } , stun_no_debug, "Disable STUN debugging", stun_no_debug_usage };
3332 int ast_rtp_reload(void)
3334 struct ast_config *cfg;
3339 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
3340 cfg = ast_config_load("rtp.conf");
3342 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
3344 if (rtpstart < 1024)
3346 if (rtpstart > 65535)
3349 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
3356 if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
3357 rtcpinterval = atoi(s);
3358 if (rtcpinterval == 0)
3359 rtcpinterval = 0; /* Just so we're clear... it's zero */
3360 if (rtcpinterval < RTCP_MIN_INTERVALMS)
3361 rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
3362 if (rtcpinterval > RTCP_MAX_INTERVALMS)
3363 rtcpinterval = RTCP_MAX_INTERVALMS;
3365 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
3373 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
3376 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
3377 dtmftimeout = atoi(s);
3378 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
3379 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
3380 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
3381 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
3384 ast_config_destroy(cfg);
3386 if (rtpstart >= rtpend) {
3387 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
3391 if (option_verbose > 1)
3392 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
3396 /*! \brief Initialize the RTP system in Asterisk */
3397 void ast_rtp_init(void)
3399 ast_cli_register(&cli_debug);
3400 ast_cli_register(&cli_debug_ip);
3401 ast_cli_register(&cli_no_debug);
3403 ast_cli_register(&cli_debug_rtcp);
3404 ast_cli_register(&cli_debug_ip_rtcp);
3405 ast_cli_register(&cli_no_debug_rtcp);
3407 ast_cli_register(&cli_stats_rtcp);
3408 ast_cli_register(&cli_no_stats_rtcp);
3410 ast_cli_register(&cli_stun_debug);
3411 ast_cli_register(&cli_stun_no_debug);