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 */
132 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
133 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
134 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
136 /* DTMF Reception Variables */
138 unsigned int lasteventendseqn;
140 unsigned int dtmfduration;
141 /* DTMF Transmission Variables */
142 unsigned int lastdigitts;
148 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
149 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
150 struct timeval rxcore;
151 struct timeval txcore;
152 double drxcore; /*!< The double representation of the first received packet */
153 struct timeval lastrx; /*!< timeval when we last received a packet */
154 struct timeval dtmfmute;
155 struct ast_smoother *smoother;
157 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
158 unsigned short rxseqno;
159 struct sched_context *sched;
160 struct io_context *io;
162 ast_rtp_callback callback;
163 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
164 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
165 int rtp_lookup_code_cache_code;
166 int rtp_lookup_code_cache_result;
167 struct ast_rtcp *rtcp;
168 struct ast_codec_pref pref;
169 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
172 /* Forward declarations */
173 static int ast_rtcp_write(void *data);
174 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
175 static int ast_rtcp_write_sr(void *data);
176 static int ast_rtcp_write_rr(void *data);
177 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
178 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
179 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
180 static int bridge_p2p_rtcp_write(struct ast_rtp *rtp, unsigned int *rtcpheader, int len);
182 #define FLAG_3389_WARNING (1 << 0)
183 #define FLAG_NAT_ACTIVE (3 << 1)
184 #define FLAG_NAT_INACTIVE (0 << 1)
185 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
186 #define FLAG_HAS_DTMF (1 << 3)
187 #define FLAG_P2P_SENT_MARK (1 << 4)
188 #define FLAG_P2P_NEED_DTMF (1 << 5)
189 #define FLAG_CALLBACK_MODE (1 << 6)
190 #define FLAG_DTMF_COMPENSATE (1 << 7)
191 #define FLAG_HAS_STUN (1 << 8)
194 * \brief Structure defining an RTCP session.
196 * The concept "RTCP session" is not defined in RFC 3550, but since
197 * this structure is analogous to ast_rtp, which tracks a RTP session,
198 * it is logical to think of this as a RTCP session.
200 * RTCP packet is defined on page 9 of RFC 3550.
204 int s; /*!< Socket */
205 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
206 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
207 unsigned int soc; /*!< What they told us */
208 unsigned int spc; /*!< What they told us */
209 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
210 struct timeval rxlsr; /*!< Time when we got their last SR */
211 struct timeval txlsr; /*!< Time when we sent or last SR*/
212 unsigned int expected_prior; /*!< no. packets in previous interval */
213 unsigned int received_prior; /*!< no. packets received in previous interval */
214 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
215 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
216 unsigned int sr_count; /*!< number of SRs we've sent */
217 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
218 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
219 double rtt; /*!< Last reported rtt */
220 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
221 unsigned int reported_lost; /*!< Reported lost packets in their RR */
222 char quality[AST_MAX_USER_FIELD];
231 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
233 /* XXX Maybe stun belongs in another file if it ever has use outside of RTP */
235 unsigned short msgtype;
236 unsigned short msglen;
238 unsigned char ies[0];
239 } __attribute__((packed));
244 unsigned char value[0];
245 } __attribute__((packed));
248 unsigned char unused;
249 unsigned char family;
252 } __attribute__((packed));
254 #define STUN_IGNORE (0)
255 #define STUN_ACCEPT (1)
257 #define STUN_BINDREQ 0x0001
258 #define STUN_BINDRESP 0x0101
259 #define STUN_BINDERR 0x0111
260 #define STUN_SECREQ 0x0002
261 #define STUN_SECRESP 0x0102
262 #define STUN_SECERR 0x0112
264 #define STUN_MAPPED_ADDRESS 0x0001
265 #define STUN_RESPONSE_ADDRESS 0x0002
266 #define STUN_CHANGE_REQUEST 0x0003
267 #define STUN_SOURCE_ADDRESS 0x0004
268 #define STUN_CHANGED_ADDRESS 0x0005
269 #define STUN_USERNAME 0x0006
270 #define STUN_PASSWORD 0x0007
271 #define STUN_MESSAGE_INTEGRITY 0x0008
272 #define STUN_ERROR_CODE 0x0009
273 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
274 #define STUN_REFLECTED_FROM 0x000b
276 static const char *stun_msg2str(int msg)
280 return "Binding Request";
282 return "Binding Response";
284 return "Binding Error Response";
286 return "Shared Secret Request";
288 return "Shared Secret Response";
290 return "Shared Secret Error Response";
292 return "Non-RFC3489 Message";
295 static const char *stun_attr2str(int msg)
298 case STUN_MAPPED_ADDRESS:
299 return "Mapped Address";
300 case STUN_RESPONSE_ADDRESS:
301 return "Response Address";
302 case STUN_CHANGE_REQUEST:
303 return "Change Request";
304 case STUN_SOURCE_ADDRESS:
305 return "Source Address";
306 case STUN_CHANGED_ADDRESS:
307 return "Changed Address";
312 case STUN_MESSAGE_INTEGRITY:
313 return "Message Integrity";
314 case STUN_ERROR_CODE:
316 case STUN_UNKNOWN_ATTRIBUTES:
317 return "Unknown Attributes";
318 case STUN_REFLECTED_FROM:
319 return "Reflected From";
321 return "Non-RFC3489 Attribute";
325 const char *username;
326 const char *password;
329 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
332 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
333 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
334 switch(ntohs(attr->attr)) {
336 state->username = (const char *) (attr->value);
339 state->password = (const char *) (attr->value);
343 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
344 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
349 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
351 int size = sizeof(**attr) + strlen(s);
353 (*attr)->attr = htons(attrval);
354 (*attr)->len = htons(strlen(s));
355 memcpy((*attr)->value, s, strlen(s));
356 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
362 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
364 int size = sizeof(**attr) + 8;
365 struct stun_addr *addr;
367 (*attr)->attr = htons(attrval);
368 (*attr)->len = htons(8);
369 addr = (struct stun_addr *)((*attr)->value);
372 addr->port = sin->sin_port;
373 addr->addr = sin->sin_addr.s_addr;
374 (*attr) = (struct stun_attr *)((*attr)->value + 8);
380 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
382 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
383 (struct sockaddr *)dst, sizeof(*dst));
386 static void stun_req_id(struct stun_header *req)
390 req->id.id[x] = ast_random();
393 size_t ast_rtp_alloc_size(void)
395 return sizeof(struct ast_rtp);
398 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
400 struct stun_header *req;
401 unsigned char reqdata[1024];
403 struct stun_attr *attr;
405 req = (struct stun_header *)reqdata;
408 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
411 attr = (struct stun_attr *)req->ies;
413 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
414 req->msglen = htons(reqlen);
415 req->msgtype = htons(STUN_BINDREQ);
416 stun_send(rtp->s, suggestion, req);
419 static int stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len)
421 struct stun_header *resp, *hdr = (struct stun_header *)data;
422 struct stun_attr *attr;
423 struct stun_state st;
424 int ret = STUN_IGNORE;
425 unsigned char respdata[1024];
426 int resplen, respleft;
428 if (len < sizeof(struct stun_header)) {
430 ast_log(LOG_DEBUG, "Runt STUN packet (only %zd, wanting at least %zd)\n", len, sizeof(struct stun_header));
434 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), ntohs(hdr->msglen));
435 if (ntohs(hdr->msglen) > len - sizeof(struct stun_header)) {
437 ast_log(LOG_DEBUG, "Scrambled STUN packet length (got %d, expecting %zd)\n", ntohs(hdr->msglen), len - sizeof(struct stun_header));
439 len = ntohs(hdr->msglen);
440 data += sizeof(struct stun_header);
441 memset(&st, 0, sizeof(st));
443 if (len < sizeof(struct stun_attr)) {
445 ast_log(LOG_DEBUG, "Runt Attribute (got %zd, expecting %zd)\n", len, sizeof(struct stun_attr));
448 attr = (struct stun_attr *)data;
449 if (ntohs(attr->len) > len) {
451 ast_log(LOG_DEBUG, "Inconsistent Attribute (length %d exceeds remaining msg len %zd)\n", ntohs(attr->len), len);
454 if (stun_process_attr(&st, attr)) {
456 ast_log(LOG_DEBUG, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
459 /* Clear attribute in case previous entry was a string */
461 data += ntohs(attr->len) + sizeof(struct stun_attr);
462 len -= ntohs(attr->len) + sizeof(struct stun_attr);
464 /* Null terminate any string */
466 resp = (struct stun_header *)respdata;
468 respleft = sizeof(respdata) - sizeof(struct stun_header);
472 attr = (struct stun_attr *)resp->ies;
474 switch(ntohs(hdr->msgtype)) {
477 ast_verbose("STUN Bind Request, username: %s\n",
478 st.username ? st.username : "<none>");
480 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
481 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
482 resp->msglen = htons(resplen);
483 resp->msgtype = htons(STUN_BINDRESP);
484 stun_send(s, src, resp);
489 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
495 /*! \brief List of current sessions */
496 static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
498 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
500 unsigned int sec, usec, frac;
501 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
503 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
508 int ast_rtp_fd(struct ast_rtp *rtp)
513 int ast_rtcp_fd(struct ast_rtp *rtp)
520 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
522 unsigned int interval;
523 /*! \todo XXX Do a more reasonable calculation on this one
524 * Look in RFC 3550 Section A.7 for an example*/
525 interval = rtcpinterval;
529 /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
530 void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
532 rtp->rtptimeout = (-1) * rtp->rtptimeout;
533 rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
536 /*! \brief Set rtp timeout */
537 void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
539 rtp->rtptimeout = timeout;
542 /*! \brief Set rtp hold timeout */
543 void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
545 rtp->rtpholdtimeout = timeout;
548 /*! \brief set RTP keepalive interval */
549 void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
551 rtp->rtpkeepalive = period;
554 /*! \brief Get rtp timeout */
555 int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
557 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
559 return rtp->rtptimeout;
562 /*! \brief Get rtp hold timeout */
563 int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
565 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
567 return rtp->rtpholdtimeout;
570 /*! \brief Get RTP keepalive interval */
571 int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
573 return rtp->rtpkeepalive;
576 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
581 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
583 rtp->callback = callback;
586 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
591 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
593 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
596 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
598 ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
601 void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
603 ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
606 static struct ast_frame *send_dtmf(struct ast_rtp *rtp, enum ast_frame_type type)
608 if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
609 (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
611 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
613 rtp->dtmfduration = 0;
614 return &ast_null_frame;
617 ast_log(LOG_DEBUG, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
618 if (rtp->resp == 'X') {
619 rtp->f.frametype = AST_FRAME_CONTROL;
620 rtp->f.subclass = AST_CONTROL_FLASH;
622 rtp->f.frametype = type;
623 rtp->f.subclass = rtp->resp;
633 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
637 if (rtpdebugaddr.sin_addr.s_addr) {
638 if (((ntohs(rtpdebugaddr.sin_port) != 0)
639 && (rtpdebugaddr.sin_port != addr->sin_port))
640 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
646 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
650 if (rtcpdebugaddr.sin_addr.s_addr) {
651 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
652 && (rtcpdebugaddr.sin_port != addr->sin_port))
653 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
660 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
664 struct ast_frame *f = NULL;
669 /* We should have at least 4 bytes in RTP data */
673 /* The format of Cisco RTP DTMF packet looks like next:
674 +0 - sequence number of DTMF RTP packet (begins from 1,
677 +1 (bit 0) - flaps by different DTMF digits delimited by audio
678 or repeated digit without audio???
679 +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
680 then falls to 0 at its end)
681 +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
682 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
683 by each new packet and thus provides some redudancy.
685 Sample of Cisco RTP DTMF packet is (all data in hex):
686 19 07 00 02 12 02 20 02
687 showing end of DTMF digit '2'.
690 27 07 00 02 0A 02 20 02
691 28 06 20 02 00 02 0A 02
692 shows begin of new digit '2' with very short pause (20 ms) after
693 previous digit '2'. Bit +1.0 flips at begin of new digit.
695 Cisco RTP DTMF packets comes as replacement of audio RTP packets
696 so its uses the same sequencing and timestamping rules as replaced
697 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
698 on audio framing parameters. Marker bit isn't used within stream of
699 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
700 are not sequential at borders between DTMF and audio streams,
706 event = data[3] & 0x1f;
708 if (option_debug > 2 || rtpdebug)
709 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);
712 } else if (event < 11) {
714 } else if (event < 12) {
716 } else if (event < 16) {
717 resp = 'A' + (event - 12);
718 } else if (event < 17) {
721 if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
723 /* Why we should care on DTMF compensation at reception? */
724 if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
725 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
726 rtp->dtmfduration = 0;
728 } else if ((rtp->resp == resp) && !power) {
729 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
730 f->samples = rtp->dtmfduration * 8;
732 } else if (rtp->resp == resp)
733 rtp->dtmfduration += 20 * 8;
734 rtp->dtmfcount = dtmftimeout;
739 * \brief Process RTP DTMF and events according to RFC 2833.
741 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
749 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
752 unsigned int event_end;
753 unsigned int duration;
755 struct ast_frame *f = NULL;
757 /* Figure out event, event end, and duration */
758 event = ntohl(*((unsigned int *)(data)));
760 event_end = ntohl(*((unsigned int *)(data)));
763 duration = ntohl(*((unsigned int *)(data)));
766 /* Print out debug if turned on */
767 if (rtpdebug || option_debug > 2)
768 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
770 /* Figure out what digit was pressed */
773 } else if (event < 11) {
775 } else if (event < 12) {
777 } else if (event < 16) {
778 resp = 'A' + (event - 12);
779 } else if (event < 17) { /* Event 16: Hook flash */
783 if ((!(rtp->resp) && (!(event_end & 0x80))) || (rtp->resp && rtp->resp != resp)) {
785 if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE))
786 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
787 } else if (event_end & 0x80 && rtp->lasteventendseqn != seqno && rtp->resp) {
788 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
789 f->samples = duration;
791 rtp->lasteventendseqn = seqno;
792 } else if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && event_end & 0x80 && rtp->lasteventendseqn != seqno) {
794 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
795 f->samples = duration;
797 rtp->lasteventendseqn = seqno;
800 rtp->dtmfcount = dtmftimeout;
801 rtp->dtmfduration = duration;
807 * \brief Process Comfort Noise RTP.
809 * This is incomplete at the moment.
812 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
814 struct ast_frame *f = NULL;
815 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
816 totally help us out becuase we don't have an engine to keep it going and we are not
817 guaranteed to have it every 20ms or anything */
819 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
821 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
822 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
823 ast_inet_ntoa(rtp->them.sin_addr));
824 ast_set_flag(rtp, FLAG_3389_WARNING);
827 /* Must have at least one byte */
831 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
832 rtp->f.datalen = len - 1;
833 rtp->f.offset = AST_FRIENDLY_OFFSET;
834 memcpy(rtp->f.data, data + 1, len - 1);
840 rtp->f.frametype = AST_FRAME_CNG;
841 rtp->f.subclass = data[0] & 0x7f;
842 rtp->f.datalen = len - 1;
844 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
849 static int rtpread(int *id, int fd, short events, void *cbdata)
851 struct ast_rtp *rtp = cbdata;
853 f = ast_rtp_read(rtp);
856 rtp->callback(rtp, f, rtp->data);
861 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
864 int position, i, packetwords;
866 struct sockaddr_in sin;
867 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
868 unsigned int *rtcpheader;
880 struct ast_frame *f = &ast_null_frame;
882 if (!rtp || !rtp->rtcp)
883 return &ast_null_frame;
887 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
888 0, (struct sockaddr *)&sin, &len);
889 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
893 ast_log(LOG_WARNING, "RTCP Read error: %s\n", strerror(errno));
896 return &ast_null_frame;
899 packetwords = res / 4;
902 /* Send to whoever sent to us */
903 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
904 (rtp->rtcp->them.sin_port != sin.sin_port)) {
905 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
906 if (option_debug || rtpdebug)
907 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));
911 /* If we are P2P bridged to another RTP stream, send it directly over */
912 if (ast_rtp_get_bridged(rtp) && !bridge_p2p_rtcp_write(rtp, rtcpheader, res))
913 return &ast_null_frame;
916 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
918 /* Process a compound packet */
920 while (position < packetwords) {
922 length = ntohl(rtcpheader[i]);
923 pt = (length & 0xff0000) >> 16;
924 rc = (length & 0x1f000000) >> 24;
927 if ((i + length) > packetwords) {
928 ast_log(LOG_WARNING, "RTCP Read too short\n");
929 return &ast_null_frame;
932 if (rtcp_debug_test_addr(&sin)) {
933 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
934 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
935 ast_verbose("Reception reports: %d\n", rc);
936 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
939 i += 2; /* Advance past header and ssrc */
943 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
944 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
945 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
946 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff) >> 16); /* Going to LSR in RR*/
948 if (rtcp_debug_test_addr(&sin)) {
949 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
950 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
951 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
956 /* Intentional fall through */
958 /* This is the place to calculate RTT */
959 /* Don't handle multiple reception reports (rc > 1) yet */
960 gettimeofday(&now, NULL);
961 timeval2ntp(now, &msw, &lsw);
962 /* Use the one we sent them in our SR instead, rtcp->txlsr could have been rewritten if the dlsr is large */
963 if (ntohl(rtcpheader[i + 4])) { /* We must have the LSR */
964 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
965 a = (double)((comp & 0xffff0000) >> 16) + (double)((double)(comp & 0xffff)/1000000.);
966 lsr = (double)((ntohl(rtcpheader[i + 4]) & 0xffff0000) >> 16) + (double)((double)(ntohl(rtcpheader[i + 4]) & 0xffff) / 1000000.);
967 dlsr = (double)(ntohl(rtcpheader[i + 5])/65536.);
968 rtt = a - dlsr - lsr;
969 rtp->rtcp->accumulated_transit += rtt;
970 rtp->rtcp->rtt = rtt;
971 if (rtp->rtcp->maxrtt<rtt)
972 rtp->rtcp->maxrtt = rtt;
973 if (rtp->rtcp->minrtt>rtt)
974 rtp->rtcp->minrtt = rtt;
976 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
977 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
978 if (rtcp_debug_test_addr(&sin)) {
979 ast_verbose("Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
980 ast_verbose("Packets lost so far: %d\n", rtp->rtcp->reported_lost);
981 ast_verbose("Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
982 ast_verbose("Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
983 ast_verbose("Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
984 ast_verbose("Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
985 ast_verbose("DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
987 ast_verbose("RTT: %f(sec)\n", rtt);
991 if (rtcp_debug_test_addr(&sin))
992 ast_verbose("Received an RTCP Fast Update Request\n");
993 rtp->f.frametype = AST_FRAME_CONTROL;
994 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
1002 if (rtcp_debug_test_addr(&sin))
1003 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1006 if (rtcp_debug_test_addr(&sin))
1007 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1011 ast_log(LOG_DEBUG, "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));
1014 position += (length + 1);
1020 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
1024 double current_time;
1029 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
1030 gettimeofday(&rtp->rxcore, NULL);
1031 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
1032 /* map timestamp to a real time */
1033 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
1034 rtp->rxcore.tv_sec -= timestamp / 8000;
1035 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
1036 /* Round to 0.1ms for nice, pretty timestamps */
1037 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
1038 if (rtp->rxcore.tv_usec < 0) {
1039 /* Adjust appropriately if necessary */
1040 rtp->rxcore.tv_usec += 1000000;
1041 rtp->rxcore.tv_sec -= 1;
1045 gettimeofday(&now,NULL);
1046 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
1047 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
1048 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
1049 if (tv->tv_usec >= 1000000) {
1050 tv->tv_usec -= 1000000;
1053 prog = (double)((timestamp-rtp->seedrxts)/8000.);
1054 dtv = (double)rtp->drxcore + (double)(prog);
1055 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
1056 transit = current_time - dtv;
1057 d = transit - rtp->rxtransit;
1058 rtp->rxtransit = transit;
1061 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1062 if (rtp->rtcp && rtp->rxjitter > rtp->rtcp->maxrxjitter)
1063 rtp->rtcp->maxrxjitter = rtp->rxjitter;
1064 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1065 rtp->rtcp->minrxjitter = rtp->rxjitter;
1068 /*! \brief Perform a Packet2Packet RTCP write */
1069 static int bridge_p2p_rtcp_write(struct ast_rtp *rtp, unsigned int *rtcpheader, int len)
1071 struct ast_rtp *bridged = ast_rtp_get_bridged(rtp);
1074 /* If RTCP is not present on the bridged RTP session, then ignore this */
1078 /* Send the data out */
1079 res = sendto(bridged->rtcp->s, (void *)rtcpheader, len, 0, (struct sockaddr *)&bridged->rtcp->them, sizeof(bridged->rtcp->them));
1081 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1083 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));
1085 else if ((((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug)) && (option_debug || rtpdebug)) {
1087 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));
1089 } else if (rtp_debug_test_addr(&bridged->rtcp->them)) {
1091 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);
1097 /*! \brief Perform a Packet2Packet RTP write */
1098 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, unsigned int *rtpheader, int len, int hdrlen)
1100 struct ast_rtp *bridged = ast_rtp_get_bridged(rtp);
1101 int res = 0, payload = 0, bridged_payload = 0, version, padding, mark, ext;
1102 struct rtpPayloadType rtpPT;
1105 /* Get fields from packet */
1106 seqno = ntohl(rtpheader[0]);
1107 version = (seqno & 0xC0000000) >> 30;
1108 payload = (seqno & 0x7f0000) >> 16;
1109 padding = seqno & (1 << 29);
1110 mark = seqno & (1 << 23);
1111 ext = seqno & (1 << 28);
1114 /* Check what the payload value should be */
1115 rtpPT = ast_rtp_lookup_pt(rtp, payload);
1117 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
1118 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
1121 /* Otherwise adjust bridged payload to match */
1122 bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
1124 /* If the mark bit has not been sent yet... do it now */
1125 if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
1127 ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
1130 /* Reconstruct part of the packet */
1131 rtpheader[0] = htonl((version << 30) | (mark << 23) | (bridged_payload << 16) | (seqno));
1133 /* Send the packet back out */
1134 res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
1136 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1138 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));
1139 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1140 if (option_debug || rtpdebug)
1141 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));
1142 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1145 } else if (rtp_debug_test_addr(&bridged->them))
1146 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);
1151 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
1154 struct sockaddr_in sin;
1165 unsigned int timestamp;
1166 unsigned int *rtpheader;
1167 struct rtpPayloadType rtpPT;
1169 /* If time is up, kill it */
1170 if (rtp->send_digit)
1171 ast_rtp_senddigit_continuation(rtp);
1175 /* Cache where the header will go */
1176 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
1177 0, (struct sockaddr *)&sin, &len);
1179 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
1181 if (errno != EAGAIN)
1182 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
1185 return &ast_null_frame;
1189 ast_log(LOG_WARNING, "RTP Read too short\n");
1190 return &ast_null_frame;
1194 seqno = ntohl(rtpheader[0]);
1196 /* Check RTP version */
1197 version = (seqno & 0xC0000000) >> 30;
1199 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res) == STUN_ACCEPT) &&
1200 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
1201 memcpy(&rtp->them, &sin, sizeof(rtp->them));
1203 return &ast_null_frame;
1206 #if 0 /* Allow to receive RTP stream with closed transmission path */
1207 /* If we don't have the other side's address, then ignore this */
1208 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1209 return &ast_null_frame;
1212 /* Send to whoever send to us if NAT is turned on */
1214 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1215 (rtp->them.sin_port != sin.sin_port)) {
1218 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1219 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1222 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1223 if (option_debug || rtpdebug)
1224 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));
1228 /* If we are bridged to another RTP stream, send direct */
1229 if (ast_rtp_get_bridged(rtp) && !bridge_p2p_rtp_write(rtp, rtpheader, res, hdrlen))
1230 return &ast_null_frame;
1233 return &ast_null_frame;
1235 payloadtype = (seqno & 0x7f0000) >> 16;
1236 padding = seqno & (1 << 29);
1237 mark = seqno & (1 << 23);
1238 ext = seqno & (1 << 28);
1240 timestamp = ntohl(rtpheader[1]);
1241 ssrc = ntohl(rtpheader[2]);
1243 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1244 if (option_debug || rtpdebug)
1245 ast_log(LOG_DEBUG, "Forcing Marker bit, because SSRC has changed\n");
1252 /* Remove padding bytes */
1253 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1257 /* RTP Extension present */
1259 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
1262 profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
1263 if (profile == 0x505a)
1264 ast_log(LOG_DEBUG, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
1266 ast_log(LOG_DEBUG, "Found unknown RTP Extensions %x\n", profile);
1271 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1272 return &ast_null_frame;
1275 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1277 tseqno = rtp->lastrxseqno +1;
1279 if (rtp->rxcount==1) {
1280 /* This is the first RTP packet successfully received from source */
1281 rtp->seedrxseqno = seqno;
1284 /* Do not schedule RR if RTCP isn't run */
1285 if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
1286 /* Schedule transmission of Receiver Report */
1287 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1290 if (tseqno > RTP_SEQ_MOD) { /* if tseqno is greater than RTP_SEQ_MOD it would indicate that the sender cycled */
1291 rtp->cycles += RTP_SEQ_MOD;
1292 ast_verbose("SEQNO cycled: %u\t%d\n", rtp->cycles, seqno);
1295 rtp->lastrxseqno = seqno;
1297 if (rtp->themssrc==0)
1298 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1300 if (rtp_debug_test_addr(&sin))
1301 ast_verbose("Got RTP packet from %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1302 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1304 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1305 if (!rtpPT.isAstFormat) {
1306 struct ast_frame *f = NULL;
1308 /* This is special in-band data that's not one of our codecs */
1309 if (rtpPT.code == AST_RTP_DTMF) {
1310 /* It's special -- rfc2833 process it */
1311 if (rtp_debug_test_addr(&sin)) {
1312 unsigned char *data;
1314 unsigned int event_end;
1315 unsigned int duration;
1316 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1317 event = ntohl(*((unsigned int *)(data)));
1319 event_end = ntohl(*((unsigned int *)(data)));
1322 duration = ntohl(*((unsigned int *)(data)));
1324 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);
1326 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
1327 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1328 /* It's really special -- process it the Cisco way */
1329 if (rtp->lasteventseqn <= seqno || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
1330 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1331 rtp->lasteventseqn = seqno;
1333 } else if (rtpPT.code == AST_RTP_CN) {
1335 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1337 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1339 return f ? f : &ast_null_frame;
1341 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1342 rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : AST_FRAME_VIDEO;
1345 rtp->lastrxts = timestamp;
1347 rtp->rxseqno = seqno;
1349 /* Record received timestamp as last received now */
1350 rtp->lastrxts = timestamp;
1353 rtp->f.datalen = res - hdrlen;
1354 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1355 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1356 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
1357 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1358 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1359 ast_frame_byteswap_be(&rtp->f);
1360 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1361 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1362 rtp->f.has_timing_info = 1;
1363 rtp->f.ts = timestamp / 8;
1364 rtp->f.len = rtp->f.samples / 8;
1365 rtp->f.seqno = seqno;
1367 /* Video -- samples is # of samples vs. 90000 */
1368 if (!rtp->lastividtimestamp)
1369 rtp->lastividtimestamp = timestamp;
1370 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1371 rtp->lastividtimestamp = timestamp;
1372 rtp->f.delivery.tv_sec = 0;
1373 rtp->f.delivery.tv_usec = 0;
1375 rtp->f.subclass |= 0x1;
1382 /* The following array defines the MIME Media type (and subtype) for each
1383 of our codecs, or RTP-specific data type. */
1385 struct rtpPayloadType payloadType;
1389 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1390 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1391 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1392 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1393 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1394 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1395 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1396 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1397 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1398 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1399 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1400 {{1, AST_FORMAT_G722}, "audio", "G722"},
1401 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
1402 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1403 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1404 {{0, AST_RTP_CN}, "audio", "CN"},
1405 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1406 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1407 {{1, AST_FORMAT_H261}, "video", "H261"},
1408 {{1, AST_FORMAT_H263}, "video", "H263"},
1409 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1410 {{1, AST_FORMAT_H264}, "video", "H264"},
1411 {{1, AST_FORMAT_T140}, "text", "T140"},
1414 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1415 also, our own choices for dynamic payload types. This is our master
1416 table for transmission */
1417 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1418 [0] = {1, AST_FORMAT_ULAW},
1419 #ifdef USE_DEPRECATED_G726
1420 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1422 [3] = {1, AST_FORMAT_GSM},
1423 [4] = {1, AST_FORMAT_G723_1},
1424 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1425 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1426 [7] = {1, AST_FORMAT_LPC10},
1427 [8] = {1, AST_FORMAT_ALAW},
1428 [9] = {1, AST_FORMAT_G722},
1429 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1430 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1431 [13] = {0, AST_RTP_CN},
1432 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1433 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1434 [18] = {1, AST_FORMAT_G729A},
1435 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1436 [26] = {1, AST_FORMAT_JPEG},
1437 [31] = {1, AST_FORMAT_H261},
1438 [34] = {1, AST_FORMAT_H263},
1439 [103] = {1, AST_FORMAT_H263_PLUS},
1440 [97] = {1, AST_FORMAT_ILBC},
1441 [99] = {1, AST_FORMAT_H264},
1442 [101] = {0, AST_RTP_DTMF},
1443 [102] = {1, AST_FORMAT_T140}, /* Real time text chat */
1444 [110] = {1, AST_FORMAT_SPEEX},
1445 [111] = {1, AST_FORMAT_G726},
1446 [112] = {1, AST_FORMAT_G726_AAL2},
1447 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1450 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1456 for (i = 0; i < MAX_RTP_PT; ++i) {
1457 rtp->current_RTP_PT[i].isAstFormat = 0;
1458 rtp->current_RTP_PT[i].code = 0;
1461 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1462 rtp->rtp_lookup_code_cache_code = 0;
1463 rtp->rtp_lookup_code_cache_result = 0;
1466 void ast_rtp_pt_default(struct ast_rtp* rtp)
1470 /* Initialize to default payload types */
1471 for (i = 0; i < MAX_RTP_PT; ++i) {
1472 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1473 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1476 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1477 rtp->rtp_lookup_code_cache_code = 0;
1478 rtp->rtp_lookup_code_cache_result = 0;
1481 void ast_rtp_pt_copy(struct ast_rtp *dest, const struct ast_rtp *src)
1485 for (i=0; i < MAX_RTP_PT; ++i) {
1486 dest->current_RTP_PT[i].isAstFormat =
1487 src->current_RTP_PT[i].isAstFormat;
1488 dest->current_RTP_PT[i].code =
1489 src->current_RTP_PT[i].code;
1491 dest->rtp_lookup_code_cache_isAstFormat = 0;
1492 dest->rtp_lookup_code_cache_code = 0;
1493 dest->rtp_lookup_code_cache_result = 0;
1496 /*! \brief Get channel driver interface structure */
1497 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1499 struct ast_rtp_protocol *cur = NULL;
1501 AST_LIST_LOCK(&protos);
1502 AST_LIST_TRAVERSE(&protos, cur, list) {
1503 if (cur->type == chan->tech->type)
1506 AST_LIST_UNLOCK(&protos);
1511 int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1513 // dest = c0, src = c1
1514 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1515 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1516 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1517 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED;
1518 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED;
1519 int srccodec, nat_active = 0;
1522 ast_channel_lock(c0);
1524 while(ast_channel_trylock(c1)) {
1525 ast_channel_unlock(c0);
1527 ast_channel_lock(c0);
1531 /* Find channel driver interfaces */
1532 destpr = get_proto(c0);
1534 srcpr = get_proto(c1);
1537 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", c0->name);
1538 ast_channel_unlock(c0);
1540 ast_channel_unlock(c1);
1545 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
1546 ast_channel_unlock(c0);
1548 ast_channel_unlock(c1);
1552 /* Get audio and video interface (if native bridge is possible) */
1553 audio_dest_res = destpr->get_rtp_info(c0, &destp);
1554 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
1556 audio_src_res = srcpr->get_rtp_info(c1, &srcp);
1557 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
1560 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1561 if (audio_dest_res != AST_RTP_TRY_NATIVE) {
1562 /* Somebody doesn't want to play... */
1563 ast_channel_unlock(c0);
1565 ast_channel_unlock(c1);
1568 if (audio_src_res == AST_RTP_TRY_NATIVE && srcpr->get_codec)
1569 srccodec = srcpr->get_codec(c1);
1572 /* Consider empty media as non-existant */
1573 if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
1575 if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1577 /* Bridge media early */
1578 if (destpr->set_rtp_peer(c0, srcp, vsrcp, srccodec, nat_active))
1579 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1580 ast_channel_unlock(c0);
1582 ast_channel_unlock(c1);
1584 ast_log(LOG_DEBUG, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1588 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1590 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1591 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1592 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1593 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED;
1594 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED;
1598 ast_channel_lock(dest);
1599 while(ast_channel_trylock(src)) {
1600 ast_channel_unlock(dest);
1602 ast_channel_lock(dest);
1605 /* Find channel driver interfaces */
1606 if (!(destpr = get_proto(dest))) {
1608 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1609 ast_channel_unlock(dest);
1610 ast_channel_unlock(src);
1613 if (!(srcpr = get_proto(src))) {
1615 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
1616 ast_channel_unlock(dest);
1617 ast_channel_unlock(src);
1621 /* Get audio and video interface (if native bridge is possible) */
1622 audio_dest_res = destpr->get_rtp_info(dest, &destp);
1623 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
1624 audio_src_res = srcpr->get_rtp_info(src, &srcp);
1625 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
1627 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1628 if (audio_dest_res != AST_RTP_TRY_NATIVE || audio_src_res != AST_RTP_TRY_NATIVE) {
1629 /* Somebody doesn't want to play... */
1630 ast_channel_unlock(dest);
1631 ast_channel_unlock(src);
1634 ast_rtp_pt_copy(destp, srcp);
1635 if (vdestp && vsrcp)
1636 ast_rtp_pt_copy(vdestp, vsrcp);
1637 if (srcpr->get_codec)
1638 srccodec = srcpr->get_codec(src);
1643 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1644 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1646 ast_channel_unlock(dest);
1647 ast_channel_unlock(src);
1649 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1653 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1654 * By default, use the well-known value for this type (although it may
1655 * still be set to a different value by a subsequent "a=rtpmap:" line)
1657 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1659 if (pt < 0 || pt > MAX_RTP_PT)
1660 return; /* bogus payload type */
1662 if (static_RTP_PT[pt].code != 0)
1663 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1666 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1667 * an SDP "a=rtpmap:" line.
1669 void ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
1670 char *mimeType, char *mimeSubtype,
1671 enum ast_rtp_options options)
1675 if (pt < 0 || pt > MAX_RTP_PT)
1676 return; /* bogus payload type */
1678 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1679 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1680 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1681 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1682 if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
1683 mimeTypes[i].payloadType.isAstFormat &&
1684 (options & AST_RTP_OPT_G726_NONSTANDARD))
1685 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
1691 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
1692 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1693 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1694 int* astFormats, int* nonAstFormats) {
1697 *astFormats = *nonAstFormats = 0;
1698 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1699 if (rtp->current_RTP_PT[pt].isAstFormat) {
1700 *astFormats |= rtp->current_RTP_PT[pt].code;
1702 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
1707 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
1709 struct rtpPayloadType result;
1711 result.isAstFormat = result.code = 0;
1712 if (pt < 0 || pt > MAX_RTP_PT)
1713 return result; /* bogus payload type */
1715 /* Start with negotiated codecs */
1716 result = rtp->current_RTP_PT[pt];
1718 /* If it doesn't exist, check our static RTP type list, just in case */
1720 result = static_RTP_PT[pt];
1724 /*! \brief Looks up an RTP code out of our *static* outbound list */
1725 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
1729 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
1730 code == rtp->rtp_lookup_code_cache_code) {
1732 /* Use our cached mapping, to avoid the overhead of the loop below */
1733 return rtp->rtp_lookup_code_cache_result;
1736 /* Check the dynamic list first */
1737 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1738 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
1739 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1740 rtp->rtp_lookup_code_cache_code = code;
1741 rtp->rtp_lookup_code_cache_result = pt;
1746 /* Then the static list */
1747 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1748 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
1749 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1750 rtp->rtp_lookup_code_cache_code = code;
1751 rtp->rtp_lookup_code_cache_result = pt;
1758 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
1759 enum ast_rtp_options options)
1763 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1764 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
1766 (code == AST_FORMAT_G726_AAL2) &&
1767 (options & AST_RTP_OPT_G726_NONSTANDARD))
1770 return mimeTypes[i].subtype;
1777 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
1778 const int isAstFormat, enum ast_rtp_options options)
1788 snprintf(end, size, "0x%x (", capability);
1795 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
1796 if (capability & format) {
1797 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
1799 snprintf(end, size, "%s|", name);
1807 snprintf(start, size, "nothing)");
1814 /*! \brief Open RTP or RTCP socket for a session */
1815 static int rtp_socket(void)
1819 s = socket(AF_INET, SOCK_DGRAM, 0);
1821 flags = fcntl(s, F_GETFL);
1822 fcntl(s, F_SETFL, flags | O_NONBLOCK);
1825 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
1832 * \brief Initialize a new RTCP session.
1834 * \returns The newly initialized RTCP session.
1836 static struct ast_rtcp *ast_rtcp_new(void)
1838 struct ast_rtcp *rtcp;
1840 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
1842 rtcp->s = rtp_socket();
1843 rtcp->us.sin_family = AF_INET;
1844 rtcp->them.sin_family = AF_INET;
1848 ast_log(LOG_WARNING, "Unable to allocate RTCP socket: %s\n", strerror(errno));
1855 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
1857 struct ast_rtp *rtp;
1862 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
1864 rtp->them.sin_family = AF_INET;
1865 rtp->us.sin_family = AF_INET;
1866 rtp->s = rtp_socket();
1867 rtp->ssrc = ast_random();
1868 rtp->seqno = ast_random() & 0xffff;
1869 ast_set_flag(rtp, FLAG_HAS_DTMF);
1872 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1875 if (sched && rtcpenable) {
1877 rtp->rtcp = ast_rtcp_new();
1880 /* Select a random port number in the range of possible RTP */
1881 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
1883 /* Save it for future references. */
1885 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1887 /* Must be an even port number by RTP spec */
1888 rtp->us.sin_port = htons(x);
1889 rtp->us.sin_addr = addr;
1891 /* If there's rtcp, initialize it as well. */
1893 rtp->rtcp->us.sin_port = htons(x + 1);
1894 rtp->rtcp->us.sin_addr = addr;
1896 /* Try to bind it/them. */
1897 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1898 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1901 /* Primary bind succeeded! Gotta recreate it */
1903 rtp->s = rtp_socket();
1905 if (errno != EADDRINUSE) {
1906 /* We got an error that wasn't expected, abort! */
1907 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1910 close(rtp->rtcp->s);
1916 /* The port was used, increment it (by two). */
1918 /* Did we go over the limit ? */
1920 /* then, start from the begingig. */
1921 x = (rtpstart + 1) & ~1;
1922 /* Check if we reached the place were we started. */
1923 if (x == startplace) {
1924 /* If so, there's no ports available. */
1925 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1928 close(rtp->rtcp->s);
1938 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1939 ast_set_flag(rtp, FLAG_CALLBACK_MODE);
1941 ast_rtp_pt_default(rtp);
1945 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1949 memset(&ia, 0, sizeof(ia));
1950 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1953 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1957 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1958 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1962 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1964 rtp->them.sin_port = them->sin_port;
1965 rtp->them.sin_addr = them->sin_addr;
1967 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1968 rtp->rtcp->them.sin_addr = them->sin_addr;
1973 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1975 if ((them->sin_family != AF_INET) ||
1976 (them->sin_port != rtp->them.sin_port) ||
1977 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
1978 them->sin_family = AF_INET;
1979 them->sin_port = rtp->them.sin_port;
1980 them->sin_addr = rtp->them.sin_addr;
1986 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1991 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
1993 return rtp->bridged;
1996 void ast_rtp_stop(struct ast_rtp *rtp)
1998 if (rtp->rtcp && rtp->rtcp->schedid > 0) {
1999 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2000 rtp->rtcp->schedid = -1;
2003 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
2004 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
2006 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
2007 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
2010 ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
2013 void ast_rtp_reset(struct ast_rtp *rtp)
2015 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
2016 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
2017 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
2019 rtp->lastdigitts = 0;
2021 rtp->lastividtimestamp = 0;
2022 rtp->lastovidtimestamp = 0;
2023 rtp->lasteventseqn = 0;
2024 rtp->lasteventendseqn = 0;
2025 rtp->lasttxformat = 0;
2026 rtp->lastrxformat = 0;
2028 rtp->dtmfduration = 0;
2033 char *ast_rtp_get_quality(struct ast_rtp *rtp)
2037 *themssrc their ssrc
2039 *rxjitter our calculated jitter(rx)
2040 *rxcount no. received packets
2041 *txjitter reported jitter of the other end
2042 *txcount transmitted packets
2043 *rlp remote lost packets
2046 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);
2048 return rtp->rtcp->quality;
2051 void ast_rtp_destroy(struct ast_rtp *rtp)
2053 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
2054 /*Print some info on the call here */
2055 ast_verbose(" RTP-stats\n");
2056 ast_verbose("* Our Receiver:\n");
2057 ast_verbose(" SSRC: %u\n", rtp->themssrc);
2058 ast_verbose(" Received packets: %u\n", rtp->rxcount);
2059 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
2060 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
2061 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
2062 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
2063 ast_verbose("* Our Sender:\n");
2064 ast_verbose(" SSRC: %u\n", rtp->ssrc);
2065 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2066 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
2067 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter);
2068 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
2069 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
2073 ast_smoother_free(rtp->smoother);
2075 ast_io_remove(rtp->io, rtp->ioid);
2079 if (rtp->rtcp->schedid > 0)
2080 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2081 close(rtp->rtcp->s);
2088 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2092 if (ast_tvzero(rtp->txcore)) {
2093 rtp->txcore = ast_tvnow();
2094 /* Round to 20ms for nice, pretty timestamps */
2095 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2097 /* Use previous txcore if available */
2098 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2099 ms = ast_tvdiff_ms(t, rtp->txcore);
2102 /* Use what we just got for next time */
2104 return (unsigned int) ms;
2107 /*! \brief Send begin frames for DTMF */
2108 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
2110 unsigned int *rtpheader;
2111 int hdrlen = 12, res = 0, i = 0, payload = 0;
2114 if ((digit <= '9') && (digit >= '0'))
2116 else if (digit == '*')
2118 else if (digit == '#')
2120 else if ((digit >= 'A') && (digit <= 'D'))
2121 digit = digit - 'A' + 12;
2122 else if ((digit >= 'a') && (digit <= 'd'))
2123 digit = digit - 'a' + 12;
2125 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2129 /* If we have no peer, return immediately */
2130 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2133 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
2135 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2136 rtp->send_duration = 160;
2138 /* Get a pointer to the header */
2139 rtpheader = (unsigned int *)data;
2140 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2141 rtpheader[1] = htonl(rtp->lastdigitts);
2142 rtpheader[2] = htonl(rtp->ssrc);
2144 for (i = 0; i < 2; i++) {
2145 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2146 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2148 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2149 ast_inet_ntoa(rtp->them.sin_addr),
2150 ntohs(rtp->them.sin_port), strerror(errno));
2151 if (rtp_debug_test_addr(&rtp->them))
2152 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2153 ast_inet_ntoa(rtp->them.sin_addr),
2154 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2155 /* Increment sequence number */
2157 /* Increment duration */
2158 rtp->send_duration += 160;
2159 /* Clear marker bit and set seqno */
2160 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2163 /* Since we received a begin, we can safely store the digit and disable any compensation */
2164 rtp->send_digit = digit;
2165 rtp->send_payload = payload;
2170 /*! \brief Send continuation frame for DTMF */
2171 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
2173 unsigned int *rtpheader;
2174 int hdrlen = 12, res = 0;
2177 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2180 /* Setup packet to send */
2181 rtpheader = (unsigned int *)data;
2182 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2183 rtpheader[1] = htonl(rtp->lastdigitts);
2184 rtpheader[2] = htonl(rtp->ssrc);
2185 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2186 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2189 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2191 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2192 ast_inet_ntoa(rtp->them.sin_addr),
2193 ntohs(rtp->them.sin_port), strerror(errno));
2194 if (rtp_debug_test_addr(&rtp->them))
2195 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2196 ast_inet_ntoa(rtp->them.sin_addr),
2197 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2199 /* Increment sequence number */
2201 /* Increment duration */
2202 rtp->send_duration += 160;
2207 /*! \brief Send end packets for DTMF */
2208 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
2210 unsigned int *rtpheader;
2211 int hdrlen = 12, res = 0, i = 0;
2214 /* If no address, then bail out */
2215 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2218 if ((digit <= '9') && (digit >= '0'))
2220 else if (digit == '*')
2222 else if (digit == '#')
2224 else if ((digit >= 'A') && (digit <= 'D'))
2225 digit = digit - 'A' + 12;
2226 else if ((digit >= 'a') && (digit <= 'd'))
2227 digit = digit - 'a' + 12;
2229 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2233 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2235 rtpheader = (unsigned int *)data;
2236 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2237 rtpheader[1] = htonl(rtp->lastdigitts);
2238 rtpheader[2] = htonl(rtp->ssrc);
2239 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2241 rtpheader[3] |= htonl((1 << 23));
2242 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2243 /* Send 3 termination packets */
2244 for (i = 0; i < 3; i++) {
2245 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2247 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2248 ast_inet_ntoa(rtp->them.sin_addr),
2249 ntohs(rtp->them.sin_port), strerror(errno));
2250 if (rtp_debug_test_addr(&rtp->them))
2251 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2252 ast_inet_ntoa(rtp->them.sin_addr),
2253 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2255 rtp->send_digit = 0;
2256 /* Increment lastdigitts */
2257 rtp->lastdigitts += 960;
2263 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
2264 int ast_rtcp_send_h261fur(void *data)
2266 struct ast_rtp *rtp = data;
2269 rtp->rtcp->sendfur = 1;
2270 res = ast_rtcp_write(data);
2275 /*! \brief Send RTCP sender's report */
2276 static int ast_rtcp_write_sr(void *data)
2278 struct ast_rtp *rtp = data;
2282 unsigned int now_lsw;
2283 unsigned int now_msw;
2284 unsigned int *rtcpheader;
2286 unsigned int extended;
2287 unsigned int expected;
2288 unsigned int expected_interval;
2289 unsigned int received_interval;
2292 struct timeval dlsr;
2295 /* Commented condition is always not NULL if rtp->rtcp is not NULL */
2296 if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
2299 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
2300 ast_verbose("RTCP SR transmission error, rtcp halted\n");
2301 if (rtp->rtcp->schedid > 0)
2302 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2303 rtp->rtcp->schedid = -1;
2307 gettimeofday(&now, NULL);
2308 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
2309 rtcpheader = (unsigned int *)bdata;
2310 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
2311 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
2312 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
2313 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
2314 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
2315 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
2318 extended = rtp->cycles + rtp->lastrxseqno;
2319 expected = extended - rtp->seedrxseqno + 1;
2320 if (rtp->rxcount > expected)
2321 expected += rtp->rxcount - expected;
2322 lost = expected - rtp->rxcount;
2323 expected_interval = expected - rtp->rtcp->expected_prior;
2324 rtp->rtcp->expected_prior = expected;
2325 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2326 rtp->rtcp->received_prior = rtp->rxcount;
2327 lost_interval = expected_interval - received_interval;
2328 if (expected_interval == 0 || lost_interval <= 0)
2331 fraction = (lost_interval << 8) / expected_interval;
2332 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2333 rtcpheader[7] = htonl(rtp->themssrc);
2334 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2335 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2336 rtcpheader[10] = htonl((unsigned int)rtp->rxjitter);
2337 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2338 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2341 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2343 if (rtp->rtcp->sendfur) {
2344 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2345 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
2347 rtp->rtcp->sendfur = 0;
2350 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2351 /* it can change mid call, and SDES can't) */
2352 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2353 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2354 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2357 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2359 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));
2360 if (rtp->rtcp->schedid > 0)
2361 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2362 rtp->rtcp->schedid = -1;
2366 /* FIXME Don't need to get a new one */
2367 gettimeofday(&rtp->rtcp->txlsr, NULL);
2368 rtp->rtcp->sr_count++;
2370 rtp->rtcp->lastsrtxcount = rtp->txcount;
2372 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2373 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2374 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
2375 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2376 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
2377 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2378 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
2379 ast_verbose(" Report block:\n");
2380 ast_verbose(" Fraction lost: %u\n", fraction);
2381 ast_verbose(" Cumulative loss: %u\n", lost);
2382 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
2383 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
2384 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2389 /*! \brief Send RTCP recipient's report */
2390 static int ast_rtcp_write_rr(void *data)
2392 struct ast_rtp *rtp = data;
2396 unsigned int extended;
2397 unsigned int expected;
2398 unsigned int expected_interval;
2399 unsigned int received_interval;
2402 unsigned int *rtcpheader;
2404 struct timeval dlsr;
2407 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2410 if (!rtp->rtcp->them.sin_addr.s_addr) {
2411 ast_log(LOG_ERROR, "RTCP RR transmission error to, rtcp halted %s\n",strerror(errno));
2412 if (rtp->rtcp->schedid > 0)
2413 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2414 rtp->rtcp->schedid = -1;
2418 extended = rtp->cycles + rtp->lastrxseqno;
2419 expected = extended - rtp->seedrxseqno + 1;
2420 lost = expected - rtp->rxcount;
2421 expected_interval = expected - rtp->rtcp->expected_prior;
2422 rtp->rtcp->expected_prior = expected;
2423 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2424 rtp->rtcp->received_prior = rtp->rxcount;
2425 lost_interval = expected_interval - received_interval;
2426 if (expected_interval == 0 || lost_interval <= 0)
2429 fraction = (lost_interval << 8) / expected_interval;
2430 gettimeofday(&now, NULL);
2431 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2432 rtcpheader = (unsigned int *)bdata;
2433 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2434 rtcpheader[1] = htonl(rtp->ssrc);
2435 rtcpheader[2] = htonl(rtp->themssrc);
2436 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2437 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2438 rtcpheader[5] = htonl((unsigned int)rtp->rxjitter);
2439 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2440 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2442 if (rtp->rtcp->sendfur) {
2443 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2444 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
2446 rtp->rtcp->sendfur = 0;
2449 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2450 it can change mid call, and SDES can't) */
2451 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2452 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2453 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2456 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2459 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2460 /* Remove the scheduler */
2461 if (rtp->rtcp->schedid > 0)
2462 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2463 rtp->rtcp->schedid = -1;
2467 rtp->rtcp->rr_count++;
2469 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2470 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2471 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2472 " IA jitter: %.4f\n"
2473 " Their last SR: %u\n"
2474 " DLSR: %4.4f (sec)\n\n",
2475 ast_inet_ntoa(rtp->rtcp->them.sin_addr),
2476 ntohs(rtp->rtcp->them.sin_port),
2477 rtp->ssrc, rtp->themssrc, fraction, lost,
2479 rtp->rtcp->themrxlsr,
2480 (double)(ntohl(rtcpheader[7])/65536.0));
2486 /*! \brief Write and RTCP packet to the far end
2487 * \note Decide if we are going to send an SR (with Reception Block) or RR
2488 * RR is sent if we have not sent any rtp packets in the previous interval */
2489 static int ast_rtcp_write(void *data)
2491 struct ast_rtp *rtp = data;
2494 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2495 res = ast_rtcp_write_sr(data);
2497 res = ast_rtcp_write_rr(data);
2502 /*! \brief generate comfort noice (CNG) */
2503 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2505 unsigned int *rtpheader;
2510 level = 127 - (level & 0x7f);
2511 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2513 /* If we have no peer, return immediately */
2514 if (!rtp->them.sin_addr.s_addr)
2517 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2519 /* Get a pointer to the header */
2520 rtpheader = (unsigned int *)data;
2521 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2522 rtpheader[1] = htonl(rtp->lastts);
2523 rtpheader[2] = htonl(rtp->ssrc);
2525 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2526 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2528 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));
2529 if (rtp_debug_test_addr(&rtp->them))
2530 ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %u, len %d)\n"
2531 , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
2537 /*! \brief Write RTP packet with audio or video media frames into UDP packet */
2538 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2540 unsigned char *rtpheader;
2547 ms = calc_txstamp(rtp, &f->delivery);
2548 /* Default prediction */
2549 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
2550 pred = rtp->lastts + f->samples;
2552 /* Re-calculate last TS */
2553 rtp->lastts = rtp->lastts + ms * 8;
2554 if (ast_tvzero(f->delivery)) {
2555 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
2556 and if so, go with our prediction */
2557 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
2560 if (option_debug > 2)
2561 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2566 mark = f->subclass & 0x1;
2567 pred = rtp->lastovidtimestamp + f->samples;
2568 /* Re-calculate last TS */
2569 rtp->lastts = rtp->lastts + ms * 90;
2570 /* If it's close to our prediction, go for it */
2571 if (ast_tvzero(f->delivery)) {
2572 if (abs(rtp->lastts - pred) < 7200) {
2574 rtp->lastovidtimestamp += f->samples;
2576 if (option_debug > 2)
2577 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);
2578 rtp->lastovidtimestamp = rtp->lastts;
2582 /* If the timestamp for non-digit packets has moved beyond the timestamp
2583 for digits, update the digit timestamp.
2585 if (rtp->lastts > rtp->lastdigitts)
2586 rtp->lastdigitts = rtp->lastts;
2588 if (f->has_timing_info)
2589 rtp->lastts = f->ts * 8;
2591 /* Get a pointer to the header */
2592 rtpheader = (unsigned char *)(f->data - hdrlen);
2594 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
2595 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
2596 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
2598 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2599 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2601 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
2603 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));
2604 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
2605 /* Only give this error message once if we are not RTP debugging */
2606 if (option_debug || rtpdebug)
2607 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));
2608 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
2612 rtp->txoctetcount +=(res - hdrlen);
2614 if (rtp->rtcp && rtp->rtcp->schedid < 1)
2615 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
2618 if (rtp_debug_test_addr(&rtp->them))
2619 ast_verbose("Sent RTP packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2620 ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
2628 int ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
2631 for (x = 0; x < 32; x++) { /* Ugly way */
2632 rtp->pref.order[x] = prefs->order[x];
2633 rtp->pref.framing[x] = prefs->framing[x];
2636 ast_smoother_free(rtp->smoother);
2637 rtp->smoother = NULL;
2641 struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
2646 int ast_rtp_codec_getformat(int pt)
2648 if (pt < 0 || pt > MAX_RTP_PT)
2649 return 0; /* bogus payload type */
2651 if (static_RTP_PT[pt].isAstFormat)
2652 return static_RTP_PT[pt].code;
2657 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
2659 struct ast_frame *f;
2665 /* If we have no peer, return immediately */
2666 if (!rtp->them.sin_addr.s_addr)
2669 /* If there is no data length, return immediately */
2673 /* Make sure we have enough space for RTP header */
2674 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
2675 ast_log(LOG_WARNING, "RTP can only send voice and video\n");
2679 subclass = _f->subclass;
2680 if (_f->frametype == AST_FRAME_VIDEO)
2683 codec = ast_rtp_lookup_code(rtp, 1, subclass);
2685 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
2689 if (rtp->lasttxformat != subclass) {
2690 /* New format, reset the smoother */
2692 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
2693 rtp->lasttxformat = subclass;
2695 ast_smoother_free(rtp->smoother);
2696 rtp->smoother = NULL;
2699 if (!rtp->smoother) {
2700 struct ast_format_list fmt = ast_codec_pref_getsize(&rtp->pref, subclass);
2701 if (fmt.inc_ms) { /* if codec parameters is set / avoid division by zero */
2702 if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
2703 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));
2707 ast_smoother_set_flags(rtp->smoother, fmt.flags);
2709 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));
2712 if (rtp->smoother) {
2713 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
2714 ast_smoother_feed_be(rtp->smoother, _f);
2716 ast_smoother_feed(rtp->smoother, _f);
2719 while((f = ast_smoother_read(rtp->smoother)))
2720 ast_rtp_raw_write(rtp, f, codec);
2722 /* Don't buffer outgoing frames; send them one-per-packet: */
2723 if (_f->offset < hdrlen)
2724 f = ast_frdup(_f); /*! \bug XXX this might never be free'd. Why do we do this? */
2727 ast_rtp_raw_write(rtp, f, codec);
2735 /*! \brief Unregister interface to channel driver */
2736 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
2738 AST_LIST_LOCK(&protos);
2739 AST_LIST_REMOVE(&protos, proto, list);
2740 AST_LIST_UNLOCK(&protos);
2743 /*! \brief Register interface to channel driver */
2744 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
2746 struct ast_rtp_protocol *cur;
2748 AST_LIST_LOCK(&protos);
2749 AST_LIST_TRAVERSE(&protos, cur, list) {
2750 if (!strcmp(cur->type, proto->type)) {
2751 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
2752 AST_LIST_UNLOCK(&protos);
2756 AST_LIST_INSERT_HEAD(&protos, proto, list);
2757 AST_LIST_UNLOCK(&protos);
2762 /*! \brief Bridge loop for true native bridge (reinvite) */
2763 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)
2765 struct ast_frame *fr = NULL;
2766 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
2767 int oldcodec0 = codec0, oldcodec1 = codec1;
2768 struct sockaddr_in ac1 = {0,}, vac1 = {0,}, ac0 = {0,}, vac0 = {0,};
2769 struct sockaddr_in t1 = {0,}, vt1 = {0,}, t0 = {0,}, vt0 = {0,};
2771 /* Set it up so audio goes directly between the two endpoints */
2773 /* Test the first channel */
2774 if (!(pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))) {
2775 ast_rtp_get_peer(p1, &ac1);
2777 ast_rtp_get_peer(vp1, &vac1);
2779 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
2781 /* Test the second channel */
2782 if (!(pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))) {
2783 ast_rtp_get_peer(p0, &ac0);
2785 ast_rtp_get_peer(vp0, &vac0);
2787 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c1->name, c0->name);
2789 /* Now we can unlock and move into our loop */
2790 ast_channel_unlock(c0);
2791 ast_channel_unlock(c1);
2793 /* Throw our channels into the structure and enter the loop */
2798 /* Check if anything changed */
2799 if ((c0->tech_pvt != pvt0) ||
2800 (c1->tech_pvt != pvt1) ||
2801 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
2803 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
2804 if (c0->tech_pvt == pvt0)
2805 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2806 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2807 if (c1->tech_pvt == pvt1)
2808 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2809 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2810 return AST_BRIDGE_RETRY;
2813 /* Check if they have changed their address */
2814 ast_rtp_get_peer(p1, &t1);
2816 ast_rtp_get_peer(vp1, &vt1);
2818 codec1 = pr1->get_codec(c1);
2819 ast_rtp_get_peer(p0, &t0);
2821 ast_rtp_get_peer(vp0, &vt0);
2823 codec0 = pr0->get_codec(c0);
2824 if ((inaddrcmp(&t1, &ac1)) ||
2825 (vp1 && inaddrcmp(&vt1, &vac1)) ||
2826 (codec1 != oldcodec1)) {
2827 if (option_debug > 1) {
2828 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2829 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
2830 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
2831 c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
2832 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2833 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
2834 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2835 c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
2837 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)))
2838 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
2839 memcpy(&ac1, &t1, sizeof(ac1));
2840 memcpy(&vac1, &vt1, sizeof(vac1));
2843 if ((inaddrcmp(&t0, &ac0)) ||
2844 (vp0 && inaddrcmp(&vt0, &vac0))) {
2845 if (option_debug > 1) {
2846 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2847 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
2848 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2849 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
2851 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)))
2852 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
2853 memcpy(&ac0, &t0, sizeof(ac0));
2854 memcpy(&vac0, &vt0, sizeof(vac0));
2858 /* Wait for frame to come in on the channels */
2859 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
2861 return AST_BRIDGE_RETRY;
2863 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2864 if (ast_check_hangup(c0) || ast_check_hangup(c1))
2869 other = (who == c0) ? c1 : c0;
2870 if (!fr || ((fr->frametype == AST_FRAME_DTMF) &&
2871 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
2872 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
2873 /* Break out of bridge */
2877 ast_log(LOG_DEBUG, "Oooh, got a %s\n", fr ? "digit" : "hangup");
2878 if (c0->tech_pvt == pvt0)
2879 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2880 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2881 if (c1->tech_pvt == pvt1)
2882 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2883 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2884 return AST_BRIDGE_COMPLETE;
2885 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2886 if ((fr->subclass == AST_CONTROL_HOLD) ||
2887 (fr->subclass == AST_CONTROL_UNHOLD) ||
2888 (fr->subclass == AST_CONTROL_VIDUPDATE)) {
2889 ast_indicate(other, fr->subclass);
2895 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
2896 return AST_BRIDGE_COMPLETE;
2899 if ((fr->frametype == AST_FRAME_DTMF) ||
2900 (fr->frametype == AST_FRAME_VOICE) ||
2901 (fr->frametype == AST_FRAME_VIDEO)) {
2902 ast_write(other, fr);
2912 return AST_BRIDGE_FAILED;
2915 /*! \brief P2P RTP Callback */
2916 static int p2p_rtp_callback(int *id, int fd, short events, void *cbdata)
2918 int res = 0, hdrlen = 12;
2919 struct sockaddr_in sin;
2921 unsigned int *header;
2922 struct ast_rtp *rtp = cbdata;
2928 if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
2931 header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
2933 /* If NAT support is turned on, then see if we need to change their address */
2935 ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
2936 (rtp->them.sin_port != sin.sin_port))) {
2939 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
2940 if (option_debug || rtpdebug)
2941 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));
2944 /* Write directly out to other RTP stream if bridged */
2945 if (ast_rtp_get_bridged(rtp))
2946 bridge_p2p_rtp_write(rtp, header, res, hdrlen);
2951 /*! \brief P2P RTCP Callback */
2952 static int p2p_rtcp_callback(int *id, int fd, short events, void *cbdata)
2955 struct sockaddr_in sin;
2957 unsigned int *header;
2958 struct ast_rtp *rtp = cbdata;
2959 struct ast_rtcp *rtcp = NULL;
2961 if (!rtp || !(rtcp = rtp->rtcp))
2965 if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
2968 header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
2971 ((rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
2972 (rtcp->them.sin_port != sin.sin_port))) {
2974 if (option_debug || rtpdebug)
2975 ast_log(LOG_DEBUG, "P2P RTCP NAT: Got RTCP from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtcp->them.sin_addr), ntohs(rtcp->them.sin_port));
2978 if (ast_rtp_get_bridged(rtp))
2979 bridge_p2p_rtcp_write(rtp, header, res);
2984 /*! \brief Helper function to switch a channel and RTP stream into callback mode */
2985 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
2987 /* If we need DTMF, are looking for STUN, or we have no IO structure then we can't do direct callback */
2988 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) || ast_test_flag(rtp, FLAG_HAS_STUN) || !rtp->io)
2991 /* If the RTP structure is already in callback mode, remove it temporarily */
2993 ast_io_remove(rtp->io, rtp->ioid);
2997 /* Steal the file descriptors from the channel */
3001 /* Now, fire up callback mode */
3002 iod[0] = ast_io_add(rtp->io, ast_rtp_fd(rtp), p2p_rtp_callback, AST_IO_IN, rtp);
3004 iod[1] = ast_io_add(rtp->io, ast_rtcp_fd(rtp), p2p_rtcp_callback, AST_IO_IN, rtp);
3009 /*! \brief Helper function to switch a channel and RTP stream out of callback mode */
3010 static int p2p_callback_disable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
3012 ast_channel_lock(chan);
3014 /* Remove the callback from the IO context */
3015 ast_io_remove(rtp->io, iod[0]);
3018 ast_io_remove(rtp->io, iod[1]);
3020 /* Restore file descriptors */
3021 chan->fds[0] = ast_rtp_fd(rtp);
3022 chan->fds[1] = ast_rtcp_fd(rtp);
3023 ast_channel_unlock(chan);
3025 /* Restore callback mode if previously used */
3026 if (ast_test_flag(rtp, FLAG_CALLBACK_MODE))
3027 rtp->ioid = ast_io_add(rtp->io, ast_rtp_fd(rtp), rtpread, AST_IO_IN, rtp);
3032 /*! \brief Bridge loop for partial native bridge (packet2packet)
3034 In p2p mode, Asterisk is a very basic RTP proxy, just forwarding whatever
3035 rtp/rtcp we get in to the channel.
3036 \note this currently only works for Audio
3038 static enum ast_bridge_result bridge_p2p_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp *p0, struct ast_rtp *p1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
3040 struct ast_frame *fr = NULL;
3041 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
3042 int *p0_iod[2] = {NULL, NULL}, *p1_iod[2] = {NULL, NULL};
3043 int p0_callback = 0, p1_callback = 0;
3044 enum ast_bridge_result res = AST_BRIDGE_FAILED;
3046 /* Okay, setup each RTP structure to do P2P forwarding */
3047 ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
3049 ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
3052 /* Activate callback modes if possible */
3053 p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
3054 p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
3056 /* Now let go of the channel locks and be on our way */
3057 ast_channel_unlock(c0);
3058 ast_channel_unlock(c1);
3060 /* Go into a loop forwarding frames until we don't need to anymore */
3065 /* Check if anything changed */
3066 if ((c0->tech_pvt != pvt0) ||
3067 (c1->tech_pvt != pvt1) ||
3068 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
3069 if (option_debug > 2)
3070 ast_log(LOG_DEBUG, "p2p-rtp-bridge: Oooh, something is weird, backing out\n");
3071 res = AST_BRIDGE_RETRY;
3074 /* Wait on a channel to feed us a frame */
3075 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
3077 res = AST_BRIDGE_RETRY;
3080 if (option_debug > 2)
3081 ast_log(LOG_NOTICE, "p2p-rtp-bridge: Ooh, empty read...\n");
3082 if (ast_check_hangup(c0) || ast_check_hangup(c1))
3086 /* Read in frame from channel */
3088 other = (who == c0) ? c1 : c0;
3089 /* Depending on the frame we may need to break out of our bridge */
3090 if (!fr || ((fr->frametype == AST_FRAME_DTMF) &&
3091 ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
3092 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
3093 /* Record received frame and who */
3096 if (option_debug > 2)
3097 ast_log(LOG_DEBUG, "p2p-rtp-bridge: Ooh, got a %s\n", fr ? "digit" : "hangup");
3098 res = AST_BRIDGE_COMPLETE;
3100 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3101 if ((fr->subclass == AST_CONTROL_HOLD) ||
3102 (fr->subclass == AST_CONTROL_UNHOLD) ||
3103 (fr->subclass == AST_CONTROL_VIDUPDATE)) {
3104 /* If we are going on hold, then break callback mode and P2P bridging */
3105 if (fr->subclass == AST_CONTROL_HOLD) {
3107 p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
3109 p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
3112 } else if (fr->subclass == AST_CONTROL_UNHOLD) {
3113 /* If we are off hold, then go back to callback mode and P2P bridging */
3114 ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
3116 ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
3118 p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
3119 p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
3121 ast_indicate(other, fr->subclass);
3126 if (option_debug > 2)
3127 ast_log(LOG_DEBUG, "p2p-rtp-bridge: Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
3128 res = AST_BRIDGE_COMPLETE;
3132 /* If this is a DTMF, voice, or video frame write it to the other channel */
3133 if ((fr->frametype == AST_FRAME_DTMF) ||
3134 (fr->frametype == AST_FRAME_VOICE) ||
3135 (fr->frametype == AST_FRAME_VIDEO)) {
3136 ast_write(other, fr);
3146 /* If we are totally avoiding the core, then restore our link to it */
3148 p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
3150 p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
3152 /* Break out of the direct bridge */
3159 /*! \brief Bridge calls. If possible and allowed, initiate
3160 re-invite so the peers exchange media directly outside
3163 /*! \page AstRTPbridge The Asterisk RTP bridge