Optionally display the value of several variables within the Status command.
[asterisk-bristuff.git] / main / rtp.c
blob64080a92d20e6be6f780fb82601186437069352c
1 /*
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.
19 /*!
20 * \file
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.
29 #include "asterisk.h"
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
33 #include <sys/time.h>
34 #include <signal.h>
35 #include <fcntl.h>
37 #include "asterisk/rtp.h"
38 #include "asterisk/frame.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/acl.h"
41 #include "asterisk/config.h"
42 #include "asterisk/lock.h"
43 #include "asterisk/utils.h"
44 #include "asterisk/netsock.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/manager.h"
47 #include "asterisk/unaligned.h"
49 #define MAX_TIMESTAMP_SKEW 640
51 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
52 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
53 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
54 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
56 #define RTCP_PT_FUR 192
57 #define RTCP_PT_SR 200
58 #define RTCP_PT_RR 201
59 #define RTCP_PT_SDES 202
60 #define RTCP_PT_BYE 203
61 #define RTCP_PT_APP 204
63 #define RTP_MTU 1200
65 #define DEFAULT_DTMF_TIMEOUT 3000 /*!< samples */
67 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
69 static int rtpstart; /*!< First port for RTP sessions (set in rtp.conf) */
70 static int rtpend; /*!< Last port for RTP sessions (set in rtp.conf) */
71 static int rtpdebug; /*!< Are we debugging? */
72 static int rtcpdebug; /*!< Are we debugging RTCP? */
73 static int rtcpstats; /*!< Are we debugging RTCP? */
74 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
75 static int stundebug; /*!< Are we debugging stun? */
76 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
77 static struct sockaddr_in rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
78 #ifdef SO_NO_CHECK
79 static int nochecksums;
80 #endif
81 static int strictrtp;
83 enum strict_rtp_state {
84 STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
85 STRICT_RTP_LEARN, /*! Accept next packet as source */
86 STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
89 /* Uncomment this to enable more intense native bridging, but note: this is currently buggy */
90 /* #define P2P_INTENSE */
92 /*!
93 * \brief Structure representing a RTP session.
95 * 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 [...]"
98 /*! \brief The value of each payload format mapping: */
99 struct rtpPayloadType {
100 int isAstFormat; /*!< whether the following code is an AST_FORMAT */
101 int code;
105 /*! \brief RTP session description */
106 struct ast_rtp {
107 int s;
108 struct ast_frame f;
109 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
110 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
111 unsigned int themssrc; /*!< Their SSRC */
112 unsigned int rxssrc;
113 unsigned int lastts;
114 unsigned int lastrxts;
115 unsigned int lastividtimestamp;
116 unsigned int lastovidtimestamp;
117 unsigned int lastitexttimestamp;
118 unsigned int lastotexttimestamp;
119 unsigned int lasteventseqn;
120 int lastrxseqno; /*!< Last received sequence number */
121 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
122 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
123 unsigned int rxcount; /*!< How many packets have we received? */
124 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
125 unsigned int txcount; /*!< How many packets have we sent? */
126 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
127 unsigned int cycles; /*!< Shifted count of sequence number cycles */
128 double rxjitter; /*!< Interarrival jitter at the moment */
129 double rxtransit; /*!< Relative transit time for previous packet */
130 int lasttxformat;
131 int lastrxformat;
133 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
134 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
135 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
137 /* DTMF Reception Variables */
138 char resp;
139 unsigned int lastevent;
140 int dtmfcount;
141 unsigned int dtmfsamples;
142 /* DTMF Transmission Variables */
143 unsigned int lastdigitts;
144 char sending_digit; /*!< boolean - are we sending digits */
145 char send_digit; /*!< digit we are sending */
146 int send_payload;
147 int send_duration;
148 int nat;
149 unsigned int flags;
150 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
151 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
152 struct timeval rxcore;
153 struct timeval txcore;
154 double drxcore; /*!< The double representation of the first received packet */
155 struct timeval lastrx; /*!< timeval when we last received a packet */
156 struct timeval dtmfmute;
157 struct ast_smoother *smoother;
158 int *ioid;
159 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
160 unsigned short rxseqno;
161 struct sched_context *sched;
162 struct io_context *io;
163 void *data;
164 ast_rtp_callback callback;
165 #ifdef P2P_INTENSE
166 ast_mutex_t bridge_lock;
167 #endif
168 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
169 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
170 int rtp_lookup_code_cache_code;
171 int rtp_lookup_code_cache_result;
172 struct ast_rtcp *rtcp;
173 struct ast_codec_pref pref;
174 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
176 enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
177 struct sockaddr_in strict_rtp_address; /*!< Remote address information for strict RTP purposes */
179 int set_marker_bit:1; /*!< Whether to set the marker bit or not */
182 /* Forward declarations */
183 static int ast_rtcp_write(const void *data);
184 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
185 static int ast_rtcp_write_sr(const void *data);
186 static int ast_rtcp_write_rr(const void *data);
187 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
188 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
189 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
191 #define FLAG_3389_WARNING (1 << 0)
192 #define FLAG_NAT_ACTIVE (3 << 1)
193 #define FLAG_NAT_INACTIVE (0 << 1)
194 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
195 #define FLAG_HAS_DTMF (1 << 3)
196 #define FLAG_P2P_SENT_MARK (1 << 4)
197 #define FLAG_P2P_NEED_DTMF (1 << 5)
198 #define FLAG_CALLBACK_MODE (1 << 6)
199 #define FLAG_DTMF_COMPENSATE (1 << 7)
200 #define FLAG_HAS_STUN (1 << 8)
203 * \brief Structure defining an RTCP session.
205 * The concept "RTCP session" is not defined in RFC 3550, but since
206 * this structure is analogous to ast_rtp, which tracks a RTP session,
207 * it is logical to think of this as a RTCP session.
209 * RTCP packet is defined on page 9 of RFC 3550.
212 struct ast_rtcp {
213 int s; /*!< Socket */
214 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
215 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
216 unsigned int soc; /*!< What they told us */
217 unsigned int spc; /*!< What they told us */
218 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
219 struct timeval rxlsr; /*!< Time when we got their last SR */
220 struct timeval txlsr; /*!< Time when we sent or last SR*/
221 unsigned int expected_prior; /*!< no. packets in previous interval */
222 unsigned int received_prior; /*!< no. packets received in previous interval */
223 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
224 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
225 unsigned int sr_count; /*!< number of SRs we've sent */
226 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
227 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
228 double rtt; /*!< Last reported rtt */
229 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
230 unsigned int reported_lost; /*!< Reported lost packets in their RR */
231 char quality[AST_MAX_USER_FIELD];
232 double maxrxjitter;
233 double minrxjitter;
234 double maxrtt;
235 double minrtt;
236 int sendfur;
240 * \brief STUN support code
242 * This code provides some support for doing STUN transactions.
243 * Eventually it should be moved elsewhere as other protocols
244 * than RTP can benefit from it - e.g. SIP.
245 * STUN is described in RFC3489 and it is based on the exchange
246 * of UDP packets between a client and one or more servers to
247 * determine the externally visible address (and port) of the client
248 * once it has gone through the NAT boxes that connect it to the
249 * outside.
250 * The simplest request packet is just the header defined in
251 * struct stun_header, and from the response we may just look at
252 * one attribute, STUN_MAPPED_ADDRESS, that we find in the response.
253 * By doing more transactions with different server addresses we
254 * may determine more about the behaviour of the NAT boxes, of
255 * course - the details are in the RFC.
257 * All STUN packets start with a simple header made of a type,
258 * length (excluding the header) and a 16-byte random transaction id.
259 * Following the header we may have zero or more attributes, each
260 * structured as a type, length and a value (whose format depends
261 * on the type, but often contains addresses).
262 * Of course all fields are in network format.
265 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
267 struct stun_header {
268 unsigned short msgtype;
269 unsigned short msglen;
270 stun_trans_id id;
271 unsigned char ies[0];
272 } __attribute__((packed));
274 struct stun_attr {
275 unsigned short attr;
276 unsigned short len;
277 unsigned char value[0];
278 } __attribute__((packed));
281 * The format normally used for addresses carried by STUN messages.
283 struct stun_addr {
284 unsigned char unused;
285 unsigned char family;
286 unsigned short port;
287 unsigned int addr;
288 } __attribute__((packed));
290 #define STUN_IGNORE (0)
291 #define STUN_ACCEPT (1)
293 /*! \brief STUN message types
294 * 'BIND' refers to transactions used to determine the externally
295 * visible addresses. 'SEC' refers to transactions used to establish
296 * a session key for subsequent requests.
297 * 'SEC' functionality is not supported here.
300 #define STUN_BINDREQ 0x0001
301 #define STUN_BINDRESP 0x0101
302 #define STUN_BINDERR 0x0111
303 #define STUN_SECREQ 0x0002
304 #define STUN_SECRESP 0x0102
305 #define STUN_SECERR 0x0112
307 /*! \brief Basic attribute types in stun messages.
308 * Messages can also contain custom attributes (codes above 0x7fff)
310 #define STUN_MAPPED_ADDRESS 0x0001
311 #define STUN_RESPONSE_ADDRESS 0x0002
312 #define STUN_CHANGE_REQUEST 0x0003
313 #define STUN_SOURCE_ADDRESS 0x0004
314 #define STUN_CHANGED_ADDRESS 0x0005
315 #define STUN_USERNAME 0x0006
316 #define STUN_PASSWORD 0x0007
317 #define STUN_MESSAGE_INTEGRITY 0x0008
318 #define STUN_ERROR_CODE 0x0009
319 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
320 #define STUN_REFLECTED_FROM 0x000b
322 /*! \brief helper function to print message names */
323 static const char *stun_msg2str(int msg)
325 switch (msg) {
326 case STUN_BINDREQ:
327 return "Binding Request";
328 case STUN_BINDRESP:
329 return "Binding Response";
330 case STUN_BINDERR:
331 return "Binding Error Response";
332 case STUN_SECREQ:
333 return "Shared Secret Request";
334 case STUN_SECRESP:
335 return "Shared Secret Response";
336 case STUN_SECERR:
337 return "Shared Secret Error Response";
339 return "Non-RFC3489 Message";
342 /*! \brief helper function to print attribute names */
343 static const char *stun_attr2str(int msg)
345 switch (msg) {
346 case STUN_MAPPED_ADDRESS:
347 return "Mapped Address";
348 case STUN_RESPONSE_ADDRESS:
349 return "Response Address";
350 case STUN_CHANGE_REQUEST:
351 return "Change Request";
352 case STUN_SOURCE_ADDRESS:
353 return "Source Address";
354 case STUN_CHANGED_ADDRESS:
355 return "Changed Address";
356 case STUN_USERNAME:
357 return "Username";
358 case STUN_PASSWORD:
359 return "Password";
360 case STUN_MESSAGE_INTEGRITY:
361 return "Message Integrity";
362 case STUN_ERROR_CODE:
363 return "Error Code";
364 case STUN_UNKNOWN_ATTRIBUTES:
365 return "Unknown Attributes";
366 case STUN_REFLECTED_FROM:
367 return "Reflected From";
369 return "Non-RFC3489 Attribute";
372 /*! \brief here we store credentials extracted from a message */
373 struct stun_state {
374 const char *username;
375 const char *password;
378 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
380 if (stundebug)
381 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
382 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
383 switch (ntohs(attr->attr)) {
384 case STUN_USERNAME:
385 state->username = (const char *) (attr->value);
386 break;
387 case STUN_PASSWORD:
388 state->password = (const char *) (attr->value);
389 break;
390 default:
391 if (stundebug)
392 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
393 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
395 return 0;
398 /*! \brief append a string to an STUN message */
399 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
401 int size = sizeof(**attr) + strlen(s);
402 if (*left > size) {
403 (*attr)->attr = htons(attrval);
404 (*attr)->len = htons(strlen(s));
405 memcpy((*attr)->value, s, strlen(s));
406 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
407 *len += size;
408 *left -= size;
412 /*! \brief append an address to an STUN message */
413 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
415 int size = sizeof(**attr) + 8;
416 struct stun_addr *addr;
417 if (*left > size) {
418 (*attr)->attr = htons(attrval);
419 (*attr)->len = htons(8);
420 addr = (struct stun_addr *)((*attr)->value);
421 addr->unused = 0;
422 addr->family = 0x01;
423 addr->port = sin->sin_port;
424 addr->addr = sin->sin_addr.s_addr;
425 (*attr) = (struct stun_attr *)((*attr)->value + 8);
426 *len += size;
427 *left -= size;
431 /*! \brief wrapper to send an STUN message */
432 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
434 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
435 (struct sockaddr *)dst, sizeof(*dst));
438 /*! \brief helper function to generate a random request id */
439 static void stun_req_id(struct stun_header *req)
441 int x;
442 for (x = 0; x < 4; x++)
443 req->id.id[x] = ast_random();
446 size_t ast_rtp_alloc_size(void)
448 return sizeof(struct ast_rtp);
451 /*! \brief callback type to be invoked on stun responses. */
452 typedef int (stun_cb_f)(struct stun_attr *attr, void *arg);
454 /*! \brief handle an incoming STUN message.
456 * Do some basic sanity checks on packet size and content,
457 * try to extract a bit of information, and possibly reply.
458 * At the moment this only processes BIND requests, and returns
459 * the externally visible address of the request.
460 * If a callback is specified, invoke it with the attribute.
462 static int stun_handle_packet(int s, struct sockaddr_in *src,
463 unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
465 struct stun_header *hdr = (struct stun_header *)data;
466 struct stun_attr *attr;
467 struct stun_state st;
468 int ret = STUN_IGNORE;
469 int x;
471 /* On entry, 'len' is the length of the udp payload. After the
472 * initial checks it becomes the size of unprocessed options,
473 * while 'data' is advanced accordingly.
475 if (len < sizeof(struct stun_header)) {
476 ast_debug(1, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
477 return -1;
479 len -= sizeof(struct stun_header);
480 data += sizeof(struct stun_header);
481 x = ntohs(hdr->msglen); /* len as advertised in the message */
482 if (stundebug)
483 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), x);
484 if (x > len) {
485 ast_debug(1, "Scrambled STUN packet length (got %d, expecting %d)\n", x, (int)len);
486 } else
487 len = x;
488 memset(&st, 0, sizeof(st));
489 while (len) {
490 if (len < sizeof(struct stun_attr)) {
491 ast_debug(1, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
492 break;
494 attr = (struct stun_attr *)data;
495 /* compute total attribute length */
496 x = ntohs(attr->len) + sizeof(struct stun_attr);
497 if (x > len) {
498 ast_debug(1, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x, (int)len);
499 break;
501 if (stun_cb)
502 stun_cb(attr, arg);
503 if (stun_process_attr(&st, attr)) {
504 ast_debug(1, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
505 break;
507 /* Clear attribute id: in case previous entry was a string,
508 * this will act as the terminator for the string.
510 attr->attr = 0;
511 data += x;
512 len -= x;
514 /* Null terminate any string.
515 * XXX NOTE, we write past the size of the buffer passed by the
516 * caller, so this is potentially dangerous. The only thing that
517 * saves us is that usually we read the incoming message in a
518 * much larger buffer in the struct ast_rtp
520 *data = '\0';
522 /* Now prepare to generate a reply, which at the moment is done
523 * only for properly formed (len == 0) STUN_BINDREQ messages.
525 if (len == 0) {
526 unsigned char respdata[1024];
527 struct stun_header *resp = (struct stun_header *)respdata;
528 int resplen = 0; /* len excluding header */
529 int respleft = sizeof(respdata) - sizeof(struct stun_header);
531 resp->id = hdr->id;
532 resp->msgtype = 0;
533 resp->msglen = 0;
534 attr = (struct stun_attr *)resp->ies;
535 switch (ntohs(hdr->msgtype)) {
536 case STUN_BINDREQ:
537 if (stundebug)
538 ast_verbose("STUN Bind Request, username: %s\n",
539 st.username ? st.username : "<none>");
540 if (st.username)
541 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
542 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
543 resp->msglen = htons(resplen);
544 resp->msgtype = htons(STUN_BINDRESP);
545 stun_send(s, src, resp);
546 ret = STUN_ACCEPT;
547 break;
548 default:
549 if (stundebug)
550 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
553 return ret;
556 /*! \brief Extract the STUN_MAPPED_ADDRESS from the stun response.
557 * This is used as a callback for stun_handle_response
558 * when called from ast_stun_request.
560 static int stun_get_mapped(struct stun_attr *attr, void *arg)
562 struct stun_addr *addr = (struct stun_addr *)(attr + 1);
563 struct sockaddr_in *sa = (struct sockaddr_in *)arg;
565 if (ntohs(attr->attr) != STUN_MAPPED_ADDRESS || ntohs(attr->len) != 8)
566 return 1; /* not us. */
567 sa->sin_port = addr->port;
568 sa->sin_addr.s_addr = addr->addr;
569 return 0;
572 /*! \brief Generic STUN request
573 * Send a generic stun request to the server specified,
574 * possibly waiting for a reply and filling the 'reply' field with
575 * the externally visible address. Note that in this case the request
576 * will be blocking.
577 * (Note, the interface may change slightly in the future).
579 * \param s the socket used to send the request
580 * \param dst the address of the STUN server
581 * \param username if non null, add the username in the request
582 * \param answer if non null, the function waits for a response and
583 * puts here the externally visible address.
584 * \return 0 on success, other values on error.
586 int ast_stun_request(int s, struct sockaddr_in *dst,
587 const char *username, struct sockaddr_in *answer)
589 struct stun_header *req;
590 unsigned char reqdata[1024];
591 int reqlen, reqleft;
592 struct stun_attr *attr;
593 int res = 0;
594 int retry;
596 req = (struct stun_header *)reqdata;
597 stun_req_id(req);
598 reqlen = 0;
599 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
600 req->msgtype = 0;
601 req->msglen = 0;
602 attr = (struct stun_attr *)req->ies;
603 if (username)
604 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
605 req->msglen = htons(reqlen);
606 req->msgtype = htons(STUN_BINDREQ);
607 for (retry = 0; retry < 3; retry++) { /* XXX make retries configurable */
608 /* send request, possibly wait for reply */
609 unsigned char reply_buf[1024];
610 fd_set rfds;
611 struct timeval to = { 3, 0 }; /* timeout, make it configurable */
612 struct sockaddr_in src;
613 socklen_t srclen;
615 res = stun_send(s, dst, req);
616 if (res < 0) {
617 ast_log(LOG_WARNING, "ast_stun_request send #%d failed error %d, retry\n",
618 retry, res);
619 continue;
621 if (answer == NULL)
622 break;
623 FD_ZERO(&rfds);
624 FD_SET(s, &rfds);
625 res = ast_select(s + 1, &rfds, NULL, NULL, &to);
626 if (res <= 0) /* timeout or error */
627 continue;
628 bzero(&src, sizeof(src));
629 srclen = sizeof(src);
630 /* XXX pass -1 in the size, because stun_handle_packet might
631 * write past the end of the buffer.
633 res = recvfrom(s, reply_buf, sizeof(reply_buf) - 1,
634 0, (struct sockaddr *)&src, &srclen);
635 if (res < 0) {
636 ast_log(LOG_WARNING, "ast_stun_request recvfrom #%d failed error %d, retry\n",
637 retry, res);
638 continue;
640 bzero(answer, sizeof(struct sockaddr_in));
641 stun_handle_packet(s, &src, reply_buf, res,
642 stun_get_mapped, answer);
643 res = 0; /* signal regular exit */
644 break;
646 return res;
649 /*! \brief send a STUN BIND request to the given destination.
650 * Optionally, add a username if specified.
652 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
654 ast_stun_request(rtp->s, suggestion, username, NULL);
657 /*! \brief List of current sessions */
658 static AST_RWLIST_HEAD_STATIC(protos, ast_rtp_protocol);
660 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
662 unsigned int sec, usec, frac;
663 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
664 usec = tv.tv_usec;
665 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
666 *msw = sec;
667 *lsw = frac;
670 int ast_rtp_fd(struct ast_rtp *rtp)
672 return rtp->s;
675 int ast_rtcp_fd(struct ast_rtp *rtp)
677 if (rtp->rtcp)
678 return rtp->rtcp->s;
679 return -1;
682 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
684 unsigned int interval;
685 /*! \todo XXX Do a more reasonable calculation on this one
686 * Look in RFC 3550 Section A.7 for an example*/
687 interval = rtcpinterval;
688 return interval;
691 /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
692 void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
694 rtp->rtptimeout = (-1) * rtp->rtptimeout;
695 rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
698 /*! \brief Set rtp timeout */
699 void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
701 rtp->rtptimeout = timeout;
704 /*! \brief Set rtp hold timeout */
705 void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
707 rtp->rtpholdtimeout = timeout;
710 /*! \brief set RTP keepalive interval */
711 void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
713 rtp->rtpkeepalive = period;
716 /*! \brief Get rtp timeout */
717 int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
719 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
720 return 0;
721 return rtp->rtptimeout;
724 /*! \brief Get rtp hold timeout */
725 int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
727 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
728 return 0;
729 return rtp->rtpholdtimeout;
732 /*! \brief Get RTP keepalive interval */
733 int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
735 return rtp->rtpkeepalive;
738 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
740 rtp->data = data;
743 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
745 rtp->callback = callback;
748 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
750 rtp->nat = nat;
753 int ast_rtp_getnat(struct ast_rtp *rtp)
755 return ast_test_flag(rtp, FLAG_NAT_ACTIVE);
758 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
760 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
763 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
765 ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
768 void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
770 ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
773 static void rtp_bridge_lock(struct ast_rtp *rtp)
775 #ifdef P2P_INTENSE
776 ast_mutex_lock(&rtp->bridge_lock);
777 #endif
778 return;
781 static void rtp_bridge_unlock(struct ast_rtp *rtp)
783 #ifdef P2P_INTENSE
784 ast_mutex_unlock(&rtp->bridge_lock);
785 #endif
786 return;
789 static struct ast_frame *send_dtmf(struct ast_rtp *rtp, enum ast_frame_type type)
791 if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
792 (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
793 ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
794 rtp->resp = 0;
795 rtp->dtmfsamples = 0;
796 return &ast_null_frame;
798 ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
799 if (rtp->resp == 'X') {
800 rtp->f.frametype = AST_FRAME_CONTROL;
801 rtp->f.subclass = AST_CONTROL_FLASH;
802 } else {
803 rtp->f.frametype = type;
804 rtp->f.subclass = rtp->resp;
806 rtp->f.datalen = 0;
807 rtp->f.samples = 0;
808 rtp->f.mallocd = 0;
809 rtp->f.src = "RTP";
810 return &rtp->f;
814 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
816 if (rtpdebug == 0)
817 return 0;
818 if (rtpdebugaddr.sin_addr.s_addr) {
819 if (((ntohs(rtpdebugaddr.sin_port) != 0)
820 && (rtpdebugaddr.sin_port != addr->sin_port))
821 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
822 return 0;
824 return 1;
827 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
829 if (rtcpdebug == 0)
830 return 0;
831 if (rtcpdebugaddr.sin_addr.s_addr) {
832 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
833 && (rtcpdebugaddr.sin_port != addr->sin_port))
834 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
835 return 0;
837 return 1;
841 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
843 unsigned int event;
844 char resp = 0;
845 struct ast_frame *f = NULL;
846 unsigned char seq;
847 unsigned int flags;
848 unsigned int power;
850 /* We should have at least 4 bytes in RTP data */
851 if (len < 4)
852 return f;
854 /* The format of Cisco RTP DTMF packet looks like next:
855 +0 - sequence number of DTMF RTP packet (begins from 1,
856 wrapped to 0)
857 +1 - set of flags
858 +1 (bit 0) - flaps by different DTMF digits delimited by audio
859 or repeated digit without audio???
860 +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
861 then falls to 0 at its end)
862 +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
863 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
864 by each new packet and thus provides some redudancy.
866 Sample of Cisco RTP DTMF packet is (all data in hex):
867 19 07 00 02 12 02 20 02
868 showing end of DTMF digit '2'.
870 The packets
871 27 07 00 02 0A 02 20 02
872 28 06 20 02 00 02 0A 02
873 shows begin of new digit '2' with very short pause (20 ms) after
874 previous digit '2'. Bit +1.0 flips at begin of new digit.
876 Cisco RTP DTMF packets comes as replacement of audio RTP packets
877 so its uses the same sequencing and timestamping rules as replaced
878 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
879 on audio framing parameters. Marker bit isn't used within stream of
880 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
881 are not sequential at borders between DTMF and audio streams,
884 seq = data[0];
885 flags = data[1];
886 power = data[2];
887 event = data[3] & 0x1f;
889 if (option_debug > 2 || rtpdebug)
890 ast_debug(0, "Cisco DTMF Digit: %02x (len=%d, seq=%d, flags=%02x, power=%d, history count=%d)\n", event, len, seq, flags, power, (len - 4) / 2);
891 if (event < 10) {
892 resp = '0' + event;
893 } else if (event < 11) {
894 resp = '*';
895 } else if (event < 12) {
896 resp = '#';
897 } else if (event < 16) {
898 resp = 'A' + (event - 12);
899 } else if (event < 17) {
900 resp = 'X';
902 if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
903 rtp->resp = resp;
904 /* Why we should care on DTMF compensation at reception? */
905 if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
906 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
907 rtp->dtmfsamples = 0;
909 } else if ((rtp->resp == resp) && !power) {
910 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
911 f->samples = rtp->dtmfsamples * 8;
912 rtp->resp = 0;
913 } else if (rtp->resp == resp)
914 rtp->dtmfsamples += 20 * 8;
915 rtp->dtmfcount = dtmftimeout;
916 return f;
919 /*!
920 * \brief Process RTP DTMF and events according to RFC 2833.
922 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
924 * \param rtp
925 * \param data
926 * \param len
927 * \param seqno
928 * \param timestamp
929 * \returns
931 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp)
933 unsigned int event;
934 unsigned int event_end;
935 unsigned int samples;
936 char resp = 0;
937 struct ast_frame *f = NULL;
939 /* Figure out event, event end, and samples */
940 event = ntohl(*((unsigned int *)(data)));
941 event >>= 24;
942 event_end = ntohl(*((unsigned int *)(data)));
943 event_end <<= 8;
944 event_end >>= 24;
945 samples = ntohl(*((unsigned int *)(data)));
946 samples &= 0xFFFF;
948 /* Print out debug if turned on */
949 if (rtpdebug || option_debug > 2)
950 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
952 /* Figure out what digit was pressed */
953 if (event < 10) {
954 resp = '0' + event;
955 } else if (event < 11) {
956 resp = '*';
957 } else if (event < 12) {
958 resp = '#';
959 } else if (event < 16) {
960 resp = 'A' + (event - 12);
961 } else if (event < 17) { /* Event 16: Hook flash */
962 resp = 'X';
963 } else {
964 /* Not a supported event */
965 ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
966 return &ast_null_frame;
969 if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
970 if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
971 rtp->resp = resp;
972 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
973 f->len = 0;
974 rtp->lastevent = timestamp;
976 } else {
977 if ((!(rtp->resp) && (!(event_end & 0x80))) || (rtp->resp && rtp->resp != resp)) {
978 rtp->resp = resp;
979 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
980 } else if ((event_end & 0x80) && (rtp->lastevent != seqno) && rtp->resp) {
981 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
982 f->len = ast_tvdiff_ms(ast_samp2tv(samples, 8000), ast_tv(0, 0)); /* XXX hard coded 8kHz */
983 rtp->resp = 0;
984 rtp->lastevent = seqno;
988 rtp->dtmfcount = dtmftimeout;
989 rtp->dtmfsamples = samples;
991 return f;
995 * \brief Process Comfort Noise RTP.
997 * This is incomplete at the moment.
1000 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
1002 struct ast_frame *f = NULL;
1003 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
1004 totally help us out becuase we don't have an engine to keep it going and we are not
1005 guaranteed to have it every 20ms or anything */
1006 if (rtpdebug)
1007 ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
1009 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
1010 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
1011 ast_inet_ntoa(rtp->them.sin_addr));
1012 ast_set_flag(rtp, FLAG_3389_WARNING);
1015 /* Must have at least one byte */
1016 if (!len)
1017 return NULL;
1018 if (len < 24) {
1019 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
1020 rtp->f.datalen = len - 1;
1021 rtp->f.offset = AST_FRIENDLY_OFFSET;
1022 memcpy(rtp->f.data, data + 1, len - 1);
1023 } else {
1024 rtp->f.data = NULL;
1025 rtp->f.offset = 0;
1026 rtp->f.datalen = 0;
1028 rtp->f.frametype = AST_FRAME_CNG;
1029 rtp->f.subclass = data[0] & 0x7f;
1030 rtp->f.datalen = len - 1;
1031 rtp->f.samples = 0;
1032 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
1033 f = &rtp->f;
1034 return f;
1037 static int rtpread(int *id, int fd, short events, void *cbdata)
1039 struct ast_rtp *rtp = cbdata;
1040 struct ast_frame *f;
1041 f = ast_rtp_read(rtp);
1042 if (f) {
1043 if (rtp->callback)
1044 rtp->callback(rtp, f, rtp->data);
1046 return 1;
1049 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
1051 socklen_t len;
1052 int position, i, packetwords;
1053 int res;
1054 struct sockaddr_in sin;
1055 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
1056 unsigned int *rtcpheader;
1057 int pt;
1058 struct timeval now;
1059 unsigned int length;
1060 int rc;
1061 double rttsec;
1062 uint64_t rtt = 0;
1063 unsigned int dlsr;
1064 unsigned int lsr;
1065 unsigned int msw;
1066 unsigned int lsw;
1067 unsigned int comp;
1068 struct ast_frame *f = &ast_null_frame;
1070 if (!rtp || !rtp->rtcp)
1071 return &ast_null_frame;
1073 len = sizeof(sin);
1075 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
1076 0, (struct sockaddr *)&sin, &len);
1077 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
1079 if (res < 0) {
1080 if (errno == EBADF)
1081 CRASH;
1082 if (errno != EAGAIN) {
1083 ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n", strerror(errno));
1084 return NULL;
1086 return &ast_null_frame;
1089 packetwords = res / 4;
1091 if (rtp->nat) {
1092 /* Send to whoever sent to us */
1093 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1094 (rtp->rtcp->them.sin_port != sin.sin_port)) {
1095 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1096 if (option_debug || rtpdebug)
1097 ast_debug(0, "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));
1101 ast_debug(1, "Got RTCP report of %d bytes\n", res);
1103 /* Process a compound packet */
1104 position = 0;
1105 while (position < packetwords) {
1106 i = position;
1107 length = ntohl(rtcpheader[i]);
1108 pt = (length & 0xff0000) >> 16;
1109 rc = (length & 0x1f000000) >> 24;
1110 length &= 0xffff;
1112 if ((i + length) > packetwords) {
1113 if (option_debug || rtpdebug)
1114 ast_log(LOG_DEBUG, "RTCP Read too short\n");
1115 return &ast_null_frame;
1118 if (rtcp_debug_test_addr(&sin)) {
1119 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1120 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
1121 ast_verbose("Reception reports: %d\n", rc);
1122 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
1125 i += 2; /* Advance past header and ssrc */
1127 switch (pt) {
1128 case RTCP_PT_SR:
1129 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
1130 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
1131 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
1132 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
1134 if (rtcp_debug_test_addr(&sin)) {
1135 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
1136 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
1137 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
1139 i += 5;
1140 if (rc < 1)
1141 break;
1142 /* Intentional fall through */
1143 case RTCP_PT_RR:
1144 /* Don't handle multiple reception reports (rc > 1) yet */
1145 /* Calculate RTT per RFC */
1146 gettimeofday(&now, NULL);
1147 timeval2ntp(now, &msw, &lsw);
1148 if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
1149 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
1150 lsr = ntohl(rtcpheader[i + 4]);
1151 dlsr = ntohl(rtcpheader[i + 5]);
1152 rtt = comp - lsr - dlsr;
1154 /* Convert end to end delay to usec (keeping the calculation in 64bit space)
1155 sess->ee_delay = (eedelay * 1000) / 65536; */
1156 if (rtt < 4294) {
1157 rtt = (rtt * 1000000) >> 16;
1158 } else {
1159 rtt = (rtt * 1000) >> 16;
1160 rtt *= 1000;
1162 rtt = rtt / 1000.;
1163 rttsec = rtt / 1000.;
1165 if (comp - dlsr >= lsr) {
1166 rtp->rtcp->accumulated_transit += rttsec;
1167 rtp->rtcp->rtt = rttsec;
1168 if (rtp->rtcp->maxrtt<rttsec)
1169 rtp->rtcp->maxrtt = rttsec;
1170 if (rtp->rtcp->minrtt>rttsec)
1171 rtp->rtcp->minrtt = rttsec;
1172 } else if (rtcp_debug_test_addr(&sin)) {
1173 ast_verbose("Internal RTCP NTP clock skew detected: "
1174 "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
1175 "diff=%d\n",
1176 lsr, comp, dlsr, dlsr / 65536,
1177 (dlsr % 65536) * 1000 / 65536,
1178 dlsr - (comp - lsr));
1182 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
1183 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
1184 if (rtcp_debug_test_addr(&sin)) {
1185 ast_verbose(" Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
1186 ast_verbose(" Packets lost so far: %d\n", rtp->rtcp->reported_lost);
1187 ast_verbose(" Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
1188 ast_verbose(" Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
1189 ast_verbose(" Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
1190 ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
1191 ast_verbose(" DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
1192 if (rtt)
1193 ast_verbose(" RTT: %lu(sec)\n", (unsigned long) rtt);
1195 if (rtt) {
1196 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From %s:%d\r\n"
1197 "PT: %d(%s)\r\n"
1198 "ReceptionReports: %d\r\n"
1199 "SenderSSRC: %u\r\n"
1200 "FractionLost: %ld\r\n"
1201 "PacketsLost: %d\r\n"
1202 "HighestSequence: %ld\r\n"
1203 "SequenceNumberCycles: %ld\r\n"
1204 "IAJitter: %u\r\n"
1205 "LastSR: %lu.%010lu\r\n"
1206 "DLSR: %4.4f(sec)\r\n"
1207 "RTT: %llu(sec)\r\n",
1208 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
1209 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1211 rtcpheader[i + 1],
1212 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1213 rtp->rtcp->reported_lost,
1214 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1215 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1216 rtp->rtcp->reported_jitter,
1217 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1218 ntohl(rtcpheader[i + 5])/65536.0,
1219 (unsigned long long)rtt);
1220 } else {
1221 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From %s:%d\r\n"
1222 "PT: %d(%s)\r\n"
1223 "ReceptionReports: %d\r\n"
1224 "SenderSSRC: %u\r\n"
1225 "FractionLost: %ld\r\n"
1226 "PacketsLost: %d\r\n"
1227 "HighestSequence: %ld\r\n"
1228 "SequenceNumberCycles: %ld\r\n"
1229 "IAJitter: %u\r\n"
1230 "LastSR: %lu.%010lu\r\n"
1231 "DLSR: %4.4f(sec)\r\n",
1232 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
1233 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1235 rtcpheader[i + 1],
1236 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1237 rtp->rtcp->reported_lost,
1238 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1239 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1240 rtp->rtcp->reported_jitter,
1241 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
1242 ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1243 ntohl(rtcpheader[i + 5])/65536.0);
1245 break;
1246 case RTCP_PT_FUR:
1247 if (rtcp_debug_test_addr(&sin))
1248 ast_verbose("Received an RTCP Fast Update Request\n");
1249 rtp->f.frametype = AST_FRAME_CONTROL;
1250 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
1251 rtp->f.datalen = 0;
1252 rtp->f.samples = 0;
1253 rtp->f.mallocd = 0;
1254 rtp->f.src = "RTP";
1255 f = &rtp->f;
1256 break;
1257 case RTCP_PT_SDES:
1258 if (rtcp_debug_test_addr(&sin))
1259 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1260 break;
1261 case RTCP_PT_BYE:
1262 if (rtcp_debug_test_addr(&sin))
1263 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1264 break;
1265 default:
1266 ast_debug(1, "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));
1267 break;
1269 position += (length + 1);
1272 return f;
1275 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
1277 struct timeval now;
1278 double transit;
1279 double current_time;
1280 double d;
1281 double dtv;
1282 double prog;
1284 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
1285 gettimeofday(&rtp->rxcore, NULL);
1286 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
1287 /* map timestamp to a real time */
1288 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
1289 rtp->rxcore.tv_sec -= timestamp / 8000;
1290 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
1291 /* Round to 0.1ms for nice, pretty timestamps */
1292 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
1293 if (rtp->rxcore.tv_usec < 0) {
1294 /* Adjust appropriately if necessary */
1295 rtp->rxcore.tv_usec += 1000000;
1296 rtp->rxcore.tv_sec -= 1;
1300 gettimeofday(&now,NULL);
1301 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
1302 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
1303 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
1304 if (tv->tv_usec >= 1000000) {
1305 tv->tv_usec -= 1000000;
1306 tv->tv_sec += 1;
1308 prog = (double)((timestamp-rtp->seedrxts)/8000.);
1309 dtv = (double)rtp->drxcore + (double)(prog);
1310 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
1311 transit = current_time - dtv;
1312 d = transit - rtp->rxtransit;
1313 rtp->rxtransit = transit;
1314 if (d<0)
1315 d=-d;
1316 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1317 if (rtp->rtcp && rtp->rxjitter > rtp->rtcp->maxrxjitter)
1318 rtp->rtcp->maxrxjitter = rtp->rxjitter;
1319 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1320 rtp->rtcp->minrxjitter = rtp->rxjitter;
1323 /*! \brief Perform a Packet2Packet RTP write */
1324 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, struct ast_rtp *bridged, unsigned int *rtpheader, int len, int hdrlen)
1326 int res = 0, payload = 0, bridged_payload = 0, mark;
1327 struct rtpPayloadType rtpPT;
1328 int reconstruct = ntohl(rtpheader[0]);
1330 /* Get fields from packet */
1331 payload = (reconstruct & 0x7f0000) >> 16;
1332 mark = (((reconstruct & 0x800000) >> 23) != 0);
1334 /* Check what the payload value should be */
1335 rtpPT = ast_rtp_lookup_pt(rtp, payload);
1337 /* If the payload coming in is not one of the negotiated ones then send it to the core, this will cause formats to change and the bridge to break */
1338 if (!bridged->current_RTP_PT[payload].code)
1339 return -1;
1341 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
1342 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
1343 return -1;
1345 /* Otherwise adjust bridged payload to match */
1346 bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
1348 /* If the mark bit has not been sent yet... do it now */
1349 if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
1350 mark = 1;
1351 ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
1354 /* Reconstruct part of the packet */
1355 reconstruct &= 0xFF80FFFF;
1356 reconstruct |= (bridged_payload << 16);
1357 reconstruct |= (mark << 23);
1358 rtpheader[0] = htonl(reconstruct);
1360 /* Send the packet back out */
1361 res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
1362 if (res < 0) {
1363 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1364 ast_debug(1, "RTP Transmission error of packet to %s:%d: %s\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), strerror(errno));
1365 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1366 if (option_debug || rtpdebug)
1367 ast_debug(0, "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));
1368 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1370 return 0;
1371 } else if (rtp_debug_test_addr(&bridged->them))
1372 ast_verbose("Sent RTP P2P packet to %s:%u (type %-2.2d, len %-6.6u)\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), bridged_payload, len - hdrlen);
1374 return 0;
1377 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
1379 int res;
1380 struct sockaddr_in sin;
1381 socklen_t len;
1382 unsigned int seqno;
1383 int version;
1384 int payloadtype;
1385 int hdrlen = 12;
1386 int padding;
1387 int mark;
1388 int ext;
1389 int cc;
1390 unsigned int ssrc;
1391 unsigned int timestamp;
1392 unsigned int *rtpheader;
1393 struct rtpPayloadType rtpPT;
1394 struct ast_rtp *bridged = NULL;
1396 /* If time is up, kill it */
1397 if (rtp->sending_digit)
1398 ast_rtp_senddigit_continuation(rtp);
1400 len = sizeof(sin);
1402 /* Cache where the header will go */
1403 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
1404 0, (struct sockaddr *)&sin, &len);
1406 /* If strict RTP protection is enabled see if we need to learn this address or if the packet should be dropped */
1407 if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
1408 /* Copy over address that this packet was received on */
1409 memcpy(&rtp->strict_rtp_address, &sin, sizeof(rtp->strict_rtp_address));
1410 /* Now move over to actually protecting the RTP port */
1411 rtp->strict_rtp_state = STRICT_RTP_CLOSED;
1412 ast_debug(1, "Learned remote address is %s:%d for strict RTP purposes, now protecting the port.\n", ast_inet_ntoa(rtp->strict_rtp_address.sin_addr), ntohs(rtp->strict_rtp_address.sin_port));
1413 } else if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
1414 /* If the address we previously learned doesn't match the address this packet came in on simply drop it */
1415 if ((rtp->strict_rtp_address.sin_addr.s_addr != sin.sin_addr.s_addr) || (rtp->strict_rtp_address.sin_port != sin.sin_port)) {
1416 ast_debug(1, "Received RTP packet from %s:%d, dropping due to strict RTP protection. Expected it to be from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), ast_inet_ntoa(rtp->strict_rtp_address.sin_addr), ntohs(rtp->strict_rtp_address.sin_port));
1417 return &ast_null_frame;
1421 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
1422 if (res < 0) {
1423 if (errno == EBADF)
1424 CRASH;
1425 if (errno != EAGAIN) {
1426 ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
1427 return NULL;
1429 return &ast_null_frame;
1432 if (res < hdrlen) {
1433 ast_log(LOG_WARNING, "RTP Read too short\n");
1434 return &ast_null_frame;
1437 /* Get fields */
1438 seqno = ntohl(rtpheader[0]);
1440 /* Check RTP version */
1441 version = (seqno & 0xC0000000) >> 30;
1442 if (!version) {
1443 /* If the two high bits are 0, this might be a
1444 * STUN message, so process it. stun_handle_packet()
1445 * answers to requests, and it returns STUN_ACCEPT
1446 * if the request is valid.
1448 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == STUN_ACCEPT) &&
1449 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
1450 memcpy(&rtp->them, &sin, sizeof(rtp->them));
1452 return &ast_null_frame;
1455 #if 0 /* Allow to receive RTP stream with closed transmission path */
1456 /* If we don't have the other side's address, then ignore this */
1457 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1458 return &ast_null_frame;
1459 #endif
1461 /* Send to whoever send to us if NAT is turned on */
1462 if (rtp->nat) {
1463 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1464 (rtp->them.sin_port != sin.sin_port)) {
1465 rtp->them = sin;
1466 if (rtp->rtcp) {
1467 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1468 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1470 rtp->rxseqno = 0;
1471 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1472 if (option_debug || rtpdebug)
1473 ast_debug(0, "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));
1477 /* If we are bridged to another RTP stream, send direct */
1478 if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
1479 return &ast_null_frame;
1481 if (version != 2)
1482 return &ast_null_frame;
1484 payloadtype = (seqno & 0x7f0000) >> 16;
1485 padding = seqno & (1 << 29);
1486 mark = seqno & (1 << 23);
1487 ext = seqno & (1 << 28);
1488 cc = (seqno & 0xF000000) >> 24;
1489 seqno &= 0xffff;
1490 timestamp = ntohl(rtpheader[1]);
1491 ssrc = ntohl(rtpheader[2]);
1493 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1494 if (option_debug || rtpdebug)
1495 ast_debug(0, "Forcing Marker bit, because SSRC has changed\n");
1496 mark = 1;
1499 rtp->rxssrc = ssrc;
1501 if (padding) {
1502 /* Remove padding bytes */
1503 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1506 if (cc) {
1507 /* CSRC fields present */
1508 hdrlen += cc*4;
1511 if (ext) {
1512 /* RTP Extension present */
1513 hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
1514 hdrlen += 4;
1515 if (option_debug) {
1516 int profile;
1517 profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
1518 if (profile == 0x505a)
1519 ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
1520 else
1521 ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
1525 if (res < hdrlen) {
1526 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1527 return &ast_null_frame;
1530 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1532 if (rtp->rxcount==1) {
1533 /* This is the first RTP packet successfully received from source */
1534 rtp->seedrxseqno = seqno;
1537 /* Do not schedule RR if RTCP isn't run */
1538 if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
1539 /* Schedule transmission of Receiver Report */
1540 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1542 if ( (int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
1543 rtp->cycles += RTP_SEQ_MOD;
1545 rtp->lastrxseqno = seqno;
1547 if (!rtp->themssrc)
1548 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1550 if (rtp_debug_test_addr(&sin))
1551 ast_verbose("Got RTP packet from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1552 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1554 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1555 if (!rtpPT.isAstFormat) {
1556 struct ast_frame *f = NULL;
1558 /* This is special in-band data that's not one of our codecs */
1559 if (rtpPT.code == AST_RTP_DTMF) {
1560 /* It's special -- rfc2833 process it */
1561 if (rtp_debug_test_addr(&sin)) {
1562 unsigned char *data;
1563 unsigned int event;
1564 unsigned int event_end;
1565 unsigned int duration;
1566 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1567 event = ntohl(*((unsigned int *)(data)));
1568 event >>= 24;
1569 event_end = ntohl(*((unsigned int *)(data)));
1570 event_end <<= 8;
1571 event_end >>= 24;
1572 duration = ntohl(*((unsigned int *)(data)));
1573 duration &= 0xFFFF;
1574 ast_verbose("Got RTP RFC2833 from %s:%u (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);
1576 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp);
1577 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1578 /* It's really special -- process it the Cisco way */
1579 if (rtp->lastevent <= seqno || (rtp->lastevent >= 65530 && seqno <= 6)) {
1580 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1581 rtp->lastevent = seqno;
1583 } else if (rtpPT.code == AST_RTP_CN) {
1584 /* Comfort Noise */
1585 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1586 } else {
1587 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1589 return f ? f : &ast_null_frame;
1591 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1592 rtp->f.frametype = (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) ? AST_FRAME_VOICE : (rtp->f.subclass & AST_FORMAT_VIDEO_MASK) ? AST_FRAME_VIDEO : AST_FRAME_TEXT;
1594 if (!rtp->lastrxts)
1595 rtp->lastrxts = timestamp;
1597 rtp->rxseqno = seqno;
1599 /* Record received timestamp as last received now */
1600 rtp->lastrxts = timestamp;
1602 rtp->f.mallocd = 0;
1603 rtp->f.datalen = res - hdrlen;
1604 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1605 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1606 rtp->f.seqno = seqno;
1607 if (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) {
1608 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1609 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1610 ast_frame_byteswap_be(&rtp->f);
1611 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1612 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1613 ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
1614 rtp->f.ts = timestamp / 8;
1615 rtp->f.len = rtp->f.samples / ( (ast_format_rate(rtp->f.subclass) == 16000) ? 16 : 8 );
1616 } else if(rtp->f.subclass & AST_FORMAT_VIDEO_MASK) {
1617 /* Video -- samples is # of samples vs. 90000 */
1618 if (!rtp->lastividtimestamp)
1619 rtp->lastividtimestamp = timestamp;
1620 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1621 rtp->lastividtimestamp = timestamp;
1622 rtp->f.delivery.tv_sec = 0;
1623 rtp->f.delivery.tv_usec = 0;
1624 /* Pass the RTP marker bit as bit 0 in the subclass field.
1625 * This is ok because subclass is actually a bitmask, and
1626 * the low bits represent audio formats, that are not
1627 * involved here since we deal with video.
1629 if (mark)
1630 rtp->f.subclass |= 0x1;
1631 } else {
1632 /* TEXT -- samples is # of samples vs. 1000 */
1633 if (!rtp->lastitexttimestamp)
1634 rtp->lastitexttimestamp = timestamp;
1635 rtp->f.samples = timestamp - rtp->lastitexttimestamp;
1636 rtp->lastitexttimestamp = timestamp;
1637 rtp->f.delivery.tv_sec = 0;
1638 rtp->f.delivery.tv_usec = 0;
1640 rtp->f.src = "RTP";
1641 return &rtp->f;
1644 /* The following array defines the MIME Media type (and subtype) for each
1645 of our codecs, or RTP-specific data type. */
1646 static struct {
1647 struct rtpPayloadType payloadType;
1648 char* type;
1649 char* subtype;
1650 } mimeTypes[] = {
1651 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1652 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1653 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1654 {{1, AST_FORMAT_ULAW}, "audio", "G711U"},
1655 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1656 {{1, AST_FORMAT_ALAW}, "audio", "G711A"},
1657 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1658 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1659 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1660 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1661 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1662 {{1, AST_FORMAT_G729A}, "audio", "G729A"},
1663 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1664 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1665 {{1, AST_FORMAT_G722}, "audio", "G722"},
1666 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
1667 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1668 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1669 {{0, AST_RTP_CN}, "audio", "CN"},
1670 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1671 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1672 {{1, AST_FORMAT_H261}, "video", "H261"},
1673 {{1, AST_FORMAT_H263}, "video", "H263"},
1674 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1675 {{1, AST_FORMAT_H264}, "video", "H264"},
1676 {{1, AST_FORMAT_MP4_VIDEO}, "video", "MP4V-ES"},
1677 {{1, AST_FORMAT_T140}, "text", "T140"},
1680 /*!
1681 * \brief Mapping between Asterisk codecs and rtp payload types
1683 * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1684 * also, our own choices for dynamic payload types. This is our master
1685 * table for transmission
1687 * See http://www.iana.org/assignments/rtp-parameters for a list of
1688 * assigned values
1690 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1691 [0] = {1, AST_FORMAT_ULAW},
1692 #ifdef USE_DEPRECATED_G726
1693 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1694 #endif
1695 [3] = {1, AST_FORMAT_GSM},
1696 [4] = {1, AST_FORMAT_G723_1},
1697 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1698 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1699 [7] = {1, AST_FORMAT_LPC10},
1700 [8] = {1, AST_FORMAT_ALAW},
1701 [9] = {1, AST_FORMAT_G722},
1702 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1703 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1704 [13] = {0, AST_RTP_CN},
1705 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1706 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1707 [18] = {1, AST_FORMAT_G729A},
1708 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1709 [26] = {1, AST_FORMAT_JPEG},
1710 [31] = {1, AST_FORMAT_H261},
1711 [34] = {1, AST_FORMAT_H263},
1712 [97] = {1, AST_FORMAT_ILBC},
1713 [98] = {1, AST_FORMAT_H263_PLUS},
1714 [99] = {1, AST_FORMAT_H264},
1715 [101] = {0, AST_RTP_DTMF},
1716 [102] = {1, AST_FORMAT_T140}, /* Real time text chat */
1717 [103] = {1, AST_FORMAT_H263_PLUS},
1718 [104] = {1, AST_FORMAT_MP4_VIDEO},
1719 [110] = {1, AST_FORMAT_SPEEX},
1720 [111] = {1, AST_FORMAT_G726},
1721 [112] = {1, AST_FORMAT_G726_AAL2},
1722 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1725 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1727 int i;
1729 if (!rtp)
1730 return;
1732 rtp_bridge_lock(rtp);
1734 for (i = 0; i < MAX_RTP_PT; ++i) {
1735 rtp->current_RTP_PT[i].isAstFormat = 0;
1736 rtp->current_RTP_PT[i].code = 0;
1739 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1740 rtp->rtp_lookup_code_cache_code = 0;
1741 rtp->rtp_lookup_code_cache_result = 0;
1743 rtp_bridge_unlock(rtp);
1746 void ast_rtp_pt_default(struct ast_rtp* rtp)
1748 int i;
1750 rtp_bridge_lock(rtp);
1752 /* Initialize to default payload types */
1753 for (i = 0; i < MAX_RTP_PT; ++i) {
1754 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1755 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1758 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1759 rtp->rtp_lookup_code_cache_code = 0;
1760 rtp->rtp_lookup_code_cache_result = 0;
1762 rtp_bridge_unlock(rtp);
1765 void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
1767 unsigned int i;
1769 rtp_bridge_lock(dest);
1770 rtp_bridge_lock(src);
1772 for (i = 0; i < MAX_RTP_PT; ++i) {
1773 dest->current_RTP_PT[i].isAstFormat =
1774 src->current_RTP_PT[i].isAstFormat;
1775 dest->current_RTP_PT[i].code =
1776 src->current_RTP_PT[i].code;
1778 dest->rtp_lookup_code_cache_isAstFormat = 0;
1779 dest->rtp_lookup_code_cache_code = 0;
1780 dest->rtp_lookup_code_cache_result = 0;
1782 rtp_bridge_unlock(src);
1783 rtp_bridge_unlock(dest);
1786 /*! \brief Get channel driver interface structure */
1787 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1789 struct ast_rtp_protocol *cur = NULL;
1791 AST_RWLIST_RDLOCK(&protos);
1792 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1793 if (cur->type == chan->tech->type)
1794 break;
1796 AST_RWLIST_UNLOCK(&protos);
1798 return cur;
1801 int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1803 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1804 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1805 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
1806 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1807 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED, text_dest_res = AST_RTP_GET_FAILED;
1808 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED, text_src_res = AST_RTP_GET_FAILED;
1809 int srccodec, destcodec, nat_active = 0;
1811 /* Lock channels */
1812 ast_channel_lock(c0);
1813 if (c1) {
1814 while (ast_channel_trylock(c1)) {
1815 ast_channel_unlock(c0);
1816 usleep(1);
1817 ast_channel_lock(c0);
1821 /* Find channel driver interfaces */
1822 destpr = get_proto(c0);
1823 if (c1)
1824 srcpr = get_proto(c1);
1825 if (!destpr) {
1826 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c0->name);
1827 ast_channel_unlock(c0);
1828 if (c1)
1829 ast_channel_unlock(c1);
1830 return -1;
1832 if (!srcpr) {
1833 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
1834 ast_channel_unlock(c0);
1835 if (c1)
1836 ast_channel_unlock(c1);
1837 return -1;
1840 /* Get audio, video and text interface (if native bridge is possible) */
1841 audio_dest_res = destpr->get_rtp_info(c0, &destp);
1842 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
1843 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(c0, &tdestp) : AST_RTP_GET_FAILED;
1844 if (srcpr) {
1845 audio_src_res = srcpr->get_rtp_info(c1, &srcp);
1846 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
1847 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(c1, &tsrcp) : AST_RTP_GET_FAILED;
1850 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1851 if (audio_dest_res != AST_RTP_TRY_NATIVE) {
1852 /* Somebody doesn't want to play... */
1853 ast_channel_unlock(c0);
1854 if (c1)
1855 ast_channel_unlock(c1);
1856 return -1;
1858 if (audio_src_res == AST_RTP_TRY_NATIVE && srcpr->get_codec)
1859 srccodec = srcpr->get_codec(c1);
1860 else
1861 srccodec = 0;
1862 if (audio_dest_res == AST_RTP_TRY_NATIVE && destpr->get_codec)
1863 destcodec = destpr->get_codec(c0);
1864 else
1865 destcodec = 0;
1866 /* Ensure we have at least one matching codec */
1867 if (!(srccodec & destcodec)) {
1868 ast_channel_unlock(c0);
1869 if (c1)
1870 ast_channel_unlock(c1);
1871 return 0;
1873 /* Consider empty media as non-existent */
1874 if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
1875 srcp = NULL;
1876 if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1877 nat_active = 1;
1878 /* Bridge media early */
1879 if (destpr->set_rtp_peer(c0, srcp, vsrcp, tsrcp, srccodec, nat_active))
1880 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1881 ast_channel_unlock(c0);
1882 if (c1)
1883 ast_channel_unlock(c1);
1884 ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1885 return 0;
1888 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1890 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1891 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1892 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
1893 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1894 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED, text_dest_res = AST_RTP_GET_FAILED;
1895 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED, text_src_res = AST_RTP_GET_FAILED;
1896 int srccodec, destcodec;
1898 /* Lock channels */
1899 ast_channel_lock(dest);
1900 while (ast_channel_trylock(src)) {
1901 ast_channel_unlock(dest);
1902 usleep(1);
1903 ast_channel_lock(dest);
1906 /* Find channel driver interfaces */
1907 if (!(destpr = get_proto(dest))) {
1908 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1909 ast_channel_unlock(dest);
1910 ast_channel_unlock(src);
1911 return 0;
1913 if (!(srcpr = get_proto(src))) {
1914 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", src->name);
1915 ast_channel_unlock(dest);
1916 ast_channel_unlock(src);
1917 return 0;
1920 /* Get audio and video interface (if native bridge is possible) */
1921 audio_dest_res = destpr->get_rtp_info(dest, &destp);
1922 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
1923 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(dest, &tdestp) : AST_RTP_GET_FAILED;
1924 audio_src_res = srcpr->get_rtp_info(src, &srcp);
1925 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
1926 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(src, &tsrcp) : AST_RTP_GET_FAILED;
1928 /* Ensure we have at least one matching codec */
1929 if (srcpr->get_codec)
1930 srccodec = srcpr->get_codec(src);
1931 else
1932 srccodec = 0;
1933 if (destpr->get_codec)
1934 destcodec = destpr->get_codec(dest);
1935 else
1936 destcodec = 0;
1938 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1939 if (audio_dest_res != AST_RTP_TRY_NATIVE || audio_src_res != AST_RTP_TRY_NATIVE || !(srccodec & destcodec)) {
1940 /* Somebody doesn't want to play... */
1941 ast_channel_unlock(dest);
1942 ast_channel_unlock(src);
1943 return 0;
1945 ast_rtp_pt_copy(destp, srcp);
1946 if (vdestp && vsrcp)
1947 ast_rtp_pt_copy(vdestp, vsrcp);
1948 if (tdestp && tsrcp)
1949 ast_rtp_pt_copy(tdestp, tsrcp);
1950 if (media) {
1951 /* Bridge early */
1952 if (destpr->set_rtp_peer(dest, srcp, vsrcp, tsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1953 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1955 ast_channel_unlock(dest);
1956 ast_channel_unlock(src);
1957 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1958 return 1;
1961 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1962 * By default, use the well-known value for this type (although it may
1963 * still be set to a different value by a subsequent "a=rtpmap:" line)
1965 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1967 if (pt < 0 || pt > MAX_RTP_PT || static_RTP_PT[pt].code == 0)
1968 return; /* bogus payload type */
1970 rtp_bridge_lock(rtp);
1971 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1972 rtp_bridge_unlock(rtp);
1975 /*! \brief remove setting from payload type list if the rtpmap header indicates
1976 an unknown media type */
1977 void ast_rtp_unset_m_type(struct ast_rtp* rtp, int pt)
1979 if (pt < 0 || pt > MAX_RTP_PT)
1980 return; /* bogus payload type */
1982 rtp_bridge_lock(rtp);
1983 rtp->current_RTP_PT[pt].isAstFormat = 0;
1984 rtp->current_RTP_PT[pt].code = 0;
1985 rtp_bridge_unlock(rtp);
1988 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1989 * an SDP "a=rtpmap:" line.
1990 * \return 0 if the MIME type was found and set, -1 if it wasn't found
1992 int ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
1993 char *mimeType, char *mimeSubtype,
1994 enum ast_rtp_options options)
1996 unsigned int i;
1997 int found = 0;
1999 if (pt < 0 || pt > MAX_RTP_PT)
2000 return -1; /* bogus payload type */
2002 rtp_bridge_lock(rtp);
2004 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
2005 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
2006 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
2007 found = 1;
2008 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
2009 if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
2010 mimeTypes[i].payloadType.isAstFormat &&
2011 (options & AST_RTP_OPT_G726_NONSTANDARD))
2012 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
2013 break;
2017 rtp_bridge_unlock(rtp);
2019 return (found ? 0 : -1);
2022 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
2023 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
2024 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
2025 int* astFormats, int* nonAstFormats)
2027 int pt;
2029 rtp_bridge_lock(rtp);
2031 *astFormats = *nonAstFormats = 0;
2032 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2033 if (rtp->current_RTP_PT[pt].isAstFormat) {
2034 *astFormats |= rtp->current_RTP_PT[pt].code;
2035 } else {
2036 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
2040 rtp_bridge_unlock(rtp);
2043 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
2045 struct rtpPayloadType result;
2047 result.isAstFormat = result.code = 0;
2049 if (pt < 0 || pt > MAX_RTP_PT)
2050 return result; /* bogus payload type */
2052 /* Start with negotiated codecs */
2053 rtp_bridge_lock(rtp);
2054 result = rtp->current_RTP_PT[pt];
2055 rtp_bridge_unlock(rtp);
2057 /* If it doesn't exist, check our static RTP type list, just in case */
2058 if (!result.code)
2059 result = static_RTP_PT[pt];
2061 return result;
2064 /*! \brief Looks up an RTP code out of our *static* outbound list */
2065 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
2067 int pt = 0;
2069 rtp_bridge_lock(rtp);
2071 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
2072 code == rtp->rtp_lookup_code_cache_code) {
2073 /* Use our cached mapping, to avoid the overhead of the loop below */
2074 pt = rtp->rtp_lookup_code_cache_result;
2075 rtp_bridge_unlock(rtp);
2076 return pt;
2079 /* Check the dynamic list first */
2080 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2081 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
2082 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2083 rtp->rtp_lookup_code_cache_code = code;
2084 rtp->rtp_lookup_code_cache_result = pt;
2085 rtp_bridge_unlock(rtp);
2086 return pt;
2090 /* Then the static list */
2091 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2092 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
2093 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2094 rtp->rtp_lookup_code_cache_code = code;
2095 rtp->rtp_lookup_code_cache_result = pt;
2096 rtp_bridge_unlock(rtp);
2097 return pt;
2101 rtp_bridge_unlock(rtp);
2103 return -1;
2106 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
2107 enum ast_rtp_options options)
2109 unsigned int i;
2111 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
2112 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
2113 if (isAstFormat &&
2114 (code == AST_FORMAT_G726_AAL2) &&
2115 (options & AST_RTP_OPT_G726_NONSTANDARD))
2116 return "G726-32";
2117 else
2118 return mimeTypes[i].subtype;
2122 return "";
2125 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
2126 const int isAstFormat, enum ast_rtp_options options)
2128 int format;
2129 unsigned len;
2130 char *end = buf;
2131 char *start = buf;
2133 if (!buf || !size)
2134 return NULL;
2136 snprintf(end, size, "0x%x (", capability);
2138 len = strlen(end);
2139 end += len;
2140 size -= len;
2141 start = end;
2143 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
2144 if (capability & format) {
2145 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
2147 snprintf(end, size, "%s|", name);
2148 len = strlen(end);
2149 end += len;
2150 size -= len;
2154 if (start == end)
2155 ast_copy_string(start, "nothing)", size);
2156 else if (size > 1)
2157 *(end -1) = ')';
2159 return buf;
2162 /*! \brief Open RTP or RTCP socket for a session.
2163 * Print a message on failure.
2165 static int rtp_socket(const char *type)
2167 int s = socket(AF_INET, SOCK_DGRAM, 0);
2168 if (s < 0) {
2169 if (type == NULL)
2170 type = "RTP/RTCP";
2171 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
2172 } else {
2173 long flags = fcntl(s, F_GETFL);
2174 fcntl(s, F_SETFL, flags | O_NONBLOCK);
2175 #ifdef SO_NO_CHECK
2176 if (nochecksums)
2177 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
2178 #endif
2180 return s;
2184 * \brief Initialize a new RTCP session.
2186 * \returns The newly initialized RTCP session.
2188 static struct ast_rtcp *ast_rtcp_new(void)
2190 struct ast_rtcp *rtcp;
2192 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
2193 return NULL;
2194 rtcp->s = rtp_socket("RTCP");
2195 rtcp->us.sin_family = AF_INET;
2196 rtcp->them.sin_family = AF_INET;
2197 rtcp->schedid = -1;
2199 if (rtcp->s < 0) {
2200 ast_free(rtcp);
2201 return NULL;
2204 return rtcp;
2208 * \brief Initialize a new RTP structure.
2211 void ast_rtp_new_init(struct ast_rtp *rtp)
2213 #ifdef P2P_INTENSE
2214 ast_mutex_init(&rtp->bridge_lock);
2215 #endif
2217 rtp->them.sin_family = AF_INET;
2218 rtp->us.sin_family = AF_INET;
2219 rtp->ssrc = ast_random();
2220 rtp->seqno = ast_random() & 0xffff;
2221 ast_set_flag(rtp, FLAG_HAS_DTMF);
2222 rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
2225 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
2227 struct ast_rtp *rtp;
2228 int x;
2229 int startplace;
2231 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
2232 return NULL;
2234 ast_rtp_new_init(rtp);
2236 rtp->s = rtp_socket("RTP");
2237 if (rtp->s < 0)
2238 goto fail;
2239 if (sched && rtcpenable) {
2240 rtp->sched = sched;
2241 rtp->rtcp = ast_rtcp_new();
2245 * Try to bind the RTP port, x, and possibly the RTCP port, x+1 as well.
2246 * Start from a random (even, by RTP spec) port number, and
2247 * iterate until success or no ports are available.
2248 * Note that the requirement of RTP port being even, or RTCP being the
2249 * next one, cannot be enforced in presence of a NAT box because the
2250 * mapping is not under our control.
2252 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
2253 x = x & ~1; /* make it an even number */
2254 startplace = x; /* remember the starting point */
2255 /* this is constant across the loop */
2256 rtp->us.sin_addr = addr;
2257 if (rtp->rtcp)
2258 rtp->rtcp->us.sin_addr = addr;
2259 for (;;) {
2260 rtp->us.sin_port = htons(x);
2261 if (!bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) {
2262 /* bind succeeded, if no rtcp then we are done */
2263 if (!rtp->rtcp)
2264 break;
2265 /* have rtcp, try to bind it */
2266 rtp->rtcp->us.sin_port = htons(x + 1);
2267 if (!bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us)))
2268 break; /* success again, we are really done */
2270 * RTCP bind failed, so close and recreate the
2271 * already bound RTP socket for the next round.
2273 close(rtp->s);
2274 rtp->s = rtp_socket("RTP");
2275 if (rtp->s < 0)
2276 goto fail;
2279 * If we get here, there was an error in one of the bind()
2280 * calls, so make sure it is nothing unexpected.
2282 if (errno != EADDRINUSE) {
2283 /* We got an error that wasn't expected, abort! */
2284 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
2285 goto fail;
2288 * One of the ports is in use. For the next iteration,
2289 * increment by two and handle wraparound.
2290 * If we reach the starting point, then declare failure.
2292 x += 2;
2293 if (x > rtpend)
2294 x = (rtpstart + 1) & ~1;
2295 if (x == startplace) {
2296 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
2297 goto fail;
2300 rtp->sched = sched;
2301 rtp->io = io;
2302 if (callbackmode) {
2303 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
2304 ast_set_flag(rtp, FLAG_CALLBACK_MODE);
2306 ast_rtp_pt_default(rtp);
2307 return rtp;
2309 fail:
2310 if (rtp->s >= 0)
2311 close(rtp->s);
2312 if (rtp->rtcp) {
2313 close(rtp->rtcp->s);
2314 ast_free(rtp->rtcp);
2316 ast_free(rtp);
2317 return NULL;
2320 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
2322 struct in_addr ia;
2324 memset(&ia, 0, sizeof(ia));
2325 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
2328 int ast_rtp_setqos(struct ast_rtp *rtp, int tos, int cos, char *desc)
2330 return ast_netsock_set_qos(rtp->s, tos, cos, desc);
2333 void ast_rtp_new_source(struct ast_rtp *rtp)
2335 rtp->set_marker_bit = 1;
2336 return;
2339 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2341 rtp->them.sin_port = them->sin_port;
2342 rtp->them.sin_addr = them->sin_addr;
2343 if (rtp->rtcp) {
2344 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
2345 rtp->rtcp->them.sin_addr = them->sin_addr;
2347 rtp->rxseqno = 0;
2348 /* If strict RTP protection is enabled switch back to the learn state so we don't drop packets from above */
2349 if (strictrtp)
2350 rtp->strict_rtp_state = STRICT_RTP_LEARN;
2353 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2355 if ((them->sin_family != AF_INET) ||
2356 (them->sin_port != rtp->them.sin_port) ||
2357 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
2358 them->sin_family = AF_INET;
2359 them->sin_port = rtp->them.sin_port;
2360 them->sin_addr = rtp->them.sin_addr;
2361 return 1;
2363 return 0;
2366 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
2368 *us = rtp->us;
2371 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
2373 struct ast_rtp *bridged = NULL;
2375 rtp_bridge_lock(rtp);
2376 bridged = rtp->bridged;
2377 rtp_bridge_unlock(rtp);
2379 return bridged;
2382 void ast_rtp_stop(struct ast_rtp *rtp)
2384 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2386 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
2387 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
2388 if (rtp->rtcp) {
2389 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
2390 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
2393 ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
2396 void ast_rtp_reset(struct ast_rtp *rtp)
2398 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
2399 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
2400 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
2401 rtp->lastts = 0;
2402 rtp->lastdigitts = 0;
2403 rtp->lastrxts = 0;
2404 rtp->lastividtimestamp = 0;
2405 rtp->lastovidtimestamp = 0;
2406 rtp->lastitexttimestamp = 0;
2407 rtp->lastotexttimestamp = 0;
2408 rtp->lasteventseqn = 0;
2409 rtp->lastevent = 0;
2410 rtp->lasttxformat = 0;
2411 rtp->lastrxformat = 0;
2412 rtp->dtmfcount = 0;
2413 rtp->dtmfsamples = 0;
2414 rtp->seqno = 0;
2415 rtp->rxseqno = 0;
2418 char *ast_rtp_get_quality(struct ast_rtp *rtp, struct ast_rtp_quality *qual)
2421 *ssrc our ssrc
2422 *themssrc their ssrc
2423 *lp lost packets
2424 *rxjitter our calculated jitter(rx)
2425 *rxcount no. received packets
2426 *txjitter reported jitter of the other end
2427 *txcount transmitted packets
2428 *rlp remote lost packets
2429 *rtt round trip time
2432 if (qual && rtp) {
2433 qual->local_ssrc = rtp->ssrc;
2434 qual->local_jitter = rtp->rxjitter;
2435 qual->local_count = rtp->rxcount;
2436 qual->remote_ssrc = rtp->themssrc;
2437 qual->remote_count = rtp->txcount;
2438 if (rtp->rtcp) {
2439 qual->local_lostpackets = rtp->rtcp->expected_prior - rtp->rtcp->received_prior;
2440 qual->remote_lostpackets = rtp->rtcp->reported_lost;
2441 qual->remote_jitter = rtp->rtcp->reported_jitter / 65536.0;
2442 qual->rtt = rtp->rtcp->rtt;
2445 if (rtp->rtcp) {
2446 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality),
2447 "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
2448 rtp->ssrc,
2449 rtp->themssrc,
2450 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2451 rtp->rxjitter,
2452 rtp->rxcount,
2453 (double)rtp->rtcp->reported_jitter / 65536.0,
2454 rtp->txcount,
2455 rtp->rtcp->reported_lost,
2456 rtp->rtcp->rtt);
2457 return rtp->rtcp->quality;
2458 } else
2459 return "<Unknown> - RTP/RTCP has already been destroyed";
2462 void ast_rtp_destroy(struct ast_rtp *rtp)
2464 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
2465 /*Print some info on the call here */
2466 ast_verbose(" RTP-stats\n");
2467 ast_verbose("* Our Receiver:\n");
2468 ast_verbose(" SSRC: %u\n", rtp->themssrc);
2469 ast_verbose(" Received packets: %u\n", rtp->rxcount);
2470 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
2471 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
2472 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
2473 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
2474 ast_verbose("* Our Sender:\n");
2475 ast_verbose(" SSRC: %u\n", rtp->ssrc);
2476 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2477 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
2478 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter / (unsigned int)65536.0);
2479 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
2480 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
2483 manager_event(EVENT_FLAG_REPORTING, "RTPReceiverStat", "SSRC: %u\r\n"
2484 "ReceivedPackets: %u\r\n"
2485 "LostPackets: %u\r\n"
2486 "Jitter: %.4f\r\n"
2487 "Transit: %.4f\r\n"
2488 "RRCount: %u\r\n",
2489 rtp->themssrc,
2490 rtp->rxcount,
2491 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2492 rtp->rxjitter,
2493 rtp->rxtransit,
2494 rtp->rtcp->rr_count);
2495 manager_event(EVENT_FLAG_REPORTING, "RTPSenderStat", "SSRC: %u\r\n"
2496 "SentPackets: %u\r\n"
2497 "LostPackets: %u\r\n"
2498 "Jitter: %u\r\n"
2499 "SRCount: %u\r\n"
2500 "RTT: %f\r\n",
2501 rtp->ssrc,
2502 rtp->txcount,
2503 rtp->rtcp->reported_lost,
2504 rtp->rtcp->reported_jitter,
2505 rtp->rtcp->sr_count,
2506 rtp->rtcp->rtt);
2507 if (rtp->smoother)
2508 ast_smoother_free(rtp->smoother);
2509 if (rtp->ioid)
2510 ast_io_remove(rtp->io, rtp->ioid);
2511 if (rtp->s > -1)
2512 close(rtp->s);
2513 if (rtp->rtcp) {
2514 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2515 close(rtp->rtcp->s);
2516 ast_free(rtp->rtcp);
2517 rtp->rtcp=NULL;
2519 #ifdef P2P_INTENSE
2520 ast_mutex_destroy(&rtp->bridge_lock);
2521 #endif
2522 ast_free(rtp);
2525 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2527 struct timeval t;
2528 long ms;
2529 if (ast_tvzero(rtp->txcore)) {
2530 rtp->txcore = ast_tvnow();
2531 /* Round to 20ms for nice, pretty timestamps */
2532 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2534 /* Use previous txcore if available */
2535 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2536 ms = ast_tvdiff_ms(t, rtp->txcore);
2537 if (ms < 0)
2538 ms = 0;
2539 /* Use what we just got for next time */
2540 rtp->txcore = t;
2541 return (unsigned int) ms;
2544 /*! \brief Send begin frames for DTMF */
2545 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
2547 unsigned int *rtpheader;
2548 int hdrlen = 12, res = 0, i = 0, payload = 0;
2549 char data[256];
2551 if ((digit <= '9') && (digit >= '0'))
2552 digit -= '0';
2553 else if (digit == '*')
2554 digit = 10;
2555 else if (digit == '#')
2556 digit = 11;
2557 else if ((digit >= 'A') && (digit <= 'D'))
2558 digit = digit - 'A' + 12;
2559 else if ((digit >= 'a') && (digit <= 'd'))
2560 digit = digit - 'a' + 12;
2561 else {
2562 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2563 return 0;
2566 /* If we have no peer, return immediately */
2567 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2568 return 0;
2570 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
2572 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2573 rtp->send_duration = 160;
2575 /* Get a pointer to the header */
2576 rtpheader = (unsigned int *)data;
2577 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2578 rtpheader[1] = htonl(rtp->lastdigitts);
2579 rtpheader[2] = htonl(rtp->ssrc);
2581 for (i = 0; i < 2; i++) {
2582 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2583 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2584 if (res < 0)
2585 ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
2586 ast_inet_ntoa(rtp->them.sin_addr),
2587 ntohs(rtp->them.sin_port), strerror(errno));
2588 if (rtp_debug_test_addr(&rtp->them))
2589 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2590 ast_inet_ntoa(rtp->them.sin_addr),
2591 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2592 /* Increment sequence number */
2593 rtp->seqno++;
2594 /* Increment duration */
2595 rtp->send_duration += 160;
2596 /* Clear marker bit and set seqno */
2597 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2600 /* Since we received a begin, we can safely store the digit and disable any compensation */
2601 rtp->sending_digit = 1;
2602 rtp->send_digit = digit;
2603 rtp->send_payload = payload;
2605 return 0;
2608 /*! \brief Send continuation frame for DTMF */
2609 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
2611 unsigned int *rtpheader;
2612 int hdrlen = 12, res = 0;
2613 char data[256];
2615 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2616 return 0;
2618 /* Setup packet to send */
2619 rtpheader = (unsigned int *)data;
2620 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2621 rtpheader[1] = htonl(rtp->lastdigitts);
2622 rtpheader[2] = htonl(rtp->ssrc);
2623 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2624 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2626 /* Transmit */
2627 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2628 if (res < 0)
2629 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2630 ast_inet_ntoa(rtp->them.sin_addr),
2631 ntohs(rtp->them.sin_port), strerror(errno));
2632 if (rtp_debug_test_addr(&rtp->them))
2633 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2634 ast_inet_ntoa(rtp->them.sin_addr),
2635 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2637 /* Increment sequence number */
2638 rtp->seqno++;
2639 /* Increment duration */
2640 rtp->send_duration += 160;
2642 return 0;
2645 /*! \brief Send end packets for DTMF */
2646 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
2648 unsigned int *rtpheader;
2649 int hdrlen = 12, res = 0, i = 0;
2650 char data[256];
2652 /* If no address, then bail out */
2653 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2654 return 0;
2656 if ((digit <= '9') && (digit >= '0'))
2657 digit -= '0';
2658 else if (digit == '*')
2659 digit = 10;
2660 else if (digit == '#')
2661 digit = 11;
2662 else if ((digit >= 'A') && (digit <= 'D'))
2663 digit = digit - 'A' + 12;
2664 else if ((digit >= 'a') && (digit <= 'd'))
2665 digit = digit - 'a' + 12;
2666 else {
2667 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2668 return 0;
2671 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2673 rtpheader = (unsigned int *)data;
2674 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2675 rtpheader[1] = htonl(rtp->lastdigitts);
2676 rtpheader[2] = htonl(rtp->ssrc);
2677 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2678 /* Set end bit */
2679 rtpheader[3] |= htonl((1 << 23));
2680 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2681 /* Send 3 termination packets */
2682 for (i = 0; i < 3; i++) {
2683 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2684 if (res < 0)
2685 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2686 ast_inet_ntoa(rtp->them.sin_addr),
2687 ntohs(rtp->them.sin_port), strerror(errno));
2688 if (rtp_debug_test_addr(&rtp->them))
2689 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2690 ast_inet_ntoa(rtp->them.sin_addr),
2691 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2693 rtp->sending_digit = 0;
2694 rtp->send_digit = 0;
2695 /* Increment lastdigitts */
2696 rtp->lastdigitts += 960;
2697 rtp->seqno++;
2699 return res;
2702 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
2703 int ast_rtcp_send_h261fur(void *data)
2705 struct ast_rtp *rtp = data;
2706 int res;
2708 rtp->rtcp->sendfur = 1;
2709 res = ast_rtcp_write(data);
2711 return res;
2714 /*! \brief Send RTCP sender's report */
2715 static int ast_rtcp_write_sr(const void *data)
2717 struct ast_rtp *rtp = (struct ast_rtp *)data;
2718 int res;
2719 int len = 0;
2720 struct timeval now;
2721 unsigned int now_lsw;
2722 unsigned int now_msw;
2723 unsigned int *rtcpheader;
2724 unsigned int lost;
2725 unsigned int extended;
2726 unsigned int expected;
2727 unsigned int expected_interval;
2728 unsigned int received_interval;
2729 int lost_interval;
2730 int fraction;
2731 struct timeval dlsr;
2732 char bdata[512];
2734 /* Commented condition is always not NULL if rtp->rtcp is not NULL */
2735 if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
2736 return 0;
2738 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
2739 ast_verbose("RTCP SR transmission error, rtcp halted\n");
2740 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2741 return 0;
2744 gettimeofday(&now, NULL);
2745 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
2746 rtcpheader = (unsigned int *)bdata;
2747 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
2748 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
2749 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
2750 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
2751 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
2752 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
2753 len += 28;
2755 extended = rtp->cycles + rtp->lastrxseqno;
2756 expected = extended - rtp->seedrxseqno + 1;
2757 if (rtp->rxcount > expected)
2758 expected += rtp->rxcount - expected;
2759 lost = expected - rtp->rxcount;
2760 expected_interval = expected - rtp->rtcp->expected_prior;
2761 rtp->rtcp->expected_prior = expected;
2762 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2763 rtp->rtcp->received_prior = rtp->rxcount;
2764 lost_interval = expected_interval - received_interval;
2765 if (expected_interval == 0 || lost_interval <= 0)
2766 fraction = 0;
2767 else
2768 fraction = (lost_interval << 8) / expected_interval;
2769 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2770 rtcpheader[7] = htonl(rtp->themssrc);
2771 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2772 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2773 rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
2774 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2775 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2776 len += 24;
2778 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2780 if (rtp->rtcp->sendfur) {
2781 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2782 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
2783 len += 8;
2784 rtp->rtcp->sendfur = 0;
2787 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2788 /* it can change mid call, and SDES can't) */
2789 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2790 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2791 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2792 len += 12;
2794 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2795 if (res < 0) {
2796 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));
2797 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2798 return 0;
2801 /* FIXME Don't need to get a new one */
2802 gettimeofday(&rtp->rtcp->txlsr, NULL);
2803 rtp->rtcp->sr_count++;
2805 rtp->rtcp->lastsrtxcount = rtp->txcount;
2807 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2808 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2809 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
2810 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2811 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
2812 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2813 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
2814 ast_verbose(" Report block:\n");
2815 ast_verbose(" Fraction lost: %u\n", fraction);
2816 ast_verbose(" Cumulative loss: %u\n", lost);
2817 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
2818 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
2819 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2821 manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To %s:%d\r\n"
2822 "OurSSRC: %u\r\n"
2823 "SentNTP: %u.%010u\r\n"
2824 "SentRTP: %u\r\n"
2825 "SentPackets: %u\r\n"
2826 "SentOctets: %u\r\n"
2827 "ReportBlock:\r\n"
2828 "FractionLost: %u\r\n"
2829 "CumulativeLoss: %u\r\n"
2830 "IAJitter: %.4f\r\n"
2831 "TheirLastSR: %u\r\n"
2832 "DLSR: %4.4f (sec)\r\n",
2833 ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port),
2834 rtp->ssrc,
2835 (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
2836 rtp->lastts,
2837 rtp->txcount,
2838 rtp->txoctetcount,
2839 fraction,
2840 lost,
2841 rtp->rxjitter,
2842 rtp->rtcp->themrxlsr,
2843 (double)(ntohl(rtcpheader[12])/65536.0));
2844 return res;
2847 /*! \brief Send RTCP recipient's report */
2848 static int ast_rtcp_write_rr(const void *data)
2850 struct ast_rtp *rtp = (struct ast_rtp *)data;
2851 int res;
2852 int len = 32;
2853 unsigned int lost;
2854 unsigned int extended;
2855 unsigned int expected;
2856 unsigned int expected_interval;
2857 unsigned int received_interval;
2858 int lost_interval;
2859 struct timeval now;
2860 unsigned int *rtcpheader;
2861 char bdata[1024];
2862 struct timeval dlsr;
2863 int fraction;
2865 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2866 return 0;
2868 if (!rtp->rtcp->them.sin_addr.s_addr) {
2869 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
2870 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2871 return 0;
2874 extended = rtp->cycles + rtp->lastrxseqno;
2875 expected = extended - rtp->seedrxseqno + 1;
2876 lost = expected - rtp->rxcount;
2877 expected_interval = expected - rtp->rtcp->expected_prior;
2878 rtp->rtcp->expected_prior = expected;
2879 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2880 rtp->rtcp->received_prior = rtp->rxcount;
2881 lost_interval = expected_interval - received_interval;
2882 if (expected_interval == 0 || lost_interval <= 0)
2883 fraction = 0;
2884 else
2885 fraction = (lost_interval << 8) / expected_interval;
2886 gettimeofday(&now, NULL);
2887 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2888 rtcpheader = (unsigned int *)bdata;
2889 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2890 rtcpheader[1] = htonl(rtp->ssrc);
2891 rtcpheader[2] = htonl(rtp->themssrc);
2892 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2893 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2894 rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
2895 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2896 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2898 if (rtp->rtcp->sendfur) {
2899 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2900 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
2901 len += 8;
2902 rtp->rtcp->sendfur = 0;
2905 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2906 it can change mid call, and SDES can't) */
2907 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2908 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2909 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2910 len += 12;
2912 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2914 if (res < 0) {
2915 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2916 /* Remove the scheduler */
2917 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2918 return 0;
2921 rtp->rtcp->rr_count++;
2923 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2924 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2925 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2926 " IA jitter: %.4f\n"
2927 " Their last SR: %u\n"
2928 " DLSR: %4.4f (sec)\n\n",
2929 ast_inet_ntoa(rtp->rtcp->them.sin_addr),
2930 ntohs(rtp->rtcp->them.sin_port),
2931 rtp->ssrc, rtp->themssrc, fraction, lost,
2932 rtp->rxjitter,
2933 rtp->rtcp->themrxlsr,
2934 (double)(ntohl(rtcpheader[7])/65536.0));
2937 return res;
2940 /*! \brief Write and RTCP packet to the far end
2941 * \note Decide if we are going to send an SR (with Reception Block) or RR
2942 * RR is sent if we have not sent any rtp packets in the previous interval */
2943 static int ast_rtcp_write(const void *data)
2945 struct ast_rtp *rtp = (struct ast_rtp *)data;
2946 int res;
2948 if (!rtp || !rtp->rtcp)
2949 return 0;
2951 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2952 res = ast_rtcp_write_sr(data);
2953 else
2954 res = ast_rtcp_write_rr(data);
2956 return res;
2959 /*! \brief generate comfort noice (CNG) */
2960 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2962 unsigned int *rtpheader;
2963 int hdrlen = 12;
2964 int res;
2965 int payload;
2966 char data[256];
2967 level = 127 - (level & 0x7f);
2968 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2970 /* If we have no peer, return immediately */
2971 if (!rtp->them.sin_addr.s_addr)
2972 return 0;
2974 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2976 /* Get a pointer to the header */
2977 rtpheader = (unsigned int *)data;
2978 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2979 rtpheader[1] = htonl(rtp->lastts);
2980 rtpheader[2] = htonl(rtp->ssrc);
2981 data[12] = level;
2982 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2983 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2984 if (res <0)
2985 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));
2986 if (rtp_debug_test_addr(&rtp->them))
2987 ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
2988 , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
2991 return 0;
2994 /*! \brief Write RTP packet with audio or video media frames into UDP packet */
2995 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2997 unsigned char *rtpheader;
2998 int hdrlen = 12;
2999 int res;
3000 unsigned int ms;
3001 int pred;
3002 int mark = 0;
3004 ms = calc_txstamp(rtp, &f->delivery);
3005 /* Default prediction */
3006 if (f->frametype == AST_FRAME_VOICE) {
3007 pred = rtp->lastts + f->samples;
3009 /* Re-calculate last TS */
3010 rtp->lastts = rtp->lastts + ms * 8;
3011 if (ast_tvzero(f->delivery)) {
3012 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
3013 and if so, go with our prediction */
3014 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
3015 rtp->lastts = pred;
3016 else {
3017 ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
3018 mark = 1;
3021 } else if (f->frametype == AST_FRAME_VIDEO) {
3022 mark = f->subclass & 0x1;
3023 pred = rtp->lastovidtimestamp + f->samples;
3024 /* Re-calculate last TS */
3025 rtp->lastts = rtp->lastts + ms * 90;
3026 /* If it's close to our prediction, go for it */
3027 if (ast_tvzero(f->delivery)) {
3028 if (abs(rtp->lastts - pred) < 7200) {
3029 rtp->lastts = pred;
3030 rtp->lastovidtimestamp += f->samples;
3031 } else {
3032 ast_debug(3, "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);
3033 rtp->lastovidtimestamp = rtp->lastts;
3036 } else {
3037 pred = rtp->lastotexttimestamp + f->samples;
3038 /* Re-calculate last TS */
3039 rtp->lastts = rtp->lastts + ms * 90;
3040 /* If it's close to our prediction, go for it */
3041 if (ast_tvzero(f->delivery)) {
3042 if (abs(rtp->lastts - pred) < 7200) {
3043 rtp->lastts = pred;
3044 rtp->lastotexttimestamp += f->samples;
3045 } else {
3046 ast_debug(3, "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);
3047 rtp->lastotexttimestamp = rtp->lastts;
3052 /* If we have been explicitly told to set the marker bit do so */
3053 if (rtp->set_marker_bit) {
3054 mark = 1;
3055 rtp->set_marker_bit = 0;
3058 /* If the timestamp for non-digit packets has moved beyond the timestamp
3059 for digits, update the digit timestamp.
3061 if (rtp->lastts > rtp->lastdigitts)
3062 rtp->lastdigitts = rtp->lastts;
3064 if (ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO))
3065 rtp->lastts = f->ts * 8;
3067 /* Get a pointer to the header */
3068 rtpheader = (unsigned char *)(f->data - hdrlen);
3070 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
3071 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
3072 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
3074 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
3075 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
3076 if (res < 0) {
3077 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
3078 ast_debug(1, "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));
3079 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
3080 /* Only give this error message once if we are not RTP debugging */
3081 if (option_debug || rtpdebug)
3082 ast_debug(0, "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));
3083 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
3085 } else {
3086 rtp->txcount++;
3087 rtp->txoctetcount +=(res - hdrlen);
3089 if (rtp->rtcp && rtp->rtcp->schedid < 1)
3090 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
3093 if (rtp_debug_test_addr(&rtp->them))
3094 ast_verbose("Sent RTP packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3095 ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
3098 rtp->seqno++;
3100 return 0;
3103 void ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
3105 int x;
3106 for (x = 0; x < 32; x++) { /* Ugly way */
3107 rtp->pref.order[x] = prefs->order[x];
3108 rtp->pref.framing[x] = prefs->framing[x];
3110 if (rtp->smoother)
3111 ast_smoother_free(rtp->smoother);
3112 rtp->smoother = NULL;
3115 struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
3117 return &rtp->pref;
3120 int ast_rtp_codec_getformat(int pt)
3122 if (pt < 0 || pt > MAX_RTP_PT)
3123 return 0; /* bogus payload type */
3125 if (static_RTP_PT[pt].isAstFormat)
3126 return static_RTP_PT[pt].code;
3127 else
3128 return 0;
3131 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
3133 struct ast_frame *f;
3134 int codec;
3135 int hdrlen = 12;
3136 int subclass;
3139 /* If we have no peer, return immediately */
3140 if (!rtp->them.sin_addr.s_addr)
3141 return 0;
3143 /* If there is no data length, return immediately */
3144 if (!_f->datalen)
3145 return 0;
3147 /* Make sure we have enough space for RTP header */
3148 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO) && (_f->frametype != AST_FRAME_TEXT)) {
3149 ast_log(LOG_WARNING, "RTP can only send voice, video and text\n");
3150 return -1;
3153 /* The bottom bit of a video subclass contains the marker bit */
3154 subclass = _f->subclass;
3155 if (_f->frametype == AST_FRAME_VIDEO)
3156 subclass &= ~0x1;
3158 codec = ast_rtp_lookup_code(rtp, 1, subclass);
3159 if (codec < 0) {
3160 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
3161 return -1;
3164 if (rtp->lasttxformat != subclass) {
3165 /* New format, reset the smoother */
3166 ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
3167 rtp->lasttxformat = subclass;
3168 if (rtp->smoother)
3169 ast_smoother_free(rtp->smoother);
3170 rtp->smoother = NULL;
3173 if (!rtp->smoother && subclass != AST_FORMAT_SPEEX && subclass != AST_FORMAT_G723_1) {
3174 struct ast_format_list fmt = ast_codec_pref_getsize(&rtp->pref, subclass);
3175 if (fmt.inc_ms) { /* if codec parameters is set / avoid division by zero */
3176 if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
3177 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));
3178 return -1;
3180 if (fmt.flags)
3181 ast_smoother_set_flags(rtp->smoother, fmt.flags);
3182 ast_debug(1, "Created smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
3185 if (rtp->smoother) {
3186 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
3187 ast_smoother_feed_be(rtp->smoother, _f);
3188 } else {
3189 ast_smoother_feed(rtp->smoother, _f);
3192 while ((f = ast_smoother_read(rtp->smoother)) && (f->data)) {
3193 if (f->subclass == AST_FORMAT_G722) {
3194 /* G.722 is silllllllllllllly */
3195 f->samples /= 2;
3198 ast_rtp_raw_write(rtp, f, codec);
3200 } else {
3201 /* Don't buffer outgoing frames; send them one-per-packet: */
3202 if (_f->offset < hdrlen)
3203 f = ast_frdup(_f); /*! \bug XXX this might never be free'd. Why do we do this? */
3204 else
3205 f = _f;
3206 if (f->data)
3207 ast_rtp_raw_write(rtp, f, codec);
3208 if (f != _f)
3209 ast_frfree(f);
3212 return 0;
3215 /*! \brief Unregister interface to channel driver */
3216 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
3218 AST_RWLIST_WRLOCK(&protos);
3219 AST_RWLIST_REMOVE(&protos, proto, list);
3220 AST_RWLIST_UNLOCK(&protos);
3223 /*! \brief Register interface to channel driver */
3224 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
3226 struct ast_rtp_protocol *cur;
3228 AST_RWLIST_WRLOCK(&protos);
3229 AST_RWLIST_TRAVERSE(&protos, cur, list) {
3230 if (!strcmp(cur->type, proto->type)) {
3231 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
3232 AST_RWLIST_UNLOCK(&protos);
3233 return -1;
3236 AST_RWLIST_INSERT_HEAD(&protos, proto, list);
3237 AST_RWLIST_UNLOCK(&protos);
3239 return 0;
3242 /*! \brief Bridge loop for true native bridge (reinvite) */
3243 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 *tp0, struct ast_rtp *tp1, 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)
3245 struct ast_frame *fr = NULL;
3246 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
3247 int oldcodec0 = codec0, oldcodec1 = codec1;
3248 struct sockaddr_in ac1 = {0,}, vac1 = {0,}, tac1 = {0,}, ac0 = {0,}, vac0 = {0,}, tac0 = {0,};
3249 struct sockaddr_in t1 = {0,}, vt1 = {0,}, tt1 = {0,}, t0 = {0,}, vt0 = {0,}, tt0 = {0,};
3251 /* Set it up so audio goes directly between the two endpoints */
3253 /* Test the first channel */
3254 if (!(pr0->set_rtp_peer(c0, p1, vp1, tp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))) {
3255 ast_rtp_get_peer(p1, &ac1);
3256 if (vp1)
3257 ast_rtp_get_peer(vp1, &vac1);
3258 if (tp1)
3259 ast_rtp_get_peer(tp1, &tac1);
3260 } else
3261 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
3263 /* Test the second channel */
3264 if (!(pr1->set_rtp_peer(c1, p0, vp0, tp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))) {
3265 ast_rtp_get_peer(p0, &ac0);
3266 if (vp0)
3267 ast_rtp_get_peer(vp0, &vac0);
3268 if (tp0)
3269 ast_rtp_get_peer(tp0, &tac0);
3270 } else
3271 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c1->name, c0->name);
3273 /* Now we can unlock and move into our loop */
3274 ast_channel_unlock(c0);
3275 ast_channel_unlock(c1);
3277 ast_poll_channel_add(c0, c1);
3279 /* Throw our channels into the structure and enter the loop */
3280 cs[0] = c0;
3281 cs[1] = c1;
3282 cs[2] = NULL;
3283 for (;;) {
3284 /* Check if anything changed */
3285 if ((c0->tech_pvt != pvt0) ||
3286 (c1->tech_pvt != pvt1) ||
3287 (c0->masq || c0->masqr || c1->masq || c1->masqr) ||
3288 (c0->monitor || c0->audiohooks || c1->monitor || c1->audiohooks)) {
3289 ast_debug(1, "Oooh, something is weird, backing out\n");
3290 if (c0->tech_pvt == pvt0)
3291 if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
3292 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
3293 if (c1->tech_pvt == pvt1)
3294 if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
3295 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
3296 ast_poll_channel_del(c0, c1);
3297 return AST_BRIDGE_RETRY;
3300 /* Check if they have changed their address */
3301 ast_rtp_get_peer(p1, &t1);
3302 if (vp1)
3303 ast_rtp_get_peer(vp1, &vt1);
3304 if (tp1)
3305 ast_rtp_get_peer(tp1, &tt1);
3306 if (pr1->get_codec)
3307 codec1 = pr1->get_codec(c1);
3308 ast_rtp_get_peer(p0, &t0);
3309 if (vp0)
3310 ast_rtp_get_peer(vp0, &vt0);
3311 if (tp0)
3312 ast_rtp_get_peer(tp0, &tt0);
3313 if (pr0->get_codec)
3314 codec0 = pr0->get_codec(c0);
3315 if ((inaddrcmp(&t1, &ac1)) ||
3316 (vp1 && inaddrcmp(&vt1, &vac1)) ||
3317 (tp1 && inaddrcmp(&tt1, &tac1)) ||
3318 (codec1 != oldcodec1)) {
3319 ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
3320 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
3321 ast_debug(2, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
3322 c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
3323 ast_debug(2, "Oooh, '%s' changed end taddress to %s:%d (format %d)\n",
3324 c1->name, ast_inet_ntoa(tt1.sin_addr), ntohs(tt1.sin_port), codec1);
3325 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3326 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
3327 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3328 c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
3329 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3330 c1->name, ast_inet_ntoa(tac1.sin_addr), ntohs(tac1.sin_port), oldcodec1);
3331 if (pr0->set_rtp_peer(c0, t1.sin_addr.s_addr ? p1 : NULL, vt1.sin_addr.s_addr ? vp1 : NULL, tt1.sin_addr.s_addr ? tp1 : NULL, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
3332 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
3333 memcpy(&ac1, &t1, sizeof(ac1));
3334 memcpy(&vac1, &vt1, sizeof(vac1));
3335 memcpy(&tac1, &tt1, sizeof(tac1));
3336 oldcodec1 = codec1;
3338 if ((inaddrcmp(&t0, &ac0)) ||
3339 (vp0 && inaddrcmp(&vt0, &vac0)) ||
3340 (tp0 && inaddrcmp(&tt0, &tac0))) {
3341 ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
3342 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
3343 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3344 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
3345 if (pr1->set_rtp_peer(c1, t0.sin_addr.s_addr ? p0 : NULL, vt0.sin_addr.s_addr ? vp0 : NULL, tt0.sin_addr.s_addr ? tp0 : NULL, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
3346 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
3347 memcpy(&ac0, &t0, sizeof(ac0));
3348 memcpy(&vac0, &vt0, sizeof(vac0));
3349 memcpy(&tac0, &tt0, sizeof(tac0));
3350 oldcodec0 = codec0;
3353 /* Wait for frame to come in on the channels */
3354 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
3355 if (!timeoutms) {
3356 if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
3357 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
3358 if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
3359 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
3360 return AST_BRIDGE_RETRY;
3362 ast_debug(1, "Ooh, empty read...\n");
3363 if (ast_check_hangup(c0) || ast_check_hangup(c1))
3364 break;
3365 continue;
3367 fr = ast_read(who);
3368 other = (who == c0) ? c1 : c0;
3369 if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
3370 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
3371 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
3372 /* Break out of bridge */
3373 *fo = fr;
3374 *rc = who;
3375 ast_debug(1, "Oooh, got a %s\n", fr ? "digit" : "hangup");
3376 if (c0->tech_pvt == pvt0)
3377 if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
3378 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
3379 if (c1->tech_pvt == pvt1)
3380 if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
3381 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
3382 ast_poll_channel_del(c0, c1);
3383 return AST_BRIDGE_COMPLETE;
3384 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3385 if ((fr->subclass == AST_CONTROL_HOLD) ||
3386 (fr->subclass == AST_CONTROL_UNHOLD) ||
3387 (fr->subclass == AST_CONTROL_VIDUPDATE) ||
3388 (fr->subclass == AST_CONTROL_T38) ||
3389 (fr->subclass == AST_CONTROL_SRCUPDATE)) {
3390 if (fr->subclass == AST_CONTROL_HOLD) {
3391 /* If we someone went on hold we want the other side to reinvite back to us */
3392 if (who == c0)
3393 pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0);
3394 else
3395 pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0);
3396 } else if (fr->subclass == AST_CONTROL_UNHOLD) {
3397 /* If they went off hold they should go back to being direct */
3398 if (who == c0)
3399 pr1->set_rtp_peer(c1, p0, vp0, tp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE));
3400 else
3401 pr0->set_rtp_peer(c0, p1, vp1, tp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE));
3403 /* Update local address information */
3404 ast_rtp_get_peer(p0, &t0);
3405 memcpy(&ac0, &t0, sizeof(ac0));
3406 ast_rtp_get_peer(p1, &t1);
3407 memcpy(&ac1, &t1, sizeof(ac1));
3408 /* Update codec information */
3409 if (pr0->get_codec && c0->tech_pvt)
3410 oldcodec0 = codec0 = pr0->get_codec(c0);
3411 if (pr1->get_codec && c1->tech_pvt)
3412 oldcodec1 = codec1 = pr1->get_codec(c1);
3413 ast_indicate_data(other, fr->subclass, fr->data, fr->datalen);
3414 ast_frfree(fr);
3415 } else {
3416 *fo = fr;
3417 *rc = who;
3418 ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
3419 return AST_BRIDGE_COMPLETE;
3421 } else {
3422 if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
3423 (fr->frametype == AST_FRAME_DTMF_END) ||
3424 (fr->frametype == AST_FRAME_VOICE) ||
3425 (fr->frametype == AST_FRAME_VIDEO) ||
3426 (fr->frametype == AST_FRAME_IMAGE) ||
3427 (fr->frametype == AST_FRAME_HTML) ||
3428 (fr->frametype == AST_FRAME_MODEM) ||
3429 (fr->frametype == AST_FRAME_TEXT)) {
3430 ast_write(other, fr);
3432 ast_frfree(fr);
3434 /* Swap priority */
3435 #ifndef HAVE_EPOLL
3436 cs[2] = cs[0];
3437 cs[0] = cs[1];
3438 cs[1] = cs[2];
3439 #endif
3442 ast_poll_channel_del(c0, c1);
3444 if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
3445 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
3446 if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
3447 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
3449 return AST_BRIDGE_FAILED;
3452 /*! \brief P2P RTP Callback */
3453 #ifdef P2P_INTENSE
3454 static int p2p_rtp_callback(int *id, int fd, short events, void *cbdata)
3456 int res = 0, hdrlen = 12;
3457 struct sockaddr_in sin;
3458 socklen_t len;
3459 unsigned int *header;
3460 struct ast_rtp *rtp = cbdata, *bridged = NULL;
3462 if (!rtp)
3463 return 1;
3465 len = sizeof(sin);
3466 if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
3467 return 1;
3469 header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
3471 /* If NAT support is turned on, then see if we need to change their address */
3472 if ((rtp->nat) &&
3473 ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
3474 (rtp->them.sin_port != sin.sin_port))) {
3475 rtp->them = sin;
3476 rtp->rxseqno = 0;
3477 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
3478 if (option_debug || rtpdebug)
3479 ast_debug(0, "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));
3482 /* Write directly out to other RTP stream if bridged */
3483 if ((bridged = ast_rtp_get_bridged(rtp)))
3484 bridge_p2p_rtp_write(rtp, bridged, header, res, hdrlen);
3486 return 1;
3489 /*! \brief Helper function to switch a channel and RTP stream into callback mode */
3490 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
3492 /* If we need DTMF, are looking for STUN, or we have no IO structure then we can't do direct callback */
3493 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) || ast_test_flag(rtp, FLAG_HAS_STUN) || !rtp->io)
3494 return 0;
3496 /* If the RTP structure is already in callback mode, remove it temporarily */
3497 if (rtp->ioid) {
3498 ast_io_remove(rtp->io, rtp->ioid);
3499 rtp->ioid = NULL;
3502 /* Steal the file descriptors from the channel */
3503 chan->fds[0] = -1;
3505 /* Now, fire up callback mode */
3506 iod[0] = ast_io_add(rtp->io, ast_rtp_fd(rtp), p2p_rtp_callback, AST_IO_IN, rtp);
3508 return 1;
3510 #else
3511 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
3513 return 0;
3515 #endif
3517 /*! \brief Helper function to switch a channel and RTP stream out of callback mode */
3518 static int p2p_callback_disable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
3520 ast_channel_lock(chan);
3522 /* Remove the callback from the IO context */
3523 ast_io_remove(rtp->io, iod[0]);
3525 /* Restore file descriptors */
3526 chan->fds[0] = ast_rtp_fd(rtp);
3527 ast_channel_unlock(chan);
3529 /* Restore callback mode if previously used */
3530 if (ast_test_flag(rtp, FLAG_CALLBACK_MODE))
3531 rtp->ioid = ast_io_add(rtp->io, ast_rtp_fd(rtp), rtpread, AST_IO_IN, rtp);
3533 return 0;
3536 /*! \brief Helper function that sets what an RTP structure is bridged to */
3537 static void p2p_set_bridge(struct ast_rtp *rtp0, struct ast_rtp *rtp1)
3539 rtp_bridge_lock(rtp0);
3540 rtp0->bridged = rtp1;
3541 rtp_bridge_unlock(rtp0);
3544 /*! \brief Bridge loop for partial native bridge (packet2packet)
3546 In p2p mode, Asterisk is a very basic RTP proxy, just forwarding whatever
3547 rtp/rtcp we get in to the channel.
3548 \note this currently only works for Audio
3550 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)
3552 struct ast_frame *fr = NULL;
3553 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
3554 int *p0_iod[2] = {NULL, NULL}, *p1_iod[2] = {NULL, NULL};
3555 int p0_callback = 0, p1_callback = 0;
3556 enum ast_bridge_result res = AST_BRIDGE_FAILED;
3558 /* Okay, setup each RTP structure to do P2P forwarding */
3559 ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
3560 p2p_set_bridge(p0, p1);
3561 ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
3562 p2p_set_bridge(p1, p0);
3564 /* Activate callback modes if possible */
3565 p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
3566 p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
3568 /* Now let go of the channel locks and be on our way */
3569 ast_channel_unlock(c0);
3570 ast_channel_unlock(c1);
3572 ast_poll_channel_add(c0, c1);
3574 /* Go into a loop forwarding frames until we don't need to anymore */
3575 cs[0] = c0;
3576 cs[1] = c1;
3577 cs[2] = NULL;
3578 for (;;) {
3579 /* If the underlying formats have changed force this bridge to break */
3580 if ((c0->rawreadformat != c1->rawwriteformat) || (c1->rawreadformat != c0->rawwriteformat)) {
3581 ast_debug(3, "p2p-rtp-bridge: Oooh, formats changed, backing out\n");
3582 res = AST_BRIDGE_FAILED_NOWARN;
3583 break;
3585 /* Check if anything changed */
3586 if ((c0->tech_pvt != pvt0) ||
3587 (c1->tech_pvt != pvt1) ||
3588 (c0->masq || c0->masqr || c1->masq || c1->masqr) ||
3589 (c0->monitor || c0->audiohooks || c1->monitor || c1->audiohooks)) {
3590 ast_debug(3, "p2p-rtp-bridge: Oooh, something is weird, backing out\n");
3591 /* If a masquerade needs to happen we have to try to read in a frame so that it actually happens. Without this we risk being called again and going into a loop */
3592 if ((c0->masq || c0->masqr) && (fr = ast_read(c0)))
3593 ast_frfree(fr);
3594 if ((c1->masq || c1->masqr) && (fr = ast_read(c1)))
3595 ast_frfree(fr);
3596 res = AST_BRIDGE_RETRY;
3597 break;
3599 /* Wait on a channel to feed us a frame */
3600 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
3601 if (!timeoutms) {
3602 res = AST_BRIDGE_RETRY;
3603 break;
3605 if (option_debug > 2)
3606 ast_log(LOG_NOTICE, "p2p-rtp-bridge: Ooh, empty read...\n");
3607 if (ast_check_hangup(c0) || ast_check_hangup(c1))
3608 break;
3609 continue;
3611 /* Read in frame from channel */
3612 fr = ast_read(who);
3613 other = (who == c0) ? c1 : c0;
3614 /* Depending on the frame we may need to break out of our bridge */
3615 if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
3616 ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
3617 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
3618 /* Record received frame and who */
3619 *fo = fr;
3620 *rc = who;
3621 ast_debug(3, "p2p-rtp-bridge: Ooh, got a %s\n", fr ? "digit" : "hangup");
3622 res = AST_BRIDGE_COMPLETE;
3623 break;
3624 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3625 if ((fr->subclass == AST_CONTROL_HOLD) ||
3626 (fr->subclass == AST_CONTROL_UNHOLD) ||
3627 (fr->subclass == AST_CONTROL_VIDUPDATE) ||
3628 (fr->subclass == AST_CONTROL_T38) ||
3629 (fr->subclass == AST_CONTROL_SRCUPDATE)) {
3630 /* If we are going on hold, then break callback mode and P2P bridging */
3631 if (fr->subclass == AST_CONTROL_HOLD) {
3632 if (p0_callback)
3633 p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
3634 if (p1_callback)
3635 p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
3636 p2p_set_bridge(p0, NULL);
3637 p2p_set_bridge(p1, NULL);
3638 } else if (fr->subclass == AST_CONTROL_UNHOLD) {
3639 /* If we are off hold, then go back to callback mode and P2P bridging */
3640 ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
3641 p2p_set_bridge(p0, p1);
3642 ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
3643 p2p_set_bridge(p1, p0);
3644 p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
3645 p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
3647 ast_indicate_data(other, fr->subclass, fr->data, fr->datalen);
3648 ast_frfree(fr);
3649 } else {
3650 *fo = fr;
3651 *rc = who;
3652 ast_debug(3, "p2p-rtp-bridge: Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
3653 res = AST_BRIDGE_COMPLETE;
3654 break;
3656 } else {
3657 if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
3658 (fr->frametype == AST_FRAME_DTMF_END) ||
3659 (fr->frametype == AST_FRAME_VOICE) ||
3660 (fr->frametype == AST_FRAME_VIDEO) ||
3661 (fr->frametype == AST_FRAME_IMAGE) ||
3662 (fr->frametype == AST_FRAME_HTML) ||
3663 (fr->frametype == AST_FRAME_MODEM) ||
3664 (fr->frametype == AST_FRAME_TEXT)) {
3665 ast_write(other, fr);
3668 ast_frfree(fr);
3670 /* Swap priority */
3671 #ifndef HAVE_EPOLL
3672 cs[2] = cs[0];
3673 cs[0] = cs[1];
3674 cs[1] = cs[2];
3675 #endif
3678 /* If we are totally avoiding the core, then restore our link to it */
3679 if (p0_callback)
3680 p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
3681 if (p1_callback)
3682 p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
3684 /* Break out of the direct bridge */
3685 p2p_set_bridge(p0, NULL);
3686 p2p_set_bridge(p1, NULL);
3688 ast_poll_channel_del(c0, c1);
3690 return res;
3693 /*! \page AstRTPbridge The Asterisk RTP bridge
3694 The RTP bridge is called from the channel drivers that are using the RTP
3695 subsystem in Asterisk - like SIP, H.323 and Jingle/Google Talk.
3697 This bridge aims to offload the Asterisk server by setting up
3698 the media stream directly between the endpoints, keeping the
3699 signalling in Asterisk.
3701 It checks with the channel driver, using a callback function, if
3702 there are possibilities for a remote bridge.
3704 If this fails, the bridge hands off to the core bridge. Reasons
3705 can be NAT support needed, DTMF features in audio needed by
3706 the PBX for transfers or spying/monitoring on channels.
3708 If transcoding is needed - we can't do a remote bridge.
3709 If only NAT support is needed, we're using Asterisk in
3710 RTP proxy mode with the p2p RTP bridge, basically
3711 forwarding incoming audio packets to the outbound
3712 stream on a network level.
3714 References:
3715 - ast_rtp_bridge()
3716 - ast_channel_early_bridge()
3717 - ast_channel_bridge()
3718 - rtp.c
3719 - rtp.h
3721 /*! \brief Bridge calls. If possible and allowed, initiate
3722 re-invite so the peers exchange media directly outside
3723 of Asterisk.
3725 enum ast_bridge_result ast_rtp_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
3727 struct ast_rtp *p0 = NULL, *p1 = NULL; /* Audio RTP Channels */
3728 struct ast_rtp *vp0 = NULL, *vp1 = NULL; /* Video RTP channels */
3729 struct ast_rtp *tp0 = NULL, *tp1 = NULL; /* Text RTP channels */
3730 struct ast_rtp_protocol *pr0 = NULL, *pr1 = NULL;
3731 enum ast_rtp_get_result audio_p0_res = AST_RTP_GET_FAILED, video_p0_res = AST_RTP_GET_FAILED, text_p0_res = AST_RTP_GET_FAILED;
3732 enum ast_rtp_get_result audio_p1_res = AST_RTP_GET_FAILED, video_p1_res = AST_RTP_GET_FAILED, text_p1_res = AST_RTP_GET_FAILED;
3733 enum ast_bridge_result res = AST_BRIDGE_FAILED;
3734 int codec0 = 0, codec1 = 0;
3735 void *pvt0 = NULL, *pvt1 = NULL;
3737 /* Lock channels */
3738 ast_channel_lock(c0);
3739 while (ast_channel_trylock(c1)) {
3740 ast_channel_unlock(c0);
3741 usleep(1);
3742 ast_channel_lock(c0);
3745 /* Ensure neither channel got hungup during lock avoidance */
3746 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3747 ast_log(LOG_WARNING, "Got hangup while attempting to bridge '%s' and '%s'\n", c0->name, c1->name);
3748 ast_channel_unlock(c0);
3749 ast_channel_unlock(c1);
3750 return AST_BRIDGE_FAILED;
3753 /* Find channel driver interfaces */
3754 if (!(pr0 = get_proto(c0))) {
3755 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
3756 ast_channel_unlock(c0);
3757 ast_channel_unlock(c1);
3758 return AST_BRIDGE_FAILED;
3760 if (!(pr1 = get_proto(c1))) {
3761 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
3762 ast_channel_unlock(c0);
3763 ast_channel_unlock(c1);
3764 return AST_BRIDGE_FAILED;
3767 /* Get channel specific interface structures */
3768 pvt0 = c0->tech_pvt;
3769 pvt1 = c1->tech_pvt;
3771 /* Get audio and video interface (if native bridge is possible) */
3772 audio_p0_res = pr0->get_rtp_info(c0, &p0);
3773 video_p0_res = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
3774 text_p0_res = pr0->get_trtp_info ? pr0->get_trtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
3775 audio_p1_res = pr1->get_rtp_info(c1, &p1);
3776 video_p1_res = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
3777 text_p1_res = pr1->get_trtp_info ? pr1->get_trtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
3779 /* If we are carrying video, and both sides are not reinviting... then fail the native bridge */
3780 if (video_p0_res != AST_RTP_GET_FAILED && (audio_p0_res != AST_RTP_TRY_NATIVE || video_p0_res != AST_RTP_TRY_NATIVE))
3781 audio_p0_res = AST_RTP_GET_FAILED;
3782 if (video_p1_res != AST_RTP_GET_FAILED && (audio_p1_res != AST_RTP_TRY_NATIVE || video_p1_res != AST_RTP_TRY_NATIVE))
3783 audio_p1_res = AST_RTP_GET_FAILED;
3785 /* Check if a bridge is possible (partial/native) */
3786 if (audio_p0_res == AST_RTP_GET_FAILED || audio_p1_res == AST_RTP_GET_FAILED) {
3787 /* Somebody doesn't want to play... */
3788 ast_channel_unlock(c0);
3789 ast_channel_unlock(c1);
3790 return AST_BRIDGE_FAILED_NOWARN;
3793 /* If we need to feed DTMF frames into the core then only do a partial native bridge */
3794 if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
3795 ast_set_flag(p0, FLAG_P2P_NEED_DTMF);
3796 audio_p0_res = AST_RTP_TRY_PARTIAL;
3799 if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
3800 ast_set_flag(p1, FLAG_P2P_NEED_DTMF);
3801 audio_p1_res = AST_RTP_TRY_PARTIAL;
3804 /* If both sides are not using the same method of DTMF transmission
3805 * (ie: one is RFC2833, other is INFO... then we can not do direct media.
3806 * --------------------------------------------------
3807 * | DTMF Mode | HAS_DTMF | Accepts Begin Frames |
3808 * |-----------|------------|-----------------------|
3809 * | Inband | False | True |
3810 * | RFC2833 | True | True |
3811 * | SIP INFO | False | False |
3812 * --------------------------------------------------
3813 * However, if DTMF from both channels is being monitored by the core, then
3814 * we can still do packet-to-packet bridging, because passing through the
3815 * core will handle DTMF mode translation.
3817 if ( (ast_test_flag(p0, FLAG_HAS_DTMF) != ast_test_flag(p1, FLAG_HAS_DTMF)) ||
3818 (!c0->tech->send_digit_begin != !c1->tech->send_digit_begin)) {
3819 if (!ast_test_flag(p0, FLAG_P2P_NEED_DTMF) || !ast_test_flag(p1, FLAG_P2P_NEED_DTMF)) {
3820 ast_channel_unlock(c0);
3821 ast_channel_unlock(c1);
3822 return AST_BRIDGE_FAILED_NOWARN;
3824 audio_p0_res = AST_RTP_TRY_PARTIAL;
3825 audio_p1_res = AST_RTP_TRY_PARTIAL;
3828 /* If we need to feed frames into the core don't do a P2P bridge */
3829 if ((audio_p0_res == AST_RTP_TRY_PARTIAL && ast_test_flag(p0, FLAG_P2P_NEED_DTMF)) ||
3830 (audio_p1_res == AST_RTP_TRY_PARTIAL && ast_test_flag(p1, FLAG_P2P_NEED_DTMF))) {
3831 ast_channel_unlock(c0);
3832 ast_channel_unlock(c1);
3833 return AST_BRIDGE_FAILED_NOWARN;
3836 /* Get codecs from both sides */
3837 codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
3838 codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
3839 if (codec0 && codec1 && !(codec0 & codec1)) {
3840 /* Hey, we can't do native bridging if both parties speak different codecs */
3841 ast_debug(3, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
3842 ast_channel_unlock(c0);
3843 ast_channel_unlock(c1);
3844 return AST_BRIDGE_FAILED_NOWARN;
3847 /* If either side can only do a partial bridge, then don't try for a true native bridge */
3848 if (audio_p0_res == AST_RTP_TRY_PARTIAL || audio_p1_res == AST_RTP_TRY_PARTIAL) {
3849 struct ast_format_list fmt0, fmt1;
3851 /* In order to do Packet2Packet bridging both sides must be in the same rawread/rawwrite */
3852 if (c0->rawreadformat != c1->rawwriteformat || c1->rawreadformat != c0->rawwriteformat) {
3853 ast_debug(1, "Cannot packet2packet bridge - raw formats are incompatible\n");
3854 ast_channel_unlock(c0);
3855 ast_channel_unlock(c1);
3856 return AST_BRIDGE_FAILED_NOWARN;
3858 /* They must also be using the same packetization */
3859 fmt0 = ast_codec_pref_getsize(&p0->pref, c0->rawreadformat);
3860 fmt1 = ast_codec_pref_getsize(&p1->pref, c1->rawreadformat);
3861 if (fmt0.cur_ms != fmt1.cur_ms) {
3862 ast_debug(1, "Cannot packet2packet bridge - packetization settings prevent it\n");
3863 ast_channel_unlock(c0);
3864 ast_channel_unlock(c1);
3865 return AST_BRIDGE_FAILED_NOWARN;
3868 ast_verb(3, "Packet2Packet bridging %s and %s\n", c0->name, c1->name);
3869 res = bridge_p2p_loop(c0, c1, p0, p1, timeoutms, flags, fo, rc, pvt0, pvt1);
3870 } else {
3871 ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
3872 res = bridge_native_loop(c0, c1, p0, p1, vp0, vp1, tp0, tp1, pr0, pr1, codec0, codec1, timeoutms, flags, fo, rc, pvt0, pvt1);
3875 return res;
3878 static char *rtp_do_debug_ip(struct ast_cli_args *a)
3880 struct hostent *hp;
3881 struct ast_hostent ahp;
3882 int port = 0;
3883 char *p, *arg;
3885 arg = a->argv[3];
3886 p = strstr(arg, ":");
3887 if (p) {
3888 *p = '\0';
3889 p++;
3890 port = atoi(p);
3892 hp = ast_gethostbyname(arg, &ahp);
3893 if (hp == NULL) {
3894 ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
3895 return CLI_FAILURE;
3897 rtpdebugaddr.sin_family = AF_INET;
3898 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
3899 rtpdebugaddr.sin_port = htons(port);
3900 if (port == 0)
3901 ast_cli(a->fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr.sin_addr));
3902 else
3903 ast_cli(a->fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr.sin_addr), port);
3904 rtpdebug = 1;
3905 return CLI_SUCCESS;
3908 static char *rtcp_do_debug_ip(struct ast_cli_args *a)
3910 struct hostent *hp;
3911 struct ast_hostent ahp;
3912 int port = 0;
3913 char *p, *arg;
3915 arg = a->argv[3];
3916 p = strstr(arg, ":");
3917 if (p) {
3918 *p = '\0';
3919 p++;
3920 port = atoi(p);
3922 hp = ast_gethostbyname(arg, &ahp);
3923 if (hp == NULL) {
3924 ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
3925 return CLI_FAILURE;
3927 rtcpdebugaddr.sin_family = AF_INET;
3928 memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
3929 rtcpdebugaddr.sin_port = htons(port);
3930 if (port == 0)
3931 ast_cli(a->fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
3932 else
3933 ast_cli(a->fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
3934 rtcpdebug = 1;
3935 return CLI_SUCCESS;
3938 static char *handle_cli_rtp_debug_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3940 switch (cmd) {
3941 case CLI_INIT:
3942 e->command = "rtp debug [off|ip]";
3943 e->usage =
3944 "Usage: rtp debug [off]|[ip host[:port]]\n"
3945 " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
3946 " specified, limit the dumped packets to those to and from\n"
3947 " the specified 'host' with optional port.\n";
3948 return NULL;
3949 case CLI_GENERATE:
3950 return NULL;
3953 if (a->argc < 2 || a->argc > 4)
3954 return CLI_SHOWUSAGE;
3955 if (a->argc == 2) {
3956 rtpdebug = 1;
3957 memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
3958 ast_cli(a->fd, "RTP Debugging Enabled\n");
3959 } else if (a->argc == 3) {
3960 if (strncasecmp(a->argv[2], "off", 3))
3961 return CLI_SHOWUSAGE;
3962 rtpdebug = 0;
3963 ast_cli(a->fd, "RTP Debugging Disabled\n");
3964 } else {
3965 if (strncasecmp(a->argv[2], "ip", 2))
3966 return CLI_SHOWUSAGE;
3967 return rtp_do_debug_ip(a);
3970 return CLI_SUCCESS;
3973 static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3975 switch (cmd) {
3976 case CLI_INIT:
3977 e->command = "rtp set debug {on|off|ip}";
3978 e->usage =
3979 "Usage: rtp set debug {on|off|ip host[:port]}\n"
3980 " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
3981 " specified, limit the dumped packets to those to and from\n"
3982 " the specified 'host' with optional port.\n";
3983 return NULL;
3984 case CLI_GENERATE:
3985 return NULL;
3988 if (a->argc == e->args) { /* set on or off */
3989 if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
3990 rtpdebug = 1;
3991 memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
3992 ast_cli(a->fd, "RTP Debugging Enabled\n");
3993 return CLI_SUCCESS;
3994 } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
3995 rtpdebug = 0;
3996 ast_cli(a->fd, "RTP Debugging Disabled\n");
3997 return CLI_SUCCESS;
3999 } else if (a->argc == e->args +1) { /* ip */
4000 return rtp_do_debug_ip(a);
4003 return CLI_SHOWUSAGE; /* default, failure */
4006 static char *handle_cli_rtcp_debug_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4008 switch (cmd) {
4009 case CLI_INIT:
4010 e->command = "rtcp debug [off|ip]";
4011 e->usage =
4012 "Usage: rtcp debug [off]|[ip host[:port]]\n"
4013 " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
4014 " specified, limit the dumped packets to those to and from\n"
4015 " the specified 'host' with optional port.\n";
4016 return NULL;
4017 case CLI_GENERATE:
4018 return NULL;
4021 if (a->argc < 2 || a->argc > 4)
4022 return CLI_SHOWUSAGE;
4023 if (a->argc == 2) {
4024 rtcpdebug = 1;
4025 memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
4026 ast_cli(a->fd, "RTCP Debugging Enabled\n");
4027 } else if (a->argc == 3) {
4028 if (strncasecmp(a->argv[2], "off", 3))
4029 return CLI_SHOWUSAGE;
4030 rtcpdebug = 0;
4031 ast_cli(a->fd, "RTCP Debugging Disabled\n");
4032 } else {
4033 if (strncasecmp(a->argv[2], "ip", 2))
4034 return CLI_SHOWUSAGE;
4035 return rtcp_do_debug_ip(a);
4038 return CLI_SUCCESS;
4041 static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4043 switch (cmd) {
4044 case CLI_INIT:
4045 e->command = "rtcp set debug {on|off|ip}";
4046 e->usage =
4047 "Usage: rtcp set debug {on|off|ip host[:port]}\n"
4048 " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
4049 " specified, limit the dumped packets to those to and from\n"
4050 " the specified 'host' with optional port.\n";
4051 return NULL;
4052 case CLI_GENERATE:
4053 return NULL;
4056 if (a->argc == e->args) { /* set on or off */
4057 if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
4058 rtcpdebug = 1;
4059 memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
4060 ast_cli(a->fd, "RTCP Debugging Enabled\n");
4061 return CLI_SUCCESS;
4062 } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
4063 rtcpdebug = 0;
4064 ast_cli(a->fd, "RTCP Debugging Disabled\n");
4065 return CLI_SUCCESS;
4067 } else if (a->argc == e->args +1) { /* ip */
4068 return rtcp_do_debug_ip(a);
4071 return CLI_SHOWUSAGE; /* default, failure */
4074 static char *handle_cli_rtcp_stats_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4076 switch (cmd) {
4077 case CLI_INIT:
4078 e->command = "rtcp stats [off]";
4079 e->usage =
4080 "Usage: rtcp stats [off]\n"
4081 " Enable/Disable dumping of RTCP stats.\n";
4082 return NULL;
4083 case CLI_GENERATE:
4084 return NULL;
4087 if (a->argc < 2 || a->argc > 3)
4088 return CLI_SHOWUSAGE;
4089 if (a->argc == 3 && strncasecmp(a->argv[2], "off", 3))
4090 return CLI_SHOWUSAGE;
4092 rtcpstats = (a->argc == 3) ? 0 : 1;
4093 ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
4094 return CLI_SUCCESS;
4097 static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4099 switch (cmd) {
4100 case CLI_INIT:
4101 e->command = "rtcp set stats {on|off}";
4102 e->usage =
4103 "Usage: rtcp set stats {on|off}\n"
4104 " Enable/Disable dumping of RTCP stats.\n";
4105 return NULL;
4106 case CLI_GENERATE:
4107 return NULL;
4110 if (a->argc != e->args)
4111 return CLI_SHOWUSAGE;
4113 if (!strncasecmp(a->argv[e->args-1], "on", 2))
4114 rtcpstats = 1;
4115 else if (!strncasecmp(a->argv[e->args-1], "off", 3))
4116 rtcpstats = 0;
4117 else
4118 return CLI_SHOWUSAGE;
4120 ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
4121 return CLI_SUCCESS;
4124 static char *handle_cli_stun_debug_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4126 switch (cmd) {
4127 case CLI_INIT:
4128 e->command = "stun debug [off]";
4129 e->usage =
4130 "Usage: stun debug [off]\n"
4131 " Enable/Disable STUN (Simple Traversal of UDP through NATs)\n"
4132 " debugging\n";
4133 return NULL;
4134 case CLI_GENERATE:
4135 return NULL;
4138 if (a->argc < 2 || a->argc > 3)
4139 return CLI_SHOWUSAGE;
4140 if (a->argc == 3 && strncasecmp(a->argv[2], "off", 3))
4141 return CLI_SHOWUSAGE;
4143 stundebug = (a->argc == 3) ? 0 : 1;
4144 ast_cli(a->fd, "STUN Debugging %s\n", stundebug ? "Enabled" : "Disabled");
4145 return CLI_SUCCESS;
4148 static char *handle_cli_stun_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4150 switch (cmd) {
4151 case CLI_INIT:
4152 e->command = "stun set debug {on|off}";
4153 e->usage =
4154 "Usage: stun set debug {on|off}\n"
4155 " Enable/Disable STUN (Simple Traversal of UDP through NATs)\n"
4156 " debugging\n";
4157 return NULL;
4158 case CLI_GENERATE:
4159 return NULL;
4162 if (a->argc != e->args)
4163 return CLI_SHOWUSAGE;
4165 if (!strncasecmp(a->argv[e->args-1], "on", 2))
4166 stundebug = 1;
4167 else if (!strncasecmp(a->argv[e->args-1], "off", 3))
4168 stundebug = 0;
4169 else
4170 return CLI_SHOWUSAGE;
4172 ast_cli(a->fd, "STUN Debugging %s\n", stundebug ? "Enabled" : "Disabled");
4173 return CLI_SUCCESS;
4176 static struct ast_cli_entry cli_rtp_debug_deprecated = AST_CLI_DEFINE(handle_cli_rtp_debug_deprecated, "Enable/Disable RTP debugging");
4177 static struct ast_cli_entry cli_rtcp_debug_deprecated = AST_CLI_DEFINE(handle_cli_rtcp_debug_deprecated, "Enable/Disable RTCP debugging");
4178 static struct ast_cli_entry cli_rtcp_stats_deprecated = AST_CLI_DEFINE(handle_cli_rtcp_stats_deprecated, "Enable/Disable RTCP stats");
4179 static struct ast_cli_entry cli_stun_debug_deprecated = AST_CLI_DEFINE(handle_cli_stun_debug_deprecated, "Enable/Disable STUN debugging");
4181 static struct ast_cli_entry cli_rtp[] = {
4182 AST_CLI_DEFINE(handle_cli_rtp_set_debug, "Enable/Disable RTP debugging", .deprecate_cmd = &cli_rtp_debug_deprecated),
4183 AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging", .deprecate_cmd = &cli_rtcp_debug_deprecated),
4184 AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats", .deprecate_cmd = &cli_rtcp_stats_deprecated),
4185 AST_CLI_DEFINE(handle_cli_stun_set_debug, "Enable/Disable STUN debugging", .deprecate_cmd = &cli_stun_debug_deprecated),
4188 static int __ast_rtp_reload(int reload)
4190 struct ast_config *cfg;
4191 const char *s;
4192 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
4194 if ((cfg = ast_config_load2("rtp.conf", "rtp", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
4195 return 0;
4197 rtpstart = 5000;
4198 rtpend = 31000;
4199 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
4200 strictrtp = STRICT_RTP_OPEN;
4201 if (cfg) {
4202 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
4203 rtpstart = atoi(s);
4204 if (rtpstart < 1024)
4205 rtpstart = 1024;
4206 if (rtpstart > 65535)
4207 rtpstart = 65535;
4209 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
4210 rtpend = atoi(s);
4211 if (rtpend < 1024)
4212 rtpend = 1024;
4213 if (rtpend > 65535)
4214 rtpend = 65535;
4216 if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
4217 rtcpinterval = atoi(s);
4218 if (rtcpinterval == 0)
4219 rtcpinterval = 0; /* Just so we're clear... it's zero */
4220 if (rtcpinterval < RTCP_MIN_INTERVALMS)
4221 rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
4222 if (rtcpinterval > RTCP_MAX_INTERVALMS)
4223 rtcpinterval = RTCP_MAX_INTERVALMS;
4225 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
4226 #ifdef SO_NO_CHECK
4227 if (ast_false(s))
4228 nochecksums = 1;
4229 else
4230 nochecksums = 0;
4231 #else
4232 if (ast_false(s))
4233 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
4234 #endif
4236 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
4237 dtmftimeout = atoi(s);
4238 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
4239 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
4240 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
4241 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
4244 if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
4245 strictrtp = ast_true(s);
4247 ast_config_destroy(cfg);
4249 if (rtpstart >= rtpend) {
4250 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
4251 rtpstart = 5000;
4252 rtpend = 31000;
4254 ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
4255 return 0;
4258 int ast_rtp_reload(void)
4260 return __ast_rtp_reload(1);
4263 /*! \brief Initialize the RTP system in Asterisk */
4264 void ast_rtp_init(void)
4266 ast_cli_register_multiple(cli_rtp, sizeof(cli_rtp) / sizeof(struct ast_cli_entry));
4267 __ast_rtp_reload(0);