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;
143 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
144 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
145 struct timeval rxcore;
146 struct timeval txcore;
147 double drxcore; /*!< The double representation of the first received packet */
148 struct timeval lastrx; /*!< timeval when we last received a packet */
149 struct timeval dtmfmute;
150 struct ast_smoother *smoother;
152 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
153 unsigned short rxseqno;
154 struct sched_context *sched;
155 struct io_context *io;
157 ast_rtp_callback callback;
158 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
159 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
160 int rtp_lookup_code_cache_code;
161 int rtp_lookup_code_cache_result;
162 struct ast_rtcp *rtcp;
163 struct ast_codec_pref pref;
164 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
167 /* Forward declarations */
168 static int ast_rtcp_write(void *data);
169 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
170 static int ast_rtcp_write_sr(void *data);
171 static int ast_rtcp_write_rr(void *data);
172 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
173 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
174 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
175 static int bridge_p2p_rtcp_write(struct ast_rtp *rtp, unsigned int *rtcpheader, int len);
177 #define FLAG_3389_WARNING (1 << 0)
178 #define FLAG_NAT_ACTIVE (3 << 1)
179 #define FLAG_NAT_INACTIVE (0 << 1)
180 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
181 #define FLAG_HAS_DTMF (1 << 3)
182 #define FLAG_P2P_SENT_MARK (1 << 4)
183 #define FLAG_P2P_NEED_DTMF (1 << 5)
184 #define FLAG_CALLBACK_MODE (1 << 6)
185 #define FLAG_DTMF_COMPENSATE (1 << 7)
188 * \brief Structure defining an RTCP session.
190 * The concept "RTCP session" is not defined in RFC 3550, but since
191 * this structure is analogous to ast_rtp, which tracks a RTP session,
192 * it is logical to think of this as a RTCP session.
194 * RTCP packet is defined on page 9 of RFC 3550.
198 int s; /*!< Socket */
199 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
200 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
201 unsigned int soc; /*!< What they told us */
202 unsigned int spc; /*!< What they told us */
203 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
204 struct timeval rxlsr; /*!< Time when we got their last SR */
205 struct timeval txlsr; /*!< Time when we sent or last SR*/
206 unsigned int expected_prior; /*!< no. packets in previous interval */
207 unsigned int received_prior; /*!< no. packets received in previous interval */
208 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
209 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
210 unsigned int sr_count; /*!< number of SRs we've sent */
211 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
212 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
213 double rtt; /*!< Last reported rtt */
214 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
215 unsigned int reported_lost; /*!< Reported lost packets in their RR */
216 char quality[AST_MAX_USER_FIELD];
225 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
227 /* XXX Maybe stun belongs in another file if it ever has use outside of RTP */
229 unsigned short msgtype;
230 unsigned short msglen;
232 unsigned char ies[0];
233 } __attribute__((packed));
238 unsigned char value[0];
239 } __attribute__((packed));
242 unsigned char unused;
243 unsigned char family;
246 } __attribute__((packed));
248 #define STUN_IGNORE (0)
249 #define STUN_ACCEPT (1)
251 #define STUN_BINDREQ 0x0001
252 #define STUN_BINDRESP 0x0101
253 #define STUN_BINDERR 0x0111
254 #define STUN_SECREQ 0x0002
255 #define STUN_SECRESP 0x0102
256 #define STUN_SECERR 0x0112
258 #define STUN_MAPPED_ADDRESS 0x0001
259 #define STUN_RESPONSE_ADDRESS 0x0002
260 #define STUN_CHANGE_REQUEST 0x0003
261 #define STUN_SOURCE_ADDRESS 0x0004
262 #define STUN_CHANGED_ADDRESS 0x0005
263 #define STUN_USERNAME 0x0006
264 #define STUN_PASSWORD 0x0007
265 #define STUN_MESSAGE_INTEGRITY 0x0008
266 #define STUN_ERROR_CODE 0x0009
267 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
268 #define STUN_REFLECTED_FROM 0x000b
270 static const char *stun_msg2str(int msg)
274 return "Binding Request";
276 return "Binding Response";
278 return "Binding Error Response";
280 return "Shared Secret Request";
282 return "Shared Secret Response";
284 return "Shared Secret Error Response";
286 return "Non-RFC3489 Message";
289 static const char *stun_attr2str(int msg)
292 case STUN_MAPPED_ADDRESS:
293 return "Mapped Address";
294 case STUN_RESPONSE_ADDRESS:
295 return "Response Address";
296 case STUN_CHANGE_REQUEST:
297 return "Change Request";
298 case STUN_SOURCE_ADDRESS:
299 return "Source Address";
300 case STUN_CHANGED_ADDRESS:
301 return "Changed Address";
306 case STUN_MESSAGE_INTEGRITY:
307 return "Message Integrity";
308 case STUN_ERROR_CODE:
310 case STUN_UNKNOWN_ATTRIBUTES:
311 return "Unknown Attributes";
312 case STUN_REFLECTED_FROM:
313 return "Reflected From";
315 return "Non-RFC3489 Attribute";
319 const char *username;
320 const char *password;
323 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
326 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
327 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
328 switch(ntohs(attr->attr)) {
330 state->username = (const char *) (attr->value);
333 state->password = (const char *) (attr->value);
337 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
338 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
343 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
345 int size = sizeof(**attr) + strlen(s);
347 (*attr)->attr = htons(attrval);
348 (*attr)->len = htons(strlen(s));
349 memcpy((*attr)->value, s, strlen(s));
350 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
356 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
358 int size = sizeof(**attr) + 8;
359 struct stun_addr *addr;
361 (*attr)->attr = htons(attrval);
362 (*attr)->len = htons(8);
363 addr = (struct stun_addr *)((*attr)->value);
366 addr->port = sin->sin_port;
367 addr->addr = sin->sin_addr.s_addr;
368 (*attr) = (struct stun_attr *)((*attr)->value + 8);
374 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
376 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
377 (struct sockaddr *)dst, sizeof(*dst));
380 static void stun_req_id(struct stun_header *req)
384 req->id.id[x] = ast_random();
387 size_t ast_rtp_alloc_size(void)
389 return sizeof(struct ast_rtp);
392 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
394 struct stun_header *req;
395 unsigned char reqdata[1024];
397 struct stun_attr *attr;
399 req = (struct stun_header *)reqdata;
402 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
405 attr = (struct stun_attr *)req->ies;
407 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
408 req->msglen = htons(reqlen);
409 req->msgtype = htons(STUN_BINDREQ);
410 stun_send(rtp->s, suggestion, req);
413 static int stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len)
415 struct stun_header *resp, *hdr = (struct stun_header *)data;
416 struct stun_attr *attr;
417 struct stun_state st;
418 int ret = STUN_IGNORE;
419 unsigned char respdata[1024];
420 int resplen, respleft;
422 if (len < sizeof(struct stun_header)) {
424 ast_log(LOG_DEBUG, "Runt STUN packet (only %zd, wanting at least %zd)\n", len, sizeof(struct stun_header));
428 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), ntohs(hdr->msglen));
429 if (ntohs(hdr->msglen) > len - sizeof(struct stun_header)) {
431 ast_log(LOG_DEBUG, "Scrambled STUN packet length (got %d, expecting %zd)\n", ntohs(hdr->msglen), len - sizeof(struct stun_header));
433 len = ntohs(hdr->msglen);
434 data += sizeof(struct stun_header);
435 memset(&st, 0, sizeof(st));
437 if (len < sizeof(struct stun_attr)) {
439 ast_log(LOG_DEBUG, "Runt Attribute (got %zd, expecting %zd)\n", len, sizeof(struct stun_attr));
442 attr = (struct stun_attr *)data;
443 if (ntohs(attr->len) > len) {
445 ast_log(LOG_DEBUG, "Inconsistent Attribute (length %d exceeds remaining msg len %zd)\n", ntohs(attr->len), len);
448 if (stun_process_attr(&st, attr)) {
450 ast_log(LOG_DEBUG, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
453 /* Clear attribute in case previous entry was a string */
455 data += ntohs(attr->len) + sizeof(struct stun_attr);
456 len -= ntohs(attr->len) + sizeof(struct stun_attr);
458 /* Null terminate any string */
460 resp = (struct stun_header *)respdata;
462 respleft = sizeof(respdata) - sizeof(struct stun_header);
466 attr = (struct stun_attr *)resp->ies;
468 switch(ntohs(hdr->msgtype)) {
471 ast_verbose("STUN Bind Request, username: %s\n",
472 st.username ? st.username : "<none>");
474 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
475 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
476 resp->msglen = htons(resplen);
477 resp->msgtype = htons(STUN_BINDRESP);
478 stun_send(s, src, resp);
483 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
489 /*! \brief List of current sessions */
490 static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
492 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
494 unsigned int sec, usec, frac;
495 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
497 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
502 int ast_rtp_fd(struct ast_rtp *rtp)
507 int ast_rtcp_fd(struct ast_rtp *rtp)
514 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
516 unsigned int interval;
517 /*! \todo XXX Do a more reasonable calculation on this one
518 * Look in RFC 3550 Section A.7 for an example*/
519 interval = rtcpinterval;
523 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
528 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
530 rtp->callback = callback;
533 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
538 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
540 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
543 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
545 ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
548 static struct ast_frame *send_dtmf(struct ast_rtp *rtp, enum ast_frame_type type)
550 if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
551 (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
553 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
555 rtp->dtmfduration = 0;
556 return &ast_null_frame;
559 ast_log(LOG_DEBUG, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
560 if (rtp->resp == 'X') {
561 rtp->f.frametype = AST_FRAME_CONTROL;
562 rtp->f.subclass = AST_CONTROL_FLASH;
564 rtp->f.frametype = type;
565 rtp->f.subclass = rtp->resp;
575 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
579 if (rtpdebugaddr.sin_addr.s_addr) {
580 if (((ntohs(rtpdebugaddr.sin_port) != 0)
581 && (rtpdebugaddr.sin_port != addr->sin_port))
582 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
588 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
592 if (rtcpdebugaddr.sin_addr.s_addr) {
593 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
594 && (rtcpdebugaddr.sin_port != addr->sin_port))
595 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
602 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
606 struct ast_frame *f = NULL;
611 /* We should have at least 4 bytes in RTP data */
615 /* The format of Cisco RTP DTMF packet looks like next:
616 +0 - sequence number of DTMF RTP packet (begins from 1,
619 +1 (bit 0) - flaps by different DTMF digits delimited by audio
620 or repeated digit without audio???
621 +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
622 then falls to 0 at its end)
623 +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
624 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
625 by each new packet and thus provides some redudancy.
627 Sample of Cisco RTP DTMF packet is (all data in hex):
628 19 07 00 02 12 02 20 02
629 showing end of DTMF digit '2'.
632 27 07 00 02 0A 02 20 02
633 28 06 20 02 00 02 0A 02
634 shows begin of new digit '2' with very short pause (20 ms) after
635 previous digit '2'. Bit +1.0 flips at begin of new digit.
637 Cisco RTP DTMF packets comes as replacement of audio RTP packets
638 so its uses the same sequencing and timestamping rules as replaced
639 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
640 on audio framing parameters. Marker bit isn't used within stream of
641 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
642 are not sequential at borders between DTMF and audio streams,
648 event = data[3] & 0x1f;
650 if (option_debug > 2 || rtpdebug)
651 ast_log(LOG_DEBUG, "Cisco DTMF Digit: %02x (len=%d, seq=%d, flags=%02x, power=%d, history count=%d)\n", event, len, seq, flags, power, (len - 4) / 2);
654 } else if (event < 11) {
656 } else if (event < 12) {
658 } else if (event < 16) {
659 resp = 'A' + (event - 12);
660 } else if (event < 17) {
663 if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
665 /* Why we should care on DTMF compensation at reception? */
666 if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
667 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
668 rtp->dtmfduration = 0;
670 } else if ((rtp->resp == resp) && !power) {
671 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
672 f->samples = rtp->dtmfduration * 8;
674 } else if (rtp->resp == resp)
675 rtp->dtmfduration += 20 * 8;
676 rtp->dtmfcount = dtmftimeout;
681 * \brief Process RTP DTMF and events according to RFC 2833.
683 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
691 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
694 unsigned int event_end;
695 unsigned int duration;
697 struct ast_frame *f = NULL;
699 /* Figure out event, event end, and duration */
700 event = ntohl(*((unsigned int *)(data)));
702 event_end = ntohl(*((unsigned int *)(data)));
705 duration = ntohl(*((unsigned int *)(data)));
708 /* Print out debug if turned on */
709 if (rtpdebug || option_debug > 2)
710 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
712 /* Figure out what digit was pressed */
715 } else if (event < 11) {
717 } else if (event < 12) {
719 } else if (event < 16) {
720 resp = 'A' + (event - 12);
721 } else if (event < 17) { /* Event 16: Hook flash */
725 if ((!(rtp->resp) && (!(event_end & 0x80))) || (rtp->resp && rtp->resp != resp)) {
727 if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE))
728 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
729 } else if (event_end & 0x80 && rtp->lasteventendseqn != seqno && rtp->resp) {
730 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
731 f->samples = duration;
733 rtp->lasteventendseqn = seqno;
734 } else if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && event_end & 0x80 && rtp->lasteventendseqn != seqno) {
736 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
737 f->samples = duration;
739 rtp->lasteventendseqn = seqno;
742 rtp->dtmfcount = dtmftimeout;
743 rtp->dtmfduration = duration;
749 * \brief Process Comfort Noise RTP.
751 * This is incomplete at the moment.
754 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
756 struct ast_frame *f = NULL;
757 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
758 totally help us out becuase we don't have an engine to keep it going and we are not
759 guaranteed to have it every 20ms or anything */
761 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
763 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
764 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
765 ast_inet_ntoa(rtp->them.sin_addr));
766 ast_set_flag(rtp, FLAG_3389_WARNING);
769 /* Must have at least one byte */
773 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
774 rtp->f.datalen = len - 1;
775 rtp->f.offset = AST_FRIENDLY_OFFSET;
776 memcpy(rtp->f.data, data + 1, len - 1);
782 rtp->f.frametype = AST_FRAME_CNG;
783 rtp->f.subclass = data[0] & 0x7f;
784 rtp->f.datalen = len - 1;
786 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
791 static int rtpread(int *id, int fd, short events, void *cbdata)
793 struct ast_rtp *rtp = cbdata;
795 f = ast_rtp_read(rtp);
798 rtp->callback(rtp, f, rtp->data);
803 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
806 int position, i, packetwords;
808 struct sockaddr_in sin;
809 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
810 unsigned int *rtcpheader;
822 struct ast_frame *f = &ast_null_frame;
824 if (!rtp || !rtp->rtcp)
825 return &ast_null_frame;
829 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
830 0, (struct sockaddr *)&sin, &len);
831 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
835 ast_log(LOG_WARNING, "RTCP Read error: %s\n", strerror(errno));
838 return &ast_null_frame;
841 packetwords = res / 4;
844 /* Send to whoever sent to us */
845 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
846 (rtp->rtcp->them.sin_port != sin.sin_port)) {
847 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
848 if (option_debug || rtpdebug)
849 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));
853 /* If we are P2P bridged to another RTP stream, send it directly over */
854 if (ast_rtp_get_bridged(rtp) && !bridge_p2p_rtcp_write(rtp, rtcpheader, res))
855 return &ast_null_frame;
858 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
860 /* Process a compound packet */
862 while (position < packetwords) {
864 length = ntohl(rtcpheader[i]);
865 pt = (length & 0xff0000) >> 16;
866 rc = (length & 0x1f000000) >> 24;
869 if ((i + length) > packetwords) {
870 ast_log(LOG_WARNING, "RTCP Read too short\n");
871 return &ast_null_frame;
874 if (rtcp_debug_test_addr(&sin)) {
875 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
876 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
877 ast_verbose("Reception reports: %d\n", rc);
878 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
881 i += 2; /* Advance past header and ssrc */
885 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
886 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
887 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
888 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff) >> 16); /* Going to LSR in RR*/
890 if (rtcp_debug_test_addr(&sin)) {
891 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
892 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
893 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
898 /* Intentional fall through */
900 /* This is the place to calculate RTT */
901 /* Don't handle multiple reception reports (rc > 1) yet */
902 gettimeofday(&now, NULL);
903 timeval2ntp(now, &msw, &lsw);
904 /* Use the one we sent them in our SR instead, rtcp->txlsr could have been rewritten if the dlsr is large */
905 if (ntohl(rtcpheader[i + 4])) { /* We must have the LSR */
906 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
907 a = (double)((comp & 0xffff0000) >> 16) + (double)((double)(comp & 0xffff)/1000000.);
908 lsr = (double)((ntohl(rtcpheader[i + 4]) & 0xffff0000) >> 16) + (double)((double)(ntohl(rtcpheader[i + 4]) & 0xffff) / 1000000.);
909 dlsr = (double)(ntohl(rtcpheader[i + 5])/65536.);
910 rtt = a - dlsr - lsr;
911 rtp->rtcp->accumulated_transit += rtt;
912 rtp->rtcp->rtt = rtt;
913 if (rtp->rtcp->maxrtt<rtt)
914 rtp->rtcp->maxrtt = rtt;
915 if (rtp->rtcp->minrtt>rtt)
916 rtp->rtcp->minrtt = rtt;
918 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
919 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
920 if (rtcp_debug_test_addr(&sin)) {
921 ast_verbose("Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
922 ast_verbose("Packets lost so far: %d\n", rtp->rtcp->reported_lost);
923 ast_verbose("Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
924 ast_verbose("Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
925 ast_verbose("Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
926 ast_verbose("Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
927 ast_verbose("DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
929 ast_verbose("RTT: %f(sec)\n", rtt);
933 if (rtcp_debug_test_addr(&sin))
934 ast_verbose("Received an RTCP Fast Update Request\n");
935 rtp->f.frametype = AST_FRAME_CONTROL;
936 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
944 if (rtcp_debug_test_addr(&sin))
945 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
948 if (rtcp_debug_test_addr(&sin))
949 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
952 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));
955 position += (length + 1);
961 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
970 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
971 gettimeofday(&rtp->rxcore, NULL);
972 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
973 /* map timestamp to a real time */
974 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
975 rtp->rxcore.tv_sec -= timestamp / 8000;
976 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
977 /* Round to 0.1ms for nice, pretty timestamps */
978 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
979 if (rtp->rxcore.tv_usec < 0) {
980 /* Adjust appropriately if necessary */
981 rtp->rxcore.tv_usec += 1000000;
982 rtp->rxcore.tv_sec -= 1;
986 gettimeofday(&now,NULL);
987 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
988 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
989 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
990 if (tv->tv_usec >= 1000000) {
991 tv->tv_usec -= 1000000;
994 prog = (double)((timestamp-rtp->seedrxts)/8000.);
995 dtv = (double)rtp->drxcore + (double)(prog);
996 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
997 transit = current_time - dtv;
998 d = transit - rtp->rxtransit;
999 rtp->rxtransit = transit;
1002 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1003 if (rtp->rtcp && rtp->rxjitter > rtp->rtcp->maxrxjitter)
1004 rtp->rtcp->maxrxjitter = rtp->rxjitter;
1005 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1006 rtp->rtcp->minrxjitter = rtp->rxjitter;
1009 /*! \brief Perform a Packet2Packet RTCP write */
1010 static int bridge_p2p_rtcp_write(struct ast_rtp *rtp, unsigned int *rtcpheader, int len)
1012 struct ast_rtp *bridged = ast_rtp_get_bridged(rtp);
1015 /* If RTCP is not present on the bridged RTP session, then ignore this */
1019 /* Send the data out */
1020 res = sendto(bridged->rtcp->s, (void *)rtcpheader, len, 0, (struct sockaddr *)&bridged->rtcp->them, sizeof(bridged->rtcp->them));
1022 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1024 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));
1026 else if ((((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug)) && (option_debug || rtpdebug)) {
1028 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));
1030 } else if (rtp_debug_test_addr(&bridged->rtcp->them)) {
1032 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);
1038 /*! \brief Perform a Packet2Packet RTP write */
1039 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, unsigned int *rtpheader, int len, int hdrlen)
1041 struct ast_rtp *bridged = ast_rtp_get_bridged(rtp);
1042 int res = 0, payload = 0, bridged_payload = 0, version, padding, mark, ext;
1043 struct rtpPayloadType rtpPT;
1046 /* Get fields from packet */
1047 seqno = ntohl(rtpheader[0]);
1048 version = (seqno & 0xC0000000) >> 30;
1049 payload = (seqno & 0x7f0000) >> 16;
1050 padding = seqno & (1 << 29);
1051 mark = seqno & (1 << 23);
1052 ext = seqno & (1 << 28);
1055 /* Check what the payload value should be */
1056 rtpPT = ast_rtp_lookup_pt(rtp, payload);
1058 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
1059 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
1062 /* Otherwise adjust bridged payload to match */
1063 bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
1065 /* If the mark bit has not been sent yet... do it now */
1066 if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
1068 ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
1071 /* Reconstruct part of the packet */
1072 rtpheader[0] = htonl((version << 30) | (mark << 23) | (bridged_payload << 16) | (seqno));
1074 /* Send the packet back out */
1075 res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
1077 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1079 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));
1080 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1081 if (option_debug || rtpdebug)
1082 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));
1083 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1086 } else if (rtp_debug_test_addr(&bridged->them))
1087 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);
1092 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
1095 struct sockaddr_in sin;
1106 unsigned int timestamp;
1107 unsigned int *rtpheader;
1108 struct rtpPayloadType rtpPT;
1110 /* If time is up, kill it */
1111 if (rtp->send_digit)
1112 ast_rtp_senddigit_continuation(rtp);
1116 /* Cache where the header will go */
1117 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
1118 0, (struct sockaddr *)&sin, &len);
1120 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
1122 if (errno != EAGAIN)
1123 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
1126 return &ast_null_frame;
1130 ast_log(LOG_WARNING, "RTP Read too short\n");
1131 return &ast_null_frame;
1135 seqno = ntohl(rtpheader[0]);
1137 /* Check RTP version */
1138 version = (seqno & 0xC0000000) >> 30;
1140 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res) == STUN_ACCEPT) &&
1141 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
1142 memcpy(&rtp->them, &sin, sizeof(rtp->them));
1144 return &ast_null_frame;
1147 #if 0 /* Allow to receive RTP stream with closed transmission path */
1148 /* If we don't have the other side's address, then ignore this */
1149 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1150 return &ast_null_frame;
1153 /* Send to whoever send to us if NAT is turned on */
1155 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1156 (rtp->them.sin_port != sin.sin_port)) {
1159 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1160 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1163 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1164 if (option_debug || rtpdebug)
1165 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));
1169 /* If we are bridged to another RTP stream, send direct */
1170 if (ast_rtp_get_bridged(rtp) && !bridge_p2p_rtp_write(rtp, rtpheader, res, hdrlen))
1171 return &ast_null_frame;
1174 return &ast_null_frame;
1176 payloadtype = (seqno & 0x7f0000) >> 16;
1177 padding = seqno & (1 << 29);
1178 mark = seqno & (1 << 23);
1179 ext = seqno & (1 << 28);
1181 timestamp = ntohl(rtpheader[1]);
1182 ssrc = ntohl(rtpheader[2]);
1184 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1185 if (option_debug || rtpdebug)
1186 ast_log(LOG_DEBUG, "Forcing Marker bit, because SSRC has changed\n");
1193 /* Remove padding bytes */
1194 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1198 /* RTP Extension present */
1200 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
1204 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1205 return &ast_null_frame;
1208 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1210 tseqno = rtp->lastrxseqno +1;
1212 if (rtp->rxcount==1) {
1213 /* This is the first RTP packet successfully received from source */
1214 rtp->seedrxseqno = seqno;
1217 /* Do not schedule RR if RTCP isn't run */
1218 if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
1219 /* Schedule transmission of Receiver Report */
1220 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1223 if (tseqno > RTP_SEQ_MOD) { /* if tseqno is greater than RTP_SEQ_MOD it would indicate that the sender cycled */
1224 rtp->cycles += RTP_SEQ_MOD;
1225 ast_verbose("SEQNO cycled: %u\t%d\n", rtp->cycles, seqno);
1228 rtp->lastrxseqno = seqno;
1230 if (rtp->themssrc==0)
1231 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1233 if (rtp_debug_test_addr(&sin))
1234 ast_verbose("Got RTP packet from %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1235 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1237 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1238 if (!rtpPT.isAstFormat) {
1239 struct ast_frame *f = NULL;
1241 /* This is special in-band data that's not one of our codecs */
1242 if (rtpPT.code == AST_RTP_DTMF) {
1243 /* It's special -- rfc2833 process it */
1244 if (rtp_debug_test_addr(&sin)) {
1245 unsigned char *data;
1247 unsigned int event_end;
1248 unsigned int duration;
1249 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1250 event = ntohl(*((unsigned int *)(data)));
1252 event_end = ntohl(*((unsigned int *)(data)));
1255 duration = ntohl(*((unsigned int *)(data)));
1257 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);
1259 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
1260 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1261 /* It's really special -- process it the Cisco way */
1262 if (rtp->lasteventseqn <= seqno || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
1263 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1264 rtp->lasteventseqn = seqno;
1266 } else if (rtpPT.code == AST_RTP_CN) {
1268 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1270 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1272 return f ? f : &ast_null_frame;
1274 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1275 rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : AST_FRAME_VIDEO;
1278 rtp->lastrxts = timestamp;
1280 rtp->rxseqno = seqno;
1282 /* Record received timestamp as last received now */
1283 rtp->lastrxts = timestamp;
1286 rtp->f.datalen = res - hdrlen;
1287 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1288 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1289 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
1290 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1291 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1292 ast_frame_byteswap_be(&rtp->f);
1293 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1294 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1295 rtp->f.has_timing_info = 1;
1296 rtp->f.ts = timestamp / 8;
1297 rtp->f.len = rtp->f.samples / 8;
1298 rtp->f.seqno = seqno;
1300 /* Video -- samples is # of samples vs. 90000 */
1301 if (!rtp->lastividtimestamp)
1302 rtp->lastividtimestamp = timestamp;
1303 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1304 rtp->lastividtimestamp = timestamp;
1305 rtp->f.delivery.tv_sec = 0;
1306 rtp->f.delivery.tv_usec = 0;
1308 rtp->f.subclass |= 0x1;
1315 /* The following array defines the MIME Media type (and subtype) for each
1316 of our codecs, or RTP-specific data type. */
1318 struct rtpPayloadType payloadType;
1322 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1323 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1324 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1325 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1326 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1327 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1328 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1329 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1330 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1331 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1332 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1333 {{1, AST_FORMAT_G722}, "audio", "G722"},
1334 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
1335 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1336 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1337 {{0, AST_RTP_CN}, "audio", "CN"},
1338 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1339 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1340 {{1, AST_FORMAT_H261}, "video", "H261"},
1341 {{1, AST_FORMAT_H263}, "video", "H263"},
1342 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1343 {{1, AST_FORMAT_H264}, "video", "H264"},
1346 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1347 also, our own choices for dynamic payload types. This is our master
1348 table for transmission */
1349 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1350 [0] = {1, AST_FORMAT_ULAW},
1351 #ifdef USE_DEPRECATED_G726
1352 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1354 [3] = {1, AST_FORMAT_GSM},
1355 [4] = {1, AST_FORMAT_G723_1},
1356 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1357 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1358 [7] = {1, AST_FORMAT_LPC10},
1359 [8] = {1, AST_FORMAT_ALAW},
1360 [9] = {1, AST_FORMAT_G722},
1361 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1362 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1363 [13] = {0, AST_RTP_CN},
1364 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1365 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1366 [18] = {1, AST_FORMAT_G729A},
1367 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1368 [26] = {1, AST_FORMAT_JPEG},
1369 [31] = {1, AST_FORMAT_H261},
1370 [34] = {1, AST_FORMAT_H263},
1371 [103] = {1, AST_FORMAT_H263_PLUS},
1372 [97] = {1, AST_FORMAT_ILBC},
1373 [99] = {1, AST_FORMAT_H264},
1374 [101] = {0, AST_RTP_DTMF},
1375 [110] = {1, AST_FORMAT_SPEEX},
1376 [111] = {1, AST_FORMAT_G726},
1377 [112] = {1, AST_FORMAT_G726_AAL2},
1378 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1381 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1387 for (i = 0; i < MAX_RTP_PT; ++i) {
1388 rtp->current_RTP_PT[i].isAstFormat = 0;
1389 rtp->current_RTP_PT[i].code = 0;
1392 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1393 rtp->rtp_lookup_code_cache_code = 0;
1394 rtp->rtp_lookup_code_cache_result = 0;
1397 void ast_rtp_pt_default(struct ast_rtp* rtp)
1401 /* Initialize to default payload types */
1402 for (i = 0; i < MAX_RTP_PT; ++i) {
1403 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1404 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1407 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1408 rtp->rtp_lookup_code_cache_code = 0;
1409 rtp->rtp_lookup_code_cache_result = 0;
1412 void ast_rtp_pt_copy(struct ast_rtp *dest, const struct ast_rtp *src)
1416 for (i=0; i < MAX_RTP_PT; ++i) {
1417 dest->current_RTP_PT[i].isAstFormat =
1418 src->current_RTP_PT[i].isAstFormat;
1419 dest->current_RTP_PT[i].code =
1420 src->current_RTP_PT[i].code;
1422 dest->rtp_lookup_code_cache_isAstFormat = 0;
1423 dest->rtp_lookup_code_cache_code = 0;
1424 dest->rtp_lookup_code_cache_result = 0;
1427 /*! \brief Get channel driver interface structure */
1428 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1430 struct ast_rtp_protocol *cur = NULL;
1432 AST_LIST_LOCK(&protos);
1433 AST_LIST_TRAVERSE(&protos, cur, list) {
1434 if (cur->type == chan->tech->type)
1437 AST_LIST_UNLOCK(&protos);
1442 int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1444 // dest = c0, src = c1
1445 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1446 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1447 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1448 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED;
1449 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED;
1453 ast_channel_lock(c0);
1455 while(ast_channel_trylock(c1)) {
1456 ast_channel_unlock(c0);
1458 ast_channel_lock(c0);
1462 /* Find channel driver interfaces */
1463 destpr = get_proto(c0);
1465 srcpr = get_proto(c1);
1468 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", c0->name);
1469 ast_channel_unlock(c0);
1471 ast_channel_unlock(c1);
1476 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
1477 ast_channel_unlock(c0);
1479 ast_channel_unlock(c1);
1483 /* Get audio and video interface (if native bridge is possible) */
1484 audio_dest_res = destpr->get_rtp_info(c0, &destp);
1485 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
1487 audio_src_res = srcpr->get_rtp_info(c1, &srcp);
1488 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
1491 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1492 if (audio_dest_res != AST_RTP_TRY_NATIVE) {
1493 /* Somebody doesn't want to play... */
1494 ast_channel_unlock(c0);
1496 ast_channel_unlock(c1);
1499 if (audio_src_res == AST_RTP_TRY_NATIVE && srcpr->get_codec)
1500 srccodec = srcpr->get_codec(c1);
1503 /* Consider empty media as non-existant */
1504 if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
1506 /* Bridge media early */
1507 if (destpr->set_rtp_peer(c0, srcp, vsrcp, srccodec, srcp ? ast_test_flag(srcp, FLAG_NAT_ACTIVE) : 0))
1508 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1509 ast_channel_unlock(c0);
1511 ast_channel_unlock(c1);
1513 ast_log(LOG_DEBUG, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1517 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1519 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1520 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1521 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1522 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED;
1523 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED;
1527 ast_channel_lock(dest);
1528 while(ast_channel_trylock(src)) {
1529 ast_channel_unlock(dest);
1531 ast_channel_lock(dest);
1534 /* Find channel driver interfaces */
1535 if (!(destpr = get_proto(dest))) {
1537 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1538 ast_channel_unlock(dest);
1539 ast_channel_unlock(src);
1542 if (!(srcpr = get_proto(src))) {
1544 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
1545 ast_channel_unlock(dest);
1546 ast_channel_unlock(src);
1550 /* Get audio and video interface (if native bridge is possible) */
1551 audio_dest_res = destpr->get_rtp_info(dest, &destp);
1552 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
1553 audio_src_res = srcpr->get_rtp_info(src, &srcp);
1554 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
1556 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1557 if (audio_dest_res != AST_RTP_TRY_NATIVE || audio_src_res != AST_RTP_TRY_NATIVE) {
1558 /* Somebody doesn't want to play... */
1559 ast_channel_unlock(dest);
1560 ast_channel_unlock(src);
1563 ast_rtp_pt_copy(destp, srcp);
1564 if (vdestp && vsrcp)
1565 ast_rtp_pt_copy(vdestp, vsrcp);
1566 if (srcpr->get_codec)
1567 srccodec = srcpr->get_codec(src);
1572 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1573 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1575 ast_channel_unlock(dest);
1576 ast_channel_unlock(src);
1578 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1582 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1583 * By default, use the well-known value for this type (although it may
1584 * still be set to a different value by a subsequent "a=rtpmap:" line)
1586 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1588 if (pt < 0 || pt > MAX_RTP_PT)
1589 return; /* bogus payload type */
1591 if (static_RTP_PT[pt].code != 0)
1592 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1595 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1596 * an SDP "a=rtpmap:" line.
1598 void ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
1599 char *mimeType, char *mimeSubtype,
1600 enum ast_rtp_options options)
1604 if (pt < 0 || pt > MAX_RTP_PT)
1605 return; /* bogus payload type */
1607 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1608 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1609 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1610 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1611 if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
1612 mimeTypes[i].payloadType.isAstFormat &&
1613 (options & AST_RTP_OPT_G726_NONSTANDARD))
1614 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
1620 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
1621 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1622 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1623 int* astFormats, int* nonAstFormats) {
1626 *astFormats = *nonAstFormats = 0;
1627 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1628 if (rtp->current_RTP_PT[pt].isAstFormat) {
1629 *astFormats |= rtp->current_RTP_PT[pt].code;
1631 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
1636 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
1638 struct rtpPayloadType result;
1640 result.isAstFormat = result.code = 0;
1641 if (pt < 0 || pt > MAX_RTP_PT)
1642 return result; /* bogus payload type */
1644 /* Start with negotiated codecs */
1645 result = rtp->current_RTP_PT[pt];
1647 /* If it doesn't exist, check our static RTP type list, just in case */
1649 result = static_RTP_PT[pt];
1653 /*! \brief Looks up an RTP code out of our *static* outbound list */
1654 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
1658 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
1659 code == rtp->rtp_lookup_code_cache_code) {
1661 /* Use our cached mapping, to avoid the overhead of the loop below */
1662 return rtp->rtp_lookup_code_cache_result;
1665 /* Check the dynamic list first */
1666 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1667 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
1668 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1669 rtp->rtp_lookup_code_cache_code = code;
1670 rtp->rtp_lookup_code_cache_result = pt;
1675 /* Then the static list */
1676 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1677 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
1678 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1679 rtp->rtp_lookup_code_cache_code = code;
1680 rtp->rtp_lookup_code_cache_result = pt;
1687 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
1688 enum ast_rtp_options options)
1692 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1693 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
1695 (code == AST_FORMAT_G726_AAL2) &&
1696 (options & AST_RTP_OPT_G726_NONSTANDARD))
1697 return "AAL2-G726-32";
1699 return mimeTypes[i].subtype;
1706 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
1707 const int isAstFormat, enum ast_rtp_options options)
1717 snprintf(end, size, "0x%x (", capability);
1724 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
1725 if (capability & format) {
1726 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
1728 snprintf(end, size, "%s|", name);
1736 snprintf(start, size, "nothing)");
1743 /*! \brief Open RTP or RTCP socket for a session */
1744 static int rtp_socket(void)
1748 s = socket(AF_INET, SOCK_DGRAM, 0);
1750 flags = fcntl(s, F_GETFL);
1751 fcntl(s, F_SETFL, flags | O_NONBLOCK);
1754 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
1761 * \brief Initialize a new RTCP session.
1763 * \returns The newly initialized RTCP session.
1765 static struct ast_rtcp *ast_rtcp_new(void)
1767 struct ast_rtcp *rtcp;
1769 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
1771 rtcp->s = rtp_socket();
1772 rtcp->us.sin_family = AF_INET;
1773 rtcp->them.sin_family = AF_INET;
1777 ast_log(LOG_WARNING, "Unable to allocate RTCP socket: %s\n", strerror(errno));
1784 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
1786 struct ast_rtp *rtp;
1791 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
1793 rtp->them.sin_family = AF_INET;
1794 rtp->us.sin_family = AF_INET;
1795 rtp->s = rtp_socket();
1796 rtp->ssrc = ast_random();
1797 rtp->seqno = ast_random() & 0xffff;
1798 ast_set_flag(rtp, FLAG_HAS_DTMF);
1801 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1804 if (sched && rtcpenable) {
1806 rtp->rtcp = ast_rtcp_new();
1809 /* Select a random port number in the range of possible RTP */
1810 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
1812 /* Save it for future references. */
1814 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1816 /* Must be an even port number by RTP spec */
1817 rtp->us.sin_port = htons(x);
1818 rtp->us.sin_addr = addr;
1820 /* If there's rtcp, initialize it as well. */
1822 rtp->rtcp->us.sin_port = htons(x + 1);
1823 rtp->rtcp->us.sin_addr = addr;
1825 /* Try to bind it/them. */
1826 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1827 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1830 /* Primary bind succeeded! Gotta recreate it */
1832 rtp->s = rtp_socket();
1834 if (errno != EADDRINUSE) {
1835 /* We got an error that wasn't expected, abort! */
1836 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1839 close(rtp->rtcp->s);
1845 /* The port was used, increment it (by two). */
1847 /* Did we go over the limit ? */
1849 /* then, start from the begingig. */
1850 x = (rtpstart + 1) & ~1;
1851 /* Check if we reached the place were we started. */
1852 if (x == startplace) {
1853 /* If so, there's no ports available. */
1854 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1857 close(rtp->rtcp->s);
1867 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1868 ast_set_flag(rtp, FLAG_CALLBACK_MODE);
1870 ast_rtp_pt_default(rtp);
1874 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1878 memset(&ia, 0, sizeof(ia));
1879 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1882 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1886 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1887 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1891 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1893 rtp->them.sin_port = them->sin_port;
1894 rtp->them.sin_addr = them->sin_addr;
1896 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1897 rtp->rtcp->them.sin_addr = them->sin_addr;
1902 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1904 if ((them->sin_family != AF_INET) ||
1905 (them->sin_port != rtp->them.sin_port) ||
1906 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
1907 them->sin_family = AF_INET;
1908 them->sin_port = rtp->them.sin_port;
1909 them->sin_addr = rtp->them.sin_addr;
1915 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1920 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
1922 return rtp->bridged;
1925 void ast_rtp_stop(struct ast_rtp *rtp)
1927 if (rtp->rtcp && rtp->rtcp->schedid > 0) {
1928 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1929 rtp->rtcp->schedid = -1;
1932 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1933 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1935 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
1936 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
1939 ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
1942 void ast_rtp_reset(struct ast_rtp *rtp)
1944 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1945 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1946 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1948 rtp->lastdigitts = 0;
1950 rtp->lastividtimestamp = 0;
1951 rtp->lastovidtimestamp = 0;
1952 rtp->lasteventseqn = 0;
1953 rtp->lasteventendseqn = 0;
1954 rtp->lasttxformat = 0;
1955 rtp->lastrxformat = 0;
1957 rtp->dtmfduration = 0;
1962 char *ast_rtp_get_quality(struct ast_rtp *rtp)
1966 *themssrc their ssrc
1968 *rxjitter our calculated jitter(rx)
1969 *rxcount no. received packets
1970 *txjitter reported jitter of the other end
1971 *txcount transmitted packets
1972 *rlp remote lost packets
1975 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);
1977 return rtp->rtcp->quality;
1980 void ast_rtp_destroy(struct ast_rtp *rtp)
1982 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
1983 /*Print some info on the call here */
1984 ast_verbose(" RTP-stats\n");
1985 ast_verbose("* Our Receiver:\n");
1986 ast_verbose(" SSRC: %u\n", rtp->themssrc);
1987 ast_verbose(" Received packets: %u\n", rtp->rxcount);
1988 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
1989 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
1990 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
1991 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
1992 ast_verbose("* Our Sender:\n");
1993 ast_verbose(" SSRC: %u\n", rtp->ssrc);
1994 ast_verbose(" Sent packets: %u\n", rtp->txcount);
1995 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
1996 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter);
1997 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
1998 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
2002 ast_smoother_free(rtp->smoother);
2004 ast_io_remove(rtp->io, rtp->ioid);
2008 if (rtp->rtcp->schedid > 0)
2009 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2010 close(rtp->rtcp->s);
2017 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2021 if (ast_tvzero(rtp->txcore)) {
2022 rtp->txcore = ast_tvnow();
2023 /* Round to 20ms for nice, pretty timestamps */
2024 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2026 /* Use previous txcore if available */
2027 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2028 ms = ast_tvdiff_ms(t, rtp->txcore);
2031 /* Use what we just got for next time */
2033 return (unsigned int) ms;
2036 /*! \brief Send begin frames for DTMF */
2037 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
2039 unsigned int *rtpheader;
2040 int hdrlen = 12, res = 0, i = 0, payload = 0;
2043 if ((digit <= '9') && (digit >= '0'))
2045 else if (digit == '*')
2047 else if (digit == '#')
2049 else if ((digit >= 'A') && (digit <= 'D'))
2050 digit = digit - 'A' + 12;
2051 else if ((digit >= 'a') && (digit <= 'd'))
2052 digit = digit - 'a' + 12;
2054 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2058 /* If we have no peer, return immediately */
2059 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2062 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
2064 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2065 rtp->send_duration = 160;
2067 /* Get a pointer to the header */
2068 rtpheader = (unsigned int *)data;
2069 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2070 rtpheader[1] = htonl(rtp->lastdigitts);
2071 rtpheader[2] = htonl(rtp->ssrc);
2073 for (i = 0; i < 2; i++) {
2074 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2075 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2077 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2078 ast_inet_ntoa(rtp->them.sin_addr),
2079 ntohs(rtp->them.sin_port), strerror(errno));
2080 if (rtp_debug_test_addr(&rtp->them))
2081 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2082 ast_inet_ntoa(rtp->them.sin_addr),
2083 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2084 /* Increment sequence number */
2086 /* Increment duration */
2087 rtp->send_duration += 160;
2088 /* Clear marker bit and set seqno */
2089 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2092 /* Since we received a begin, we can safely store the digit and disable any compensation */
2093 rtp->send_digit = digit;
2094 rtp->send_payload = payload;
2099 /*! \brief Send continuation frame for DTMF */
2100 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
2102 unsigned int *rtpheader;
2103 int hdrlen = 12, res = 0;
2106 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2109 /* Setup packet to send */
2110 rtpheader = (unsigned int *)data;
2111 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2112 rtpheader[1] = htonl(rtp->lastdigitts);
2113 rtpheader[2] = htonl(rtp->ssrc);
2114 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2115 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2118 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2120 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2121 ast_inet_ntoa(rtp->them.sin_addr),
2122 ntohs(rtp->them.sin_port), strerror(errno));
2123 if (rtp_debug_test_addr(&rtp->them))
2124 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2125 ast_inet_ntoa(rtp->them.sin_addr),
2126 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2128 /* Increment sequence number */
2130 /* Increment duration */
2131 rtp->send_duration += 160;
2136 /*! \brief Send end packets for DTMF */
2137 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
2139 unsigned int *rtpheader;
2140 int hdrlen = 12, res = 0, i = 0;
2143 /* If no address, then bail out */
2144 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2147 if ((digit <= '9') && (digit >= '0'))
2149 else if (digit == '*')
2151 else if (digit == '#')
2153 else if ((digit >= 'A') && (digit <= 'D'))
2154 digit = digit - 'A' + 12;
2155 else if ((digit >= 'a') && (digit <= 'd'))
2156 digit = digit - 'a' + 12;
2158 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2162 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2164 rtpheader = (unsigned int *)data;
2165 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2166 rtpheader[1] = htonl(rtp->lastdigitts);
2167 rtpheader[2] = htonl(rtp->ssrc);
2168 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2170 rtpheader[3] |= htonl((1 << 23));
2171 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2172 /* Send 3 termination packets */
2173 for (i = 0; i < 3; i++) {
2174 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2176 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2177 ast_inet_ntoa(rtp->them.sin_addr),
2178 ntohs(rtp->them.sin_port), strerror(errno));
2179 if (rtp_debug_test_addr(&rtp->them))
2180 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2181 ast_inet_ntoa(rtp->them.sin_addr),
2182 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2184 rtp->send_digit = 0;
2185 /* Increment lastdigitts */
2186 rtp->lastdigitts += 960;
2192 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
2193 int ast_rtcp_send_h261fur(void *data)
2195 struct ast_rtp *rtp = data;
2198 rtp->rtcp->sendfur = 1;
2199 res = ast_rtcp_write(data);
2204 /*! \brief Send RTCP sender's report */
2205 static int ast_rtcp_write_sr(void *data)
2207 struct ast_rtp *rtp = data;
2211 unsigned int now_lsw;
2212 unsigned int now_msw;
2213 unsigned int *rtcpheader;
2215 unsigned int extended;
2216 unsigned int expected;
2217 unsigned int expected_interval;
2218 unsigned int received_interval;
2221 struct timeval dlsr;
2224 /* Commented condition is always not NULL if rtp->rtcp is not NULL */
2225 if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
2228 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
2229 ast_verbose("RTCP SR transmission error, rtcp halted\n");
2230 if (rtp->rtcp->schedid > 0)
2231 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2232 rtp->rtcp->schedid = -1;
2236 gettimeofday(&now, NULL);
2237 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
2238 rtcpheader = (unsigned int *)bdata;
2239 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
2240 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
2241 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
2242 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
2243 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
2244 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
2247 extended = rtp->cycles + rtp->lastrxseqno;
2248 expected = extended - rtp->seedrxseqno + 1;
2249 if (rtp->rxcount > expected)
2250 expected += rtp->rxcount - expected;
2251 lost = expected - rtp->rxcount;
2252 expected_interval = expected - rtp->rtcp->expected_prior;
2253 rtp->rtcp->expected_prior = expected;
2254 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2255 rtp->rtcp->received_prior = rtp->rxcount;
2256 lost_interval = expected_interval - received_interval;
2257 if (expected_interval == 0 || lost_interval <= 0)
2260 fraction = (lost_interval << 8) / expected_interval;
2261 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2262 rtcpheader[7] = htonl(rtp->themssrc);
2263 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2264 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2265 rtcpheader[10] = htonl((unsigned int)rtp->rxjitter);
2266 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2267 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2270 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2272 if (rtp->rtcp->sendfur) {
2273 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2274 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
2276 rtp->rtcp->sendfur = 0;
2279 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2280 /* it can change mid call, and SDES can't) */
2281 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2282 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2283 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2286 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2288 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));
2289 if (rtp->rtcp->schedid > 0)
2290 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2291 rtp->rtcp->schedid = -1;
2295 /* FIXME Don't need to get a new one */
2296 gettimeofday(&rtp->rtcp->txlsr, NULL);
2297 rtp->rtcp->sr_count++;
2299 rtp->rtcp->lastsrtxcount = rtp->txcount;
2301 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2302 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2303 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
2304 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2305 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
2306 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2307 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
2308 ast_verbose(" Report block:\n");
2309 ast_verbose(" Fraction lost: %u\n", fraction);
2310 ast_verbose(" Cumulative loss: %u\n", lost);
2311 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
2312 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
2313 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2318 /*! \brief Send RTCP recipient's report */
2319 static int ast_rtcp_write_rr(void *data)
2321 struct ast_rtp *rtp = data;
2325 unsigned int extended;
2326 unsigned int expected;
2327 unsigned int expected_interval;
2328 unsigned int received_interval;
2331 unsigned int *rtcpheader;
2333 struct timeval dlsr;
2336 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2339 if (!rtp->rtcp->them.sin_addr.s_addr) {
2340 ast_log(LOG_ERROR, "RTCP RR transmission error to, rtcp halted %s\n",strerror(errno));
2341 if (rtp->rtcp->schedid > 0)
2342 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2343 rtp->rtcp->schedid = -1;
2347 extended = rtp->cycles + rtp->lastrxseqno;
2348 expected = extended - rtp->seedrxseqno + 1;
2349 lost = expected - rtp->rxcount;
2350 expected_interval = expected - rtp->rtcp->expected_prior;
2351 rtp->rtcp->expected_prior = expected;
2352 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2353 rtp->rtcp->received_prior = rtp->rxcount;
2354 lost_interval = expected_interval - received_interval;
2355 if (expected_interval == 0 || lost_interval <= 0)
2358 fraction = (lost_interval << 8) / expected_interval;
2359 gettimeofday(&now, NULL);
2360 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2361 rtcpheader = (unsigned int *)bdata;
2362 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2363 rtcpheader[1] = htonl(rtp->ssrc);
2364 rtcpheader[2] = htonl(rtp->themssrc);
2365 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2366 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2367 rtcpheader[5] = htonl((unsigned int)rtp->rxjitter);
2368 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2369 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2371 if (rtp->rtcp->sendfur) {
2372 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2373 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
2375 rtp->rtcp->sendfur = 0;
2378 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2379 it can change mid call, and SDES can't) */
2380 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2381 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2382 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2385 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2388 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2389 /* Remove the scheduler */
2390 if (rtp->rtcp->schedid > 0)
2391 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2392 rtp->rtcp->schedid = -1;
2396 rtp->rtcp->rr_count++;
2398 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2399 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2400 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2401 " IA jitter: %.4f\n"
2402 " Their last SR: %u\n"
2403 " DLSR: %4.4f (sec)\n\n",
2404 ast_inet_ntoa(rtp->rtcp->them.sin_addr),
2405 ntohs(rtp->rtcp->them.sin_port),
2406 rtp->ssrc, rtp->themssrc, fraction, lost,
2408 rtp->rtcp->themrxlsr,
2409 (double)(ntohl(rtcpheader[7])/65536.0));
2415 /*! \brief Write and RTCP packet to the far end
2416 * \note Decide if we are going to send an SR (with Reception Block) or RR
2417 * RR is sent if we have not sent any rtp packets in the previous interval */
2418 static int ast_rtcp_write(void *data)
2420 struct ast_rtp *rtp = data;
2423 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2424 res = ast_rtcp_write_sr(data);
2426 res = ast_rtcp_write_rr(data);
2431 /*! \brief generate comfort noice (CNG) */
2432 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2434 unsigned int *rtpheader;
2439 level = 127 - (level & 0x7f);
2440 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2442 /* If we have no peer, return immediately */
2443 if (!rtp->them.sin_addr.s_addr)
2446 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2448 /* Get a pointer to the header */
2449 rtpheader = (unsigned int *)data;
2450 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2451 rtpheader[1] = htonl(rtp->lastts);
2452 rtpheader[2] = htonl(rtp->ssrc);
2454 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2455 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2457 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));
2458 if (rtp_debug_test_addr(&rtp->them))
2459 ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %u, len %d)\n"
2460 , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
2466 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2468 unsigned char *rtpheader;
2475 ms = calc_txstamp(rtp, &f->delivery);
2476 /* Default prediction */
2477 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
2478 pred = rtp->lastts + f->samples;
2480 /* Re-calculate last TS */
2481 rtp->lastts = rtp->lastts + ms * 8;
2482 if (ast_tvzero(f->delivery)) {
2483 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
2484 and if so, go with our prediction */
2485 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
2488 if (option_debug > 2)
2489 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2494 mark = f->subclass & 0x1;
2495 pred = rtp->lastovidtimestamp + f->samples;
2496 /* Re-calculate last TS */
2497 rtp->lastts = rtp->lastts + ms * 90;
2498 /* If it's close to our prediction, go for it */
2499 if (ast_tvzero(f->delivery)) {
2500 if (abs(rtp->lastts - pred) < 7200) {
2502 rtp->lastovidtimestamp += f->samples;
2504 if (option_debug > 2)
2505 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);
2506 rtp->lastovidtimestamp = rtp->lastts;
2510 /* If the timestamp for non-digit packets has moved beyond the timestamp
2511 for digits, update the digit timestamp.
2513 if (rtp->lastts > rtp->lastdigitts)
2514 rtp->lastdigitts = rtp->lastts;
2516 if (f->has_timing_info)
2517 rtp->lastts = f->ts * 8;
2519 /* Get a pointer to the header */
2520 rtpheader = (unsigned char *)(f->data - hdrlen);
2522 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
2523 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
2524 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
2526 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2527 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2529 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
2531 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));
2532 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
2533 /* Only give this error message once if we are not RTP debugging */
2534 if (option_debug || rtpdebug)
2535 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));
2536 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
2540 rtp->txoctetcount +=(res - hdrlen);
2542 if (rtp->rtcp && rtp->rtcp->schedid < 1)
2543 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
2546 if (rtp_debug_test_addr(&rtp->them))
2547 ast_verbose("Sent RTP packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2548 ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
2556 int ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
2559 for (x = 0; x < 32; x++) { /* Ugly way */
2560 rtp->pref.order[x] = prefs->order[x];
2561 rtp->pref.framing[x] = prefs->framing[x];
2564 ast_smoother_free(rtp->smoother);
2565 rtp->smoother = NULL;
2569 struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
2574 int ast_rtp_codec_getformat(int pt)
2576 if (pt < 0 || pt > MAX_RTP_PT)
2577 return 0; /* bogus payload type */
2579 if (static_RTP_PT[pt].isAstFormat)
2580 return static_RTP_PT[pt].code;
2585 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
2587 struct ast_frame *f;
2593 /* If we have no peer, return immediately */
2594 if (!rtp->them.sin_addr.s_addr)
2597 /* If there is no data length, return immediately */
2601 /* Make sure we have enough space for RTP header */
2602 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
2603 ast_log(LOG_WARNING, "RTP can only send voice and video\n");
2607 subclass = _f->subclass;
2608 if (_f->frametype == AST_FRAME_VIDEO)
2611 codec = ast_rtp_lookup_code(rtp, 1, subclass);
2613 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
2617 if (rtp->lasttxformat != subclass) {
2618 /* New format, reset the smoother */
2620 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
2621 rtp->lasttxformat = subclass;
2623 ast_smoother_free(rtp->smoother);
2624 rtp->smoother = NULL;
2627 if (!rtp->smoother) {
2628 struct ast_format_list fmt = ast_codec_pref_getsize(&rtp->pref, subclass);
2629 if (fmt.inc_ms) { /* if codec parameters is set / avoid division by zero */
2630 if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
2631 ast_log(LOG_WARNING, "Unable to create smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
2635 ast_smoother_set_flags(rtp->smoother, fmt.flags);
2637 ast_log(LOG_DEBUG, "Created smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
2640 if (rtp->smoother) {
2641 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
2642 ast_smoother_feed_be(rtp->smoother, _f);
2644 ast_smoother_feed(rtp->smoother, _f);
2647 while((f = ast_smoother_read(rtp->smoother)))
2648 ast_rtp_raw_write(rtp, f, codec);
2650 /* Don't buffer outgoing frames; send them one-per-packet: */
2651 if (_f->offset < hdrlen) {
2656 ast_rtp_raw_write(rtp, f, codec);
2662 /*! \brief Unregister interface to channel driver */
2663 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
2665 AST_LIST_LOCK(&protos);
2666 AST_LIST_REMOVE(&protos, proto, list);
2667 AST_LIST_UNLOCK(&protos);
2670 /*! \brief Register interface to channel driver */
2671 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
2673 struct ast_rtp_protocol *cur;
2675 AST_LIST_LOCK(&protos);
2676 AST_LIST_TRAVERSE(&protos, cur, list) {
2677 if (!strcmp(cur->type, proto->type)) {
2678 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
2679 AST_LIST_UNLOCK(&protos);
2683 AST_LIST_INSERT_HEAD(&protos, proto, list);
2684 AST_LIST_UNLOCK(&protos);
2689 /*! \brief Bridge loop for true native bridge (reinvite) */
2690 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)
2692 struct ast_frame *fr = NULL;
2693 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
2694 int oldcodec0 = codec0, oldcodec1 = codec1;
2695 struct sockaddr_in ac1 = {0,}, vac1 = {0,}, ac0 = {0,}, vac0 = {0,};
2696 struct sockaddr_in t1 = {0,}, vt1 = {0,}, t0 = {0,}, vt0 = {0,};
2698 /* Set it up so audio goes directly between the two endpoints */
2700 /* Test the first channel */
2701 if (!(pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))) {
2702 ast_rtp_get_peer(p1, &ac1);
2704 ast_rtp_get_peer(vp1, &vac1);
2706 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
2708 /* Test the second channel */
2709 if (!(pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))) {
2710 ast_rtp_get_peer(p0, &ac0);
2712 ast_rtp_get_peer(vp0, &vac0);
2714 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c1->name, c0->name);
2716 /* Now we can unlock and move into our loop */
2717 ast_channel_unlock(c0);
2718 ast_channel_unlock(c1);
2720 /* Throw our channels into the structure and enter the loop */
2725 /* Check if anything changed */
2726 if ((c0->tech_pvt != pvt0) ||
2727 (c1->tech_pvt != pvt1) ||
2728 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
2730 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
2731 if (c0->tech_pvt == pvt0)
2732 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2733 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2734 if (c1->tech_pvt == pvt1)
2735 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2736 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2737 return AST_BRIDGE_RETRY;
2740 /* Check if they have changed their address */
2741 ast_rtp_get_peer(p1, &t1);
2743 ast_rtp_get_peer(vp1, &vt1);
2745 codec1 = pr1->get_codec(c1);
2746 ast_rtp_get_peer(p0, &t0);
2748 ast_rtp_get_peer(vp0, &vt0);
2750 codec0 = pr0->get_codec(c0);
2751 if ((inaddrcmp(&t1, &ac1)) ||
2752 (vp1 && inaddrcmp(&vt1, &vac1)) ||
2753 (codec1 != oldcodec1)) {
2754 if (option_debug > 1) {
2755 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2756 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
2757 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
2758 c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
2759 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2760 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
2761 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2762 c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
2764 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)))
2765 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
2766 memcpy(&ac1, &t1, sizeof(ac1));
2767 memcpy(&vac1, &vt1, sizeof(vac1));
2770 if ((inaddrcmp(&t0, &ac0)) ||
2771 (vp0 && inaddrcmp(&vt0, &vac0))) {
2772 if (option_debug > 1) {
2773 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2774 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
2775 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2776 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
2778 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)))
2779 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
2780 memcpy(&ac0, &t0, sizeof(ac0));
2781 memcpy(&vac0, &vt0, sizeof(vac0));
2785 /* Wait for frame to come in on the channels */
2786 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
2788 return AST_BRIDGE_RETRY;
2790 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2791 if (ast_check_hangup(c0) || ast_check_hangup(c1))
2796 other = (who == c0) ? c1 : c0;
2797 if (!fr || ((fr->frametype == AST_FRAME_DTMF) &&
2798 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
2799 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
2800 /* Break out of bridge */
2804 ast_log(LOG_DEBUG, "Oooh, got a %s\n", fr ? "digit" : "hangup");
2805 if (c0->tech_pvt == pvt0)
2806 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2807 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2808 if (c1->tech_pvt == pvt1)
2809 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2810 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2811 return AST_BRIDGE_COMPLETE;
2812 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2813 if ((fr->subclass == AST_CONTROL_HOLD) ||
2814 (fr->subclass == AST_CONTROL_UNHOLD) ||
2815 (fr->subclass == AST_CONTROL_VIDUPDATE)) {
2816 ast_indicate(other, fr->subclass);
2822 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
2823 return AST_BRIDGE_COMPLETE;
2826 if ((fr->frametype == AST_FRAME_DTMF) ||
2827 (fr->frametype == AST_FRAME_VOICE) ||
2828 (fr->frametype == AST_FRAME_VIDEO)) {
2829 ast_write(other, fr);
2839 return AST_BRIDGE_FAILED;
2842 /*! \brief P2P RTP/RTCP Callback */
2843 static int p2p_rtp_callback(int *id, int fd, short events, void *cbdata)
2845 int res = 0, hdrlen = 12;
2846 struct sockaddr_in sin;
2848 unsigned int *header;
2849 struct ast_rtp *rtp = cbdata;
2850 int is_rtp = 0, is_rtcp = 0;
2856 if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
2859 header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
2861 /* Determine what this file descriptor is for */
2864 else if (rtp->rtcp && rtp->rtcp->s == fd)
2867 /* If NAT support is turned on, then see if we need to change their address */
2869 /* If this is for RTP, check that - if it's for RTCP, check that */
2871 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
2872 (rtp->them.sin_port != sin.sin_port)) {
2875 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
2876 if (option_debug || rtpdebug)
2877 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));
2879 } else if (is_rtcp) {
2880 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
2881 (rtp->rtcp->them.sin_port != sin.sin_port)) {
2882 rtp->rtcp->them = sin;
2883 if (option_debug || rtpdebug)
2884 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));
2889 /* If this came from the RTP stream, write out via RTP - if it's RTCP, write out via RTCP */
2890 if (ast_rtp_get_bridged(rtp)) {
2892 bridge_p2p_rtp_write(rtp, header, res, hdrlen);
2894 bridge_p2p_rtcp_write(rtp, header, res);
2900 /*! \brief Helper function to switch a channel and RTP stream into callback mode */
2901 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int *fds, int **iod)
2903 /* If we need DTMF or we have no IO structure, then we can't do direct callback */
2904 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) || !rtp->io)
2907 /* If the RTP structure is already in callback mode, remove it temporarily */
2909 ast_io_remove(rtp->io, rtp->ioid);
2913 /* Steal the file descriptors from the channel and stash them away */
2914 fds[0] = chan->fds[0];
2915 fds[1] = chan->fds[1];
2919 /* Now, fire up callback mode */
2920 iod[0] = ast_io_add(rtp->io, fds[0], p2p_rtp_callback, AST_IO_IN, rtp);
2922 iod[1] = ast_io_add(rtp->io, fds[1], p2p_rtp_callback, AST_IO_IN, rtp);
2927 /*! \brief Helper function to switch a channel and RTP stream out of callback mode */
2928 static int p2p_callback_disable(struct ast_channel *chan, struct ast_rtp *rtp, int *fds, int **iod)
2930 ast_channel_lock(chan);
2931 /* Remove the callback from the IO context */
2932 ast_io_remove(rtp->io, iod[0]);
2933 ast_io_remove(rtp->io, iod[1]);
2934 /* Restore file descriptors */
2935 chan->fds[0] = fds[0];
2936 chan->fds[1] = fds[1];
2937 ast_channel_unlock(chan);
2938 /* Restore callback mode if previously used */
2939 if (ast_test_flag(rtp, FLAG_CALLBACK_MODE))
2940 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
2944 /*! \brief Bridge loop for partial native bridge (packet2packet) */
2945 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)
2947 struct ast_frame *fr = NULL;
2948 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
2949 int p0_fds[2] = {-1, -1}, p1_fds[2] = {-1, -1};
2950 int *p0_iod[2] = {NULL, }, *p1_iod[2] = {NULL, };
2951 int p0_callback = 0, p1_callback = 0;
2952 enum ast_bridge_result res = AST_BRIDGE_FAILED;
2954 /* Okay, setup each RTP structure to do P2P forwarding */
2955 ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
2957 ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
2960 ast_clear_flag(vp0, FLAG_P2P_SENT_MARK);
2962 ast_clear_flag(vp1, FLAG_P2P_SENT_MARK);
2966 /* Activate callback modes if possible */
2967 p0_callback = p2p_callback_enable(c0, p0, &p0_fds[0], &p0_iod[0]);
2968 p1_callback = p2p_callback_enable(c1, p1, &p1_fds[0], &p1_iod[0]);
2970 /* Now let go of the channel locks and be on our way */
2971 ast_channel_unlock(c0);
2972 ast_channel_unlock(c1);
2974 /* Go into a loop forwarding frames until we don't need to anymore */
2979 /* Check if anything changed */
2980 if ((c0->tech_pvt != pvt0) ||
2981 (c1->tech_pvt != pvt1) ||
2982 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
2984 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
2985 res = AST_BRIDGE_RETRY;
2988 /* Wait on a channel to feed us a frame */
2989 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
2991 res = AST_BRIDGE_RETRY;
2995 ast_log(LOG_NOTICE, "Ooh, empty read...\n");
2996 if (ast_check_hangup(c0) || ast_check_hangup(c1))
3000 /* Read in frame from channel */
3002 other = (who == c0) ? c1 : c0;
3003 /* Dependong on the frame we may need to break out of our bridge */
3004 if (!fr || ((fr->frametype == AST_FRAME_DTMF) &&
3005 ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
3006 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
3007 /* Record received frame and who */
3011 ast_log(LOG_DEBUG, "Oooh, got a %s\n", fr ? "digit" : "hangup");
3012 res = AST_BRIDGE_COMPLETE;
3014 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3015 if ((fr->subclass == AST_CONTROL_HOLD) ||
3016 (fr->subclass == AST_CONTROL_UNHOLD) ||
3017 (fr->subclass == AST_CONTROL_VIDUPDATE)) {
3018 /* If we are going on hold, then break callback mode and P2P bridging */
3019 if (fr->subclass == AST_CONTROL_HOLD) {
3021 p0_callback = p2p_callback_disable(c0, p0, &p0_fds[0], &p0_iod[0]);
3023 p1_callback = p2p_callback_disable(c1, p1, &p1_fds[0], &p1_iod[0]);
3027 vp0->bridged = NULL;
3028 vp1->bridged = NULL;
3030 } else if (fr->subclass == AST_CONTROL_UNHOLD) {
3031 /* If we are off hold, then go back to callback mode and P2P bridging */
3032 ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
3034 ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
3037 ast_clear_flag(vp0, FLAG_P2P_SENT_MARK);
3039 ast_clear_flag(vp1, FLAG_P2P_SENT_MARK);
3042 p0_callback = p2p_callback_enable(c0, p0, &p0_fds[0], &p0_iod[0]);
3043 p1_callback = p2p_callback_enable(c1, p1, &p1_fds[0], &p1_iod[0]);
3045 ast_indicate(other, fr->subclass);
3051 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
3052 res = AST_BRIDGE_COMPLETE;
3056 /* If this is a DTMF, voice, or video frame write it to the other channel */
3057 if ((fr->frametype == AST_FRAME_DTMF) ||
3058 (fr->frametype == AST_FRAME_VOICE) ||
3059 (fr->frametype == AST_FRAME_VIDEO)) {
3060 ast_write(other, fr);
3070 /* If we are totally avoiding the core, then restore our link to it */
3072 p0_callback = p2p_callback_disable(c0, p0, &p0_fds[0], &p0_iod[0]);
3074 p1_callback = p2p_callback_disable(c1, p1, &p1_fds[0], &p1_iod[0]);
3076 /* Break out of the direct bridge */
3080 vp0->bridged = NULL;
3081 vp1->bridged = NULL;
3087 /*! \brief Bridge calls. If possible and allowed, initiate
3088 re-invite so the peers exchange media directly outside
3090 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)
3092 struct ast_rtp *p0 = NULL, *p1 = NULL; /* Audio RTP Channels */
3093 struct ast_rtp *vp0 = NULL, *vp1 = NULL; /* Video RTP channels */
3094 struct ast_rtp_protocol *pr0 = NULL, *pr1 = NULL;
3095 enum ast_rtp_get_result audio_p0_res = AST_RTP_GET_FAILED, video_p0_res = AST_RTP_GET_FAILED;
3096 enum ast_rtp_get_result audio_p1_res = AST_RTP_GET_FAILED, video_p1_res = AST_RTP_GET_FAILED;
3097 enum ast_bridge_result res = AST_BRIDGE_FAILED;
3098 int codec0 = 0, codec1 = 0;
3099 void *pvt0 = NULL, *pvt1 = NULL;
3102 ast_channel_lock(c0);
3103 while(ast_channel_trylock(c1)) {
3104 ast_channel_unlock(c0);
3106 ast_channel_lock(c0);
3109 /* Find channel driver interfaces */
3110 if (!(pr0 = get_proto(c0))) {
3111 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
3112 ast_channel_unlock(c0);
3113 ast_channel_unlock(c1);
3114 return AST_BRIDGE_FAILED;
3116 if (!(pr1 = get_proto(c1))) {
3117 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
3118 ast_channel_unlock(c0);
3119 ast_channel_unlock(c1);
3120 return AST_BRIDGE_FAILED;
3123 /* Get channel specific interface structures */
3124 pvt0 = c0->tech_pvt;
3125 pvt1 = c1->tech_pvt;
3127 /* Get audio and video interface (if native bridge is possible) */
3128 audio_p0_res = pr0->get_rtp_info(c0, &p0);
3129 video_p0_res = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
3130 audio_p1_res = pr1->get_rtp_info(c1, &p1);
3131 video_p1_res = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
3133 /* If we are carrying video, and both sides are not reinviting... then fail the native bridge */
3134 if (video_p0_res != AST_RTP_GET_FAILED && (audio_p0_res != AST_RTP_TRY_NATIVE || video_p0_res != AST_RTP_TRY_NATIVE))
3135 audio_p0_res = AST_RTP_GET_FAILED;
3136 if (video_p1_res != AST_RTP_GET_FAILED && (audio_p1_res != AST_RTP_TRY_NATIVE || video_p1_res != AST_RTP_TRY_NATIVE))
3137 audio_p1_res = AST_RTP_GET_FAILED;
3139 /* Check if a bridge is possible (partial/native) */
3140 if (audio_p0_res == AST_RTP_GET_FAILED || audio_p1_res == AST_RTP_GET_FAILED) {
3141 /* Somebody doesn't want to play... */
3142 ast_channel_unlock(c0);
3143 ast_channel_unlock(c1);
3144 return AST_BRIDGE_FAILED_NOWARN;
3147 /* If we need to feed DTMF frames into the core then only do a partial native bridge */
3148 if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
3149 ast_set_flag(p0, FLAG_P2P_NEED_DTMF);
3150 audio_p0_res = AST_RTP_TRY_PARTIAL;
3153 if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
3154 ast_set_flag(p1, FLAG_P2P_NEED_DTMF);
3155 audio_p1_res = AST_RTP_TRY_PARTIAL;
3158 /* Get codecs from both sides */
3159 codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
3160 codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
3161 if (codec0 && codec1 && !(codec0 & codec1)) {
3162 /* Hey, we can't do native bridging if both parties speak different codecs */
3164 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
3165 ast_channel_unlock(c0);
3166 ast_channel_unlock(c1);
3167 return AST_BRIDGE_FAILED_NOWARN;
3170 /* If either side can only do a partial bridge, then don't try for a true native bridge */
3171 if (audio_p0_res == AST_RTP_TRY_PARTIAL || audio_p1_res == AST_RTP_TRY_PARTIAL) {
3172 /* In order to do Packet2Packet bridging both sides must be in the same rawread/rawwrite */
3173 if (c0->rawreadformat != c1->rawwriteformat || c1->rawreadformat != c0->rawwriteformat) {
3175 ast_log(LOG_DEBUG, "Cannot packet2packet bridge - raw formats are incompatible\n");
3176 ast_channel_unlock(c0);
3177 ast_channel_unlock(c1);
3178 return AST_BRIDGE_FAILED_NOWARN;
3180 if (option_verbose > 2)
3181 ast_verbose(VERBOSE_PREFIX_3 "Packet2Packet bridging %s and %s\n", c0->name, c1->name);
3182 res = bridge_p2p_loop(c0, c1, p0, p1, vp0, vp1, timeoutms, flags, fo, rc, pvt0, pvt1);
3184 if (option_verbose > 2)
3185 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
3186 res = bridge_native_loop(c0, c1, p0, p1, vp0, vp1, pr0, pr1, codec0, codec1, timeoutms, flags, fo, rc, pvt0, pvt1);
3192 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
3195 struct ast_hostent ahp;
3200 return RESULT_SHOWUSAGE;
3202 p = strstr(arg, ":");
3208 hp = ast_gethostbyname(arg, &ahp);
3210 return RESULT_SHOWUSAGE;
3211 rtpdebugaddr.sin_family = AF_INET;
3212 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
3213 rtpdebugaddr.sin_port = htons(port);
3215 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr.sin_addr));
3217 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr.sin_addr), port);
3219 return RESULT_SUCCESS;
3222 static int rtcp_do_debug_ip(int fd, int argc, char *argv[])
3225 struct ast_hostent ahp;
3229 return RESULT_SHOWUSAGE;
3232 p = strstr(arg, ":");
3238 hp = ast_gethostbyname(arg, &ahp);
3240 return RESULT_SHOWUSAGE;
3241 rtcpdebugaddr.sin_family = AF_INET;
3242 memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
3243 rtcpdebugaddr.sin_port = htons(port);
3245 ast_cli(fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
3247 ast_cli(fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
3249 return RESULT_SUCCESS;
3252 static int rtp_do_debug(int fd, int argc, char *argv[])
3256 return RESULT_SHOWUSAGE;
3257 return rtp_do_debug_ip(fd, argc, argv);
3260 memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
3261 ast_cli(fd, "RTP Debugging Enabled\n");
3262 return RESULT_SUCCESS;
3265 static int rtcp_do_debug(int fd, int argc, char *argv[]) {
3268 return RESULT_SHOWUSAGE;
3269 return rtcp_do_debug_ip(fd, argc, argv);
3272 memset(&rtcpdebugaddr,0,sizeof(rtcpdebugaddr));
3273 ast_cli(fd, "RTCP Debugging Enabled\n");
3274 return RESULT_SUCCESS;
3277 static int rtcp_do_stats(int fd, int argc, char *argv[]) {
3279 return RESULT_SHOWUSAGE;
3282 ast_cli(fd, "RTCP Stats Enabled\n");
3283 return RESULT_SUCCESS;
3286 static int rtp_no_debug(int fd, int argc, char *argv[])
3289 return RESULT_SHOWUSAGE;
3291 ast_cli(fd,"RTP Debugging Disabled\n");
3292 return RESULT_SUCCESS;
3295 static int rtcp_no_debug(int fd, int argc, char *argv[])
3298 return RESULT_SHOWUSAGE;
3300 ast_cli(fd,"RTCP Debugging Disabled\n");
3301 return RESULT_SUCCESS;
3304 static int rtcp_no_stats(int fd, int argc, char *argv[])
3307 return RESULT_SHOWUSAGE;
3309 ast_cli(fd,"RTCP Stats Disabled\n");
3310 return RESULT_SUCCESS;
3313 static int stun_do_debug(int fd, int argc, char *argv[])
3316 return RESULT_SHOWUSAGE;
3319 ast_cli(fd, "STUN Debugging Enabled\n");
3320 return RESULT_SUCCESS;
3323 static int stun_no_debug(int fd, int argc, char *argv[])
3326 return RESULT_SHOWUSAGE;
3328 ast_cli(fd,"STUN Debugging Disabled\n");
3329 return RESULT_SUCCESS;
3332 static char debug_usage[] =
3333 "Usage: rtp debug [ip host[:port]]\n"
3334 " Enable dumping of all RTP packets to and from host.\n";
3336 static char no_debug_usage[] =
3337 "Usage: rtp nodebug\n"
3338 " Disable all RTP debugging\n";
3340 static char stun_debug_usage[] =
3341 "Usage: stun debug\n"
3342 " Enable STUN (Simple Traversal of UDP through NATs) debugging\n";
3344 static char stun_no_debug_usage[] =
3345 "Usage: stun nodebug\n"
3346 " Disable STUN debugging\n";
3348 static char rtcp_debug_usage[] =
3349 "Usage: rtcp debug [ip host[:port]]\n"
3350 " Enable dumping of all RTCP packets to and from host.\n";
3352 static char rtcp_no_debug_usage[] =
3353 "Usage: rtcp nodebug\n"
3354 " Disable all RTCP debugging\n";
3356 static char rtcp_stats_usage[] =
3357 "Usage: rtcp stats\n"
3358 " Enable dumping of RTCP stats.\n";
3360 static char rtcp_no_stats_usage[] =
3361 "Usage: rtcp nostats\n"
3362 " Disable all RTCP stats\n";
3364 static struct ast_cli_entry cli_rtp[] = {
3365 { { "rtp", "debug", "ip", NULL },
3366 rtp_do_debug, "Enable RTP debugging on IP",
3369 { { "rtp", "debug", NULL },
3370 rtp_do_debug, "Enable RTP debugging",
3373 { { "rtp", "nodebug", NULL },
3374 rtp_no_debug, "Disable RTP debugging",
3377 { { "rtcp", "debug", "ip", NULL },
3378 rtcp_do_debug, "Enable RTCP debugging on IP",
3381 { { "rtcp", "debug", NULL },
3382 rtcp_do_debug, "Enable RTCP debugging",
3385 { { "rtcp", "nodebug", NULL },
3386 rtcp_no_debug, "Disable RTCP debugging",
3387 rtcp_no_debug_usage },
3389 { { "rtcp", "stats", NULL },
3390 rtcp_do_stats, "Enable RTCP stats",
3393 { { "rtcp", "nostats", NULL },
3394 rtcp_no_stats, "Disable RTCP stats",
3395 rtcp_no_stats_usage },
3397 { { "stun", "debug", NULL },
3398 stun_do_debug, "Enable STUN debugging",
3401 { { "stun", "nodebug", NULL },
3402 stun_no_debug, "Disable STUN debugging",
3403 stun_no_debug_usage },
3406 int ast_rtp_reload(void)
3408 struct ast_config *cfg;
3413 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
3414 cfg = ast_config_load("rtp.conf");
3416 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
3418 if (rtpstart < 1024)
3420 if (rtpstart > 65535)
3423 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
3430 if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
3431 rtcpinterval = atoi(s);
3432 if (rtcpinterval == 0)
3433 rtcpinterval = 0; /* Just so we're clear... it's zero */
3434 if (rtcpinterval < RTCP_MIN_INTERVALMS)
3435 rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
3436 if (rtcpinterval > RTCP_MAX_INTERVALMS)
3437 rtcpinterval = RTCP_MAX_INTERVALMS;
3439 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
3447 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
3450 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
3451 dtmftimeout = atoi(s);
3452 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
3453 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
3454 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
3455 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
3458 ast_config_destroy(cfg);
3460 if (rtpstart >= rtpend) {
3461 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
3465 if (option_verbose > 1)
3466 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
3470 /*! \brief Initialize the RTP system in Asterisk */
3471 void ast_rtp_init(void)
3473 ast_cli_register_multiple(cli_rtp, sizeof(cli_rtp) / sizeof(struct ast_cli_entry));