fix a flaw found while experimenting with structure alignment and padding; low-fence...
[asterisk-bristuff.git] / main / rtp.c
blob14d8aafcdbc51cfac23e7d87ae9c39daa5ad8d4d
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 <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <sys/time.h>
37 #include <signal.h>
38 #include <errno.h>
39 #include <unistd.h>
40 #include <netinet/in.h>
41 #include <sys/time.h>
42 #include <sys/socket.h>
43 #include <arpa/inet.h>
44 #include <fcntl.h>
46 #include "asterisk/rtp.h"
47 #include "asterisk/frame.h"
48 #include "asterisk/logger.h"
49 #include "asterisk/options.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/acl.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/config.h"
54 #include "asterisk/lock.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/cli.h"
57 #include "asterisk/unaligned.h"
58 #include "asterisk/utils.h"
60 #define MAX_TIMESTAMP_SKEW 640
62 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
63 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
64 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
65 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
67 #define RTCP_PT_FUR 192
68 #define RTCP_PT_SR 200
69 #define RTCP_PT_RR 201
70 #define RTCP_PT_SDES 202
71 #define RTCP_PT_BYE 203
72 #define RTCP_PT_APP 204
74 #define RTP_MTU 1200
76 #define DEFAULT_DTMF_TIMEOUT 3000 /*!< samples */
78 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
80 static int rtpstart; /*!< First port for RTP sessions (set in rtp.conf) */
81 static int rtpend; /*!< Last port for RTP sessions (set in rtp.conf) */
82 static int rtpdebug; /*!< Are we debugging? */
83 static int rtcpdebug; /*!< Are we debugging RTCP? */
84 static int rtcpstats; /*!< Are we debugging RTCP? */
85 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
86 static int stundebug; /*!< Are we debugging stun? */
87 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
88 static struct sockaddr_in rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
89 #ifdef SO_NO_CHECK
90 static int nochecksums;
91 #endif
93 /* Uncomment this to enable more intense native bridging, but note: this is currently buggy */
94 /* #define P2P_INTENSE */
96 /*!
97 * \brief Structure representing a RTP session.
99 * 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 [...]"
102 /*! \brief The value of each payload format mapping: */
103 struct rtpPayloadType {
104 int isAstFormat; /*!< whether the following code is an AST_FORMAT */
105 int code;
109 /*! \brief RTP session description */
110 struct ast_rtp {
111 int s;
112 struct ast_frame f;
113 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
114 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
115 unsigned int themssrc; /*!< Their SSRC */
116 unsigned int rxssrc;
117 unsigned int lastts;
118 unsigned int lastrxts;
119 unsigned int lastividtimestamp;
120 unsigned int lastovidtimestamp;
121 unsigned int lasteventseqn;
122 int lastrxseqno; /*!< Last received sequence number */
123 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
124 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
125 unsigned int rxcount; /*!< How many packets have we received? */
126 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
127 unsigned int txcount; /*!< How many packets have we sent? */
128 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
129 unsigned int cycles; /*!< Shifted count of sequence number cycles */
130 double rxjitter; /*!< Interarrival jitter at the moment */
131 double rxtransit; /*!< Relative transit time for previous packet */
132 int lasttxformat;
133 int lastrxformat;
135 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
136 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
137 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
139 /* DTMF Reception Variables */
140 char resp;
141 unsigned int lastevent;
142 int dtmfcount;
143 unsigned int dtmfsamples;
144 /* DTMF Transmission Variables */
145 unsigned int lastdigitts;
146 char sending_digit; /*!< boolean - are we sending digits */
147 char send_digit; /*!< digit we are sending */
148 int send_payload;
149 int send_duration;
150 int nat;
151 unsigned int flags;
152 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
153 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
154 struct timeval rxcore;
155 struct timeval txcore;
156 double drxcore; /*!< The double representation of the first received packet */
157 struct timeval lastrx; /*!< timeval when we last received a packet */
158 struct timeval dtmfmute;
159 struct ast_smoother *smoother;
160 int *ioid;
161 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
162 unsigned short rxseqno;
163 struct sched_context *sched;
164 struct io_context *io;
165 void *data;
166 ast_rtp_callback callback;
167 ast_mutex_t bridge_lock;
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 */
175 int set_marker_bit:1; /*!< Whether to set the marker bit or not */
178 /* Forward declarations */
179 static int ast_rtcp_write(const void *data);
180 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
181 static int ast_rtcp_write_sr(const void *data);
182 static int ast_rtcp_write_rr(const void *data);
183 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
184 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
185 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
187 #define FLAG_3389_WARNING (1 << 0)
188 #define FLAG_NAT_ACTIVE (3 << 1)
189 #define FLAG_NAT_INACTIVE (0 << 1)
190 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
191 #define FLAG_HAS_DTMF (1 << 3)
192 #define FLAG_P2P_SENT_MARK (1 << 4)
193 #define FLAG_P2P_NEED_DTMF (1 << 5)
194 #define FLAG_CALLBACK_MODE (1 << 6)
195 #define FLAG_DTMF_COMPENSATE (1 << 7)
196 #define FLAG_HAS_STUN (1 << 8)
199 * \brief Structure defining an RTCP session.
201 * The concept "RTCP session" is not defined in RFC 3550, but since
202 * this structure is analogous to ast_rtp, which tracks a RTP session,
203 * it is logical to think of this as a RTCP session.
205 * RTCP packet is defined on page 9 of RFC 3550.
208 struct ast_rtcp {
209 int s; /*!< Socket */
210 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
211 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
212 unsigned int soc; /*!< What they told us */
213 unsigned int spc; /*!< What they told us */
214 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
215 struct timeval rxlsr; /*!< Time when we got their last SR */
216 struct timeval txlsr; /*!< Time when we sent or last SR*/
217 unsigned int expected_prior; /*!< no. packets in previous interval */
218 unsigned int received_prior; /*!< no. packets received in previous interval */
219 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
220 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
221 unsigned int sr_count; /*!< number of SRs we've sent */
222 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
223 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
224 double rtt; /*!< Last reported rtt */
225 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
226 unsigned int reported_lost; /*!< Reported lost packets in their RR */
227 char quality[AST_MAX_USER_FIELD];
228 double maxrxjitter;
229 double minrxjitter;
230 double maxrtt;
231 double minrtt;
232 int sendfur;
236 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
238 /* XXX Maybe stun belongs in another file if it ever has use outside of RTP */
239 struct stun_header {
240 unsigned short msgtype;
241 unsigned short msglen;
242 stun_trans_id id;
243 unsigned char ies[0];
244 } __attribute__((packed));
246 struct stun_attr {
247 unsigned short attr;
248 unsigned short len;
249 unsigned char value[0];
250 } __attribute__((packed));
252 struct stun_addr {
253 unsigned char unused;
254 unsigned char family;
255 unsigned short port;
256 unsigned int addr;
257 } __attribute__((packed));
259 #define STUN_IGNORE (0)
260 #define STUN_ACCEPT (1)
262 #define STUN_BINDREQ 0x0001
263 #define STUN_BINDRESP 0x0101
264 #define STUN_BINDERR 0x0111
265 #define STUN_SECREQ 0x0002
266 #define STUN_SECRESP 0x0102
267 #define STUN_SECERR 0x0112
269 #define STUN_MAPPED_ADDRESS 0x0001
270 #define STUN_RESPONSE_ADDRESS 0x0002
271 #define STUN_CHANGE_REQUEST 0x0003
272 #define STUN_SOURCE_ADDRESS 0x0004
273 #define STUN_CHANGED_ADDRESS 0x0005
274 #define STUN_USERNAME 0x0006
275 #define STUN_PASSWORD 0x0007
276 #define STUN_MESSAGE_INTEGRITY 0x0008
277 #define STUN_ERROR_CODE 0x0009
278 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
279 #define STUN_REFLECTED_FROM 0x000b
281 static const char *stun_msg2str(int msg)
283 switch(msg) {
284 case STUN_BINDREQ:
285 return "Binding Request";
286 case STUN_BINDRESP:
287 return "Binding Response";
288 case STUN_BINDERR:
289 return "Binding Error Response";
290 case STUN_SECREQ:
291 return "Shared Secret Request";
292 case STUN_SECRESP:
293 return "Shared Secret Response";
294 case STUN_SECERR:
295 return "Shared Secret Error Response";
297 return "Non-RFC3489 Message";
300 static const char *stun_attr2str(int msg)
302 switch(msg) {
303 case STUN_MAPPED_ADDRESS:
304 return "Mapped Address";
305 case STUN_RESPONSE_ADDRESS:
306 return "Response Address";
307 case STUN_CHANGE_REQUEST:
308 return "Change Request";
309 case STUN_SOURCE_ADDRESS:
310 return "Source Address";
311 case STUN_CHANGED_ADDRESS:
312 return "Changed Address";
313 case STUN_USERNAME:
314 return "Username";
315 case STUN_PASSWORD:
316 return "Password";
317 case STUN_MESSAGE_INTEGRITY:
318 return "Message Integrity";
319 case STUN_ERROR_CODE:
320 return "Error Code";
321 case STUN_UNKNOWN_ATTRIBUTES:
322 return "Unknown Attributes";
323 case STUN_REFLECTED_FROM:
324 return "Reflected From";
326 return "Non-RFC3489 Attribute";
329 struct stun_state {
330 const char *username;
331 const char *password;
334 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
336 if (stundebug)
337 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
338 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
339 switch(ntohs(attr->attr)) {
340 case STUN_USERNAME:
341 state->username = (const char *) (attr->value);
342 break;
343 case STUN_PASSWORD:
344 state->password = (const char *) (attr->value);
345 break;
346 default:
347 if (stundebug)
348 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
349 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
351 return 0;
354 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
356 int size = sizeof(**attr) + strlen(s);
357 if (*left > size) {
358 (*attr)->attr = htons(attrval);
359 (*attr)->len = htons(strlen(s));
360 memcpy((*attr)->value, s, strlen(s));
361 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
362 *len += size;
363 *left -= size;
367 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
369 int size = sizeof(**attr) + 8;
370 struct stun_addr *addr;
371 if (*left > size) {
372 (*attr)->attr = htons(attrval);
373 (*attr)->len = htons(8);
374 addr = (struct stun_addr *)((*attr)->value);
375 addr->unused = 0;
376 addr->family = 0x01;
377 addr->port = sin->sin_port;
378 addr->addr = sin->sin_addr.s_addr;
379 (*attr) = (struct stun_attr *)((*attr)->value + 8);
380 *len += size;
381 *left -= size;
385 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
387 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
388 (struct sockaddr *)dst, sizeof(*dst));
391 static void stun_req_id(struct stun_header *req)
393 int x;
394 for (x=0;x<4;x++)
395 req->id.id[x] = ast_random();
398 size_t ast_rtp_alloc_size(void)
400 return sizeof(struct ast_rtp);
403 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
405 struct stun_header *req;
406 unsigned char reqdata[1024];
407 int reqlen, reqleft;
408 struct stun_attr *attr;
410 req = (struct stun_header *)reqdata;
411 stun_req_id(req);
412 reqlen = 0;
413 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
414 req->msgtype = 0;
415 req->msglen = 0;
416 attr = (struct stun_attr *)req->ies;
417 if (username)
418 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
419 req->msglen = htons(reqlen);
420 req->msgtype = htons(STUN_BINDREQ);
421 stun_send(rtp->s, suggestion, req);
424 static int stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len)
426 struct stun_header *resp, *hdr = (struct stun_header *)data;
427 struct stun_attr *attr;
428 struct stun_state st;
429 int ret = STUN_IGNORE;
430 unsigned char respdata[1024];
431 int resplen, respleft;
433 if (len < sizeof(struct stun_header)) {
434 if (option_debug)
435 ast_log(LOG_DEBUG, "Runt STUN packet (only %zd, wanting at least %zd)\n", len, sizeof(struct stun_header));
436 return -1;
438 if (stundebug)
439 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), ntohs(hdr->msglen));
440 if (ntohs(hdr->msglen) > len - sizeof(struct stun_header)) {
441 if (option_debug)
442 ast_log(LOG_DEBUG, "Scrambled STUN packet length (got %d, expecting %zd)\n", ntohs(hdr->msglen), len - sizeof(struct stun_header));
443 } else
444 len = ntohs(hdr->msglen);
445 data += sizeof(struct stun_header);
446 memset(&st, 0, sizeof(st));
447 while(len) {
448 if (len < sizeof(struct stun_attr)) {
449 if (option_debug)
450 ast_log(LOG_DEBUG, "Runt Attribute (got %zd, expecting %zd)\n", len, sizeof(struct stun_attr));
451 break;
453 attr = (struct stun_attr *)data;
454 if ((ntohs(attr->len) + sizeof(struct stun_attr)) > len) {
455 if (option_debug)
456 ast_log(LOG_DEBUG, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", (int) (ntohs(attr->len) + sizeof(struct stun_attr)), (int) len);
457 break;
459 if (stun_process_attr(&st, attr)) {
460 if (option_debug)
461 ast_log(LOG_DEBUG, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
462 break;
464 /* Clear attribute in case previous entry was a string */
465 attr->attr = 0;
466 data += ntohs(attr->len) + sizeof(struct stun_attr);
467 len -= ntohs(attr->len) + sizeof(struct stun_attr);
469 /* Null terminate any string */
470 *data = '\0';
471 resp = (struct stun_header *)respdata;
472 resplen = 0;
473 respleft = sizeof(respdata) - sizeof(struct stun_header);
474 resp->id = hdr->id;
475 resp->msgtype = 0;
476 resp->msglen = 0;
477 attr = (struct stun_attr *)resp->ies;
478 if (!len) {
479 switch(ntohs(hdr->msgtype)) {
480 case STUN_BINDREQ:
481 if (stundebug)
482 ast_verbose("STUN Bind Request, username: %s\n",
483 st.username ? st.username : "<none>");
484 if (st.username)
485 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
486 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
487 resp->msglen = htons(resplen);
488 resp->msgtype = htons(STUN_BINDRESP);
489 stun_send(s, src, resp);
490 ret = STUN_ACCEPT;
491 break;
492 default:
493 if (stundebug)
494 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
497 return ret;
500 /*! \brief List of current sessions */
501 static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
503 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
505 unsigned int sec, usec, frac;
506 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
507 usec = tv.tv_usec;
508 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
509 *msw = sec;
510 *lsw = frac;
513 int ast_rtp_fd(struct ast_rtp *rtp)
515 return rtp->s;
518 int ast_rtcp_fd(struct ast_rtp *rtp)
520 if (rtp->rtcp)
521 return rtp->rtcp->s;
522 return -1;
525 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
527 unsigned int interval;
528 /*! \todo XXX Do a more reasonable calculation on this one
529 * Look in RFC 3550 Section A.7 for an example*/
530 interval = rtcpinterval;
531 return interval;
534 /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
535 void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
537 rtp->rtptimeout = (-1) * rtp->rtptimeout;
538 rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
541 /*! \brief Set rtp timeout */
542 void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
544 rtp->rtptimeout = timeout;
547 /*! \brief Set rtp hold timeout */
548 void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
550 rtp->rtpholdtimeout = timeout;
553 /*! \brief set RTP keepalive interval */
554 void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
556 rtp->rtpkeepalive = period;
559 /*! \brief Get rtp timeout */
560 int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
562 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
563 return 0;
564 return rtp->rtptimeout;
567 /*! \brief Get rtp hold timeout */
568 int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
570 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
571 return 0;
572 return rtp->rtpholdtimeout;
575 /*! \brief Get RTP keepalive interval */
576 int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
578 return rtp->rtpkeepalive;
581 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
583 rtp->data = data;
586 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
588 rtp->callback = callback;
591 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
593 rtp->nat = nat;
596 int ast_rtp_getnat(struct ast_rtp *rtp)
598 return ast_test_flag(rtp, FLAG_NAT_ACTIVE);
601 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
603 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
606 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
608 ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
611 void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
613 ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
616 static struct ast_frame *send_dtmf(struct ast_rtp *rtp, enum ast_frame_type type)
618 if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
619 (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
620 if (option_debug)
621 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
622 rtp->resp = 0;
623 rtp->dtmfsamples = 0;
624 return &ast_null_frame;
626 if (option_debug)
627 ast_log(LOG_DEBUG, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
628 if (rtp->resp == 'X') {
629 rtp->f.frametype = AST_FRAME_CONTROL;
630 rtp->f.subclass = AST_CONTROL_FLASH;
631 } else {
632 rtp->f.frametype = type;
633 rtp->f.subclass = rtp->resp;
635 rtp->f.datalen = 0;
636 rtp->f.samples = 0;
637 rtp->f.mallocd = 0;
638 rtp->f.src = "RTP";
639 return &rtp->f;
643 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
645 if (rtpdebug == 0)
646 return 0;
647 if (rtpdebugaddr.sin_addr.s_addr) {
648 if (((ntohs(rtpdebugaddr.sin_port) != 0)
649 && (rtpdebugaddr.sin_port != addr->sin_port))
650 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
651 return 0;
653 return 1;
656 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
658 if (rtcpdebug == 0)
659 return 0;
660 if (rtcpdebugaddr.sin_addr.s_addr) {
661 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
662 && (rtcpdebugaddr.sin_port != addr->sin_port))
663 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
664 return 0;
666 return 1;
670 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
672 unsigned int event;
673 char resp = 0;
674 struct ast_frame *f = NULL;
675 event = ntohl(*((unsigned int *)(data)));
676 event &= 0x001F;
677 if (option_debug > 2 || rtpdebug)
678 ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
679 if (event < 10) {
680 resp = '0' + event;
681 } else if (event < 11) {
682 resp = '*';
683 } else if (event < 12) {
684 resp = '#';
685 } else if (event < 16) {
686 resp = 'A' + (event - 12);
687 } else if (event < 17) {
688 resp = 'X';
690 if (rtp->resp && (rtp->resp != resp)) {
691 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
693 rtp->resp = resp;
694 rtp->dtmfcount = dtmftimeout;
695 return f;
698 /*!
699 * \brief Process RTP DTMF and events according to RFC 2833.
701 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
703 * \param rtp
704 * \param data
705 * \param len
706 * \param seqno
707 * \returns
709 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp)
711 unsigned int event;
712 unsigned int event_end;
713 unsigned int samples;
714 char resp = 0;
715 struct ast_frame *f = NULL;
717 /* Figure out event, event end, and samples */
718 event = ntohl(*((unsigned int *)(data)));
719 event >>= 24;
720 event_end = ntohl(*((unsigned int *)(data)));
721 event_end <<= 8;
722 event_end >>= 24;
723 samples = ntohl(*((unsigned int *)(data)));
724 samples &= 0xFFFF;
726 /* Print out debug if turned on */
727 if (rtpdebug || option_debug > 2)
728 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
730 /* Figure out what digit was pressed */
731 if (event < 10) {
732 resp = '0' + event;
733 } else if (event < 11) {
734 resp = '*';
735 } else if (event < 12) {
736 resp = '#';
737 } else if (event < 16) {
738 resp = 'A' + (event - 12);
739 } else if (event < 17) { /* Event 16: Hook flash */
740 resp = 'X';
741 } else {
742 /* Not a supported event */
743 ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
744 return &ast_null_frame;
747 if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
748 if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
749 rtp->resp = resp;
750 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
751 f->len = 0;
752 rtp->lastevent = timestamp;
754 } else {
755 if ((!(rtp->resp) && (!(event_end & 0x80))) || (rtp->resp && rtp->resp != resp)) {
756 rtp->resp = resp;
757 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
758 } else if ((event_end & 0x80) && (rtp->lastevent != seqno) && rtp->resp) {
759 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
760 f->len = ast_tvdiff_ms(ast_samp2tv(samples, 8000), ast_tv(0, 0)); /* XXX hard coded 8kHz */
761 rtp->resp = 0;
762 rtp->lastevent = seqno;
766 rtp->dtmfcount = dtmftimeout;
767 rtp->dtmfsamples = samples;
769 return f;
773 * \brief Process Comfort Noise RTP.
775 * This is incomplete at the moment.
778 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
780 struct ast_frame *f = NULL;
781 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
782 totally help us out becuase we don't have an engine to keep it going and we are not
783 guaranteed to have it every 20ms or anything */
784 if (rtpdebug)
785 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
787 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
788 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
789 ast_inet_ntoa(rtp->them.sin_addr));
790 ast_set_flag(rtp, FLAG_3389_WARNING);
793 /* Must have at least one byte */
794 if (!len)
795 return NULL;
796 if (len < 24) {
797 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
798 rtp->f.datalen = len - 1;
799 rtp->f.offset = AST_FRIENDLY_OFFSET;
800 memcpy(rtp->f.data, data + 1, len - 1);
801 } else {
802 rtp->f.data = NULL;
803 rtp->f.offset = 0;
804 rtp->f.datalen = 0;
806 rtp->f.frametype = AST_FRAME_CNG;
807 rtp->f.subclass = data[0] & 0x7f;
808 rtp->f.datalen = len - 1;
809 rtp->f.samples = 0;
810 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
811 f = &rtp->f;
812 return f;
815 static int rtpread(int *id, int fd, short events, void *cbdata)
817 struct ast_rtp *rtp = cbdata;
818 struct ast_frame *f;
819 f = ast_rtp_read(rtp);
820 if (f) {
821 if (rtp->callback)
822 rtp->callback(rtp, f, rtp->data);
824 return 1;
827 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
829 socklen_t len;
830 int position, i, packetwords;
831 int res;
832 struct sockaddr_in sin;
833 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
834 unsigned int *rtcpheader;
835 int pt;
836 struct timeval now;
837 unsigned int length;
838 int rc;
839 double rttsec;
840 uint64_t rtt = 0;
841 unsigned int dlsr;
842 unsigned int lsr;
843 unsigned int msw;
844 unsigned int lsw;
845 unsigned int comp;
846 struct ast_frame *f = &ast_null_frame;
848 if (!rtp || !rtp->rtcp)
849 return &ast_null_frame;
851 len = sizeof(sin);
853 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
854 0, (struct sockaddr *)&sin, &len);
855 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
857 if (res < 0) {
858 ast_assert(errno != EBADF);
859 if (errno != EAGAIN) {
860 ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n", strerror(errno));
861 return NULL;
863 return &ast_null_frame;
866 packetwords = res / 4;
868 if (rtp->nat) {
869 /* Send to whoever sent to us */
870 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
871 (rtp->rtcp->them.sin_port != sin.sin_port)) {
872 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
873 if (option_debug || rtpdebug)
874 ast_log(LOG_DEBUG, "RTCP NAT: Got RTCP from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
878 if (option_debug)
879 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
881 /* Process a compound packet */
882 position = 0;
883 while (position < packetwords) {
884 i = position;
885 length = ntohl(rtcpheader[i]);
886 pt = (length & 0xff0000) >> 16;
887 rc = (length & 0x1f000000) >> 24;
888 length &= 0xffff;
890 if ((i + length) > packetwords) {
891 ast_log(LOG_WARNING, "RTCP Read too short\n");
892 return &ast_null_frame;
895 if (rtcp_debug_test_addr(&sin)) {
896 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
897 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
898 ast_verbose("Reception reports: %d\n", rc);
899 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
902 i += 2; /* Advance past header and ssrc */
904 switch (pt) {
905 case RTCP_PT_SR:
906 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
907 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
908 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
909 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
911 if (rtcp_debug_test_addr(&sin)) {
912 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
913 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
914 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
916 i += 5;
917 if (rc < 1)
918 break;
919 /* Intentional fall through */
920 case RTCP_PT_RR:
921 /* Don't handle multiple reception reports (rc > 1) yet */
922 /* Calculate RTT per RFC */
923 gettimeofday(&now, NULL);
924 timeval2ntp(now, &msw, &lsw);
925 if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
926 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
927 lsr = ntohl(rtcpheader[i + 4]);
928 dlsr = ntohl(rtcpheader[i + 5]);
929 rtt = comp - lsr - dlsr;
931 /* Convert end to end delay to usec (keeping the calculation in 64bit space)
932 sess->ee_delay = (eedelay * 1000) / 65536; */
933 if (rtt < 4294) {
934 rtt = (rtt * 1000000) >> 16;
935 } else {
936 rtt = (rtt * 1000) >> 16;
937 rtt *= 1000;
939 rtt = rtt / 1000.;
940 rttsec = rtt / 1000.;
942 if (comp - dlsr >= lsr) {
943 rtp->rtcp->accumulated_transit += rttsec;
944 rtp->rtcp->rtt = rttsec;
945 if (rtp->rtcp->maxrtt<rttsec)
946 rtp->rtcp->maxrtt = rttsec;
947 if (rtp->rtcp->minrtt>rttsec)
948 rtp->rtcp->minrtt = rttsec;
949 } else if (rtcp_debug_test_addr(&sin)) {
950 ast_verbose("Internal RTCP NTP clock skew detected: "
951 "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
952 "diff=%d\n",
953 lsr, comp, dlsr, dlsr / 65536,
954 (dlsr % 65536) * 1000 / 65536,
955 dlsr - (comp - lsr));
959 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
960 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
961 if (rtcp_debug_test_addr(&sin)) {
962 ast_verbose(" Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
963 ast_verbose(" Packets lost so far: %d\n", rtp->rtcp->reported_lost);
964 ast_verbose(" Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
965 ast_verbose(" Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
966 ast_verbose(" Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
967 ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
968 ast_verbose(" DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
969 if (rtt)
970 ast_verbose(" RTT: %lu(sec)\n", (unsigned long) rtt);
972 break;
973 case RTCP_PT_FUR:
974 if (rtcp_debug_test_addr(&sin))
975 ast_verbose("Received an RTCP Fast Update Request\n");
976 rtp->f.frametype = AST_FRAME_CONTROL;
977 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
978 rtp->f.datalen = 0;
979 rtp->f.samples = 0;
980 rtp->f.mallocd = 0;
981 rtp->f.src = "RTP";
982 f = &rtp->f;
983 break;
984 case RTCP_PT_SDES:
985 if (rtcp_debug_test_addr(&sin))
986 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
987 break;
988 case RTCP_PT_BYE:
989 if (rtcp_debug_test_addr(&sin))
990 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
991 break;
992 default:
993 if (option_debug)
994 ast_log(LOG_DEBUG, "Unknown RTCP packet (pt=%d) received from %s:%d\n", pt, ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
995 break;
997 position += (length + 1);
1000 return f;
1003 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
1005 struct timeval now;
1006 double transit;
1007 double current_time;
1008 double d;
1009 double dtv;
1010 double prog;
1012 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
1013 gettimeofday(&rtp->rxcore, NULL);
1014 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
1015 /* map timestamp to a real time */
1016 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
1017 rtp->rxcore.tv_sec -= timestamp / 8000;
1018 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
1019 /* Round to 0.1ms for nice, pretty timestamps */
1020 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
1021 if (rtp->rxcore.tv_usec < 0) {
1022 /* Adjust appropriately if necessary */
1023 rtp->rxcore.tv_usec += 1000000;
1024 rtp->rxcore.tv_sec -= 1;
1028 gettimeofday(&now,NULL);
1029 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
1030 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
1031 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
1032 if (tv->tv_usec >= 1000000) {
1033 tv->tv_usec -= 1000000;
1034 tv->tv_sec += 1;
1036 prog = (double)((timestamp-rtp->seedrxts)/8000.);
1037 dtv = (double)rtp->drxcore + (double)(prog);
1038 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
1039 transit = current_time - dtv;
1040 d = transit - rtp->rxtransit;
1041 rtp->rxtransit = transit;
1042 if (d<0)
1043 d=-d;
1044 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1045 if (rtp->rtcp && rtp->rxjitter > rtp->rtcp->maxrxjitter)
1046 rtp->rtcp->maxrxjitter = rtp->rxjitter;
1047 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1048 rtp->rtcp->minrxjitter = rtp->rxjitter;
1051 /*! \brief Perform a Packet2Packet RTP write */
1052 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, struct ast_rtp *bridged, unsigned int *rtpheader, int len, int hdrlen)
1054 int res = 0, payload = 0, bridged_payload = 0, mark;
1055 struct rtpPayloadType rtpPT;
1056 int reconstruct = ntohl(rtpheader[0]);
1058 /* Get fields from packet */
1059 payload = (reconstruct & 0x7f0000) >> 16;
1060 mark = (((reconstruct & 0x800000) >> 23) != 0);
1062 /* Check what the payload value should be */
1063 rtpPT = ast_rtp_lookup_pt(rtp, payload);
1065 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
1066 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
1067 return -1;
1069 /* Otherwise adjust bridged payload to match */
1070 bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
1072 /* 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 */
1073 if (!bridged->current_RTP_PT[bridged_payload].code)
1074 return -1;
1077 /* If the mark bit has not been sent yet... do it now */
1078 if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
1079 mark = 1;
1080 ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
1083 /* Reconstruct part of the packet */
1084 reconstruct &= 0xFF80FFFF;
1085 reconstruct |= (bridged_payload << 16);
1086 reconstruct |= (mark << 23);
1087 rtpheader[0] = htonl(reconstruct);
1089 /* Send the packet back out */
1090 res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
1091 if (res < 0) {
1092 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1093 ast_log(LOG_DEBUG, "RTP Transmission error of packet to %s:%d: %s\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), strerror(errno));
1094 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1095 if (option_debug || rtpdebug)
1096 ast_log(LOG_DEBUG, "RTP NAT: Can't write RTP to private address %s:%d, waiting for other end to send audio...\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port));
1097 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1099 return 0;
1100 } else if (rtp_debug_test_addr(&bridged->them))
1101 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);
1103 return 0;
1106 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
1108 int res;
1109 struct sockaddr_in sin;
1110 socklen_t len;
1111 unsigned int seqno;
1112 int version;
1113 int payloadtype;
1114 int hdrlen = 12;
1115 int padding;
1116 int mark;
1117 int ext;
1118 int cc;
1119 unsigned int ssrc;
1120 unsigned int timestamp;
1121 unsigned int *rtpheader;
1122 struct rtpPayloadType rtpPT;
1123 struct ast_rtp *bridged = NULL;
1125 /* If time is up, kill it */
1126 if (rtp->sending_digit)
1127 ast_rtp_senddigit_continuation(rtp);
1129 len = sizeof(sin);
1131 /* Cache where the header will go */
1132 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
1133 0, (struct sockaddr *)&sin, &len);
1135 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
1136 if (res < 0) {
1137 ast_assert(errno != EBADF);
1138 if (errno != EAGAIN) {
1139 ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
1140 return NULL;
1142 return &ast_null_frame;
1145 if (res < hdrlen) {
1146 ast_log(LOG_WARNING, "RTP Read too short\n");
1147 return &ast_null_frame;
1150 /* Get fields */
1151 seqno = ntohl(rtpheader[0]);
1153 /* Check RTP version */
1154 version = (seqno & 0xC0000000) >> 30;
1155 if (!version) {
1156 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res) == STUN_ACCEPT) &&
1157 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
1158 memcpy(&rtp->them, &sin, sizeof(rtp->them));
1160 return &ast_null_frame;
1163 #if 0 /* Allow to receive RTP stream with closed transmission path */
1164 /* If we don't have the other side's address, then ignore this */
1165 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1166 return &ast_null_frame;
1167 #endif
1169 /* Send to whoever send to us if NAT is turned on */
1170 if (rtp->nat) {
1171 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1172 (rtp->them.sin_port != sin.sin_port)) {
1173 rtp->them = sin;
1174 if (rtp->rtcp) {
1175 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1176 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1178 rtp->rxseqno = 0;
1179 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1180 if (option_debug || rtpdebug)
1181 ast_log(LOG_DEBUG, "RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
1185 /* If we are bridged to another RTP stream, send direct */
1186 if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
1187 return &ast_null_frame;
1189 if (version != 2)
1190 return &ast_null_frame;
1192 payloadtype = (seqno & 0x7f0000) >> 16;
1193 padding = seqno & (1 << 29);
1194 mark = seqno & (1 << 23);
1195 ext = seqno & (1 << 28);
1196 cc = (seqno & 0xF000000) >> 24;
1197 seqno &= 0xffff;
1198 timestamp = ntohl(rtpheader[1]);
1199 ssrc = ntohl(rtpheader[2]);
1201 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1202 if (option_debug || rtpdebug)
1203 ast_log(LOG_DEBUG, "Forcing Marker bit, because SSRC has changed\n");
1204 mark = 1;
1207 rtp->rxssrc = ssrc;
1209 if (padding) {
1210 /* Remove padding bytes */
1211 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1214 if (cc) {
1215 /* CSRC fields present */
1216 hdrlen += cc*4;
1219 if (ext) {
1220 /* RTP Extension present */
1221 hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
1222 hdrlen += 4;
1225 if (res < hdrlen) {
1226 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1227 return &ast_null_frame;
1230 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1232 if (rtp->rxcount==1) {
1233 /* This is the first RTP packet successfully received from source */
1234 rtp->seedrxseqno = seqno;
1237 /* Do not schedule RR if RTCP isn't run */
1238 if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
1239 /* Schedule transmission of Receiver Report */
1240 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1242 if ( (int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
1243 rtp->cycles += RTP_SEQ_MOD;
1245 rtp->lastrxseqno = seqno;
1247 if (rtp->themssrc==0)
1248 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1250 if (rtp_debug_test_addr(&sin))
1251 ast_verbose("Got RTP packet from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1252 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1254 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1255 if (!rtpPT.isAstFormat) {
1256 struct ast_frame *f = NULL;
1258 /* This is special in-band data that's not one of our codecs */
1259 if (rtpPT.code == AST_RTP_DTMF) {
1260 /* It's special -- rfc2833 process it */
1261 if (rtp_debug_test_addr(&sin)) {
1262 unsigned char *data;
1263 unsigned int event;
1264 unsigned int event_end;
1265 unsigned int duration;
1266 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1267 event = ntohl(*((unsigned int *)(data)));
1268 event >>= 24;
1269 event_end = ntohl(*((unsigned int *)(data)));
1270 event_end <<= 8;
1271 event_end >>= 24;
1272 duration = ntohl(*((unsigned int *)(data)));
1273 duration &= 0xFFFF;
1274 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);
1276 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp);
1277 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1278 /* It's really special -- process it the Cisco way */
1279 if (rtp->lastevent <= seqno || (rtp->lastevent >= 65530 && seqno <= 6)) {
1280 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1281 rtp->lastevent = seqno;
1283 } else if (rtpPT.code == AST_RTP_CN) {
1284 /* Comfort Noise */
1285 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1286 } else {
1287 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1289 return f ? f : &ast_null_frame;
1291 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1292 rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : AST_FRAME_VIDEO;
1294 if (!rtp->lastrxts)
1295 rtp->lastrxts = timestamp;
1297 rtp->rxseqno = seqno;
1299 /* Record received timestamp as last received now */
1300 rtp->lastrxts = timestamp;
1302 rtp->f.mallocd = 0;
1303 rtp->f.datalen = res - hdrlen;
1304 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1305 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1306 rtp->f.seqno = seqno;
1307 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
1308 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1309 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1310 ast_frame_byteswap_be(&rtp->f);
1311 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1312 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1313 ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
1314 rtp->f.ts = timestamp / 8;
1315 rtp->f.len = rtp->f.samples / (ast_format_rate(rtp->f.subclass) / 1000);
1316 } else {
1317 /* Video -- samples is # of samples vs. 90000 */
1318 if (!rtp->lastividtimestamp)
1319 rtp->lastividtimestamp = timestamp;
1320 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1321 rtp->lastividtimestamp = timestamp;
1322 rtp->f.delivery.tv_sec = 0;
1323 rtp->f.delivery.tv_usec = 0;
1324 if (mark)
1325 rtp->f.subclass |= 0x1;
1328 rtp->f.src = "RTP";
1329 return &rtp->f;
1332 /* The following array defines the MIME Media type (and subtype) for each
1333 of our codecs, or RTP-specific data type. */
1334 static struct {
1335 struct rtpPayloadType payloadType;
1336 char* type;
1337 char* subtype;
1338 } mimeTypes[] = {
1339 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1340 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1341 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1342 {{1, AST_FORMAT_ULAW}, "audio", "G711U"},
1343 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1344 {{1, AST_FORMAT_ALAW}, "audio", "G711A"},
1345 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1346 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1347 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1348 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1349 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1350 {{1, AST_FORMAT_G729A}, "audio", "G729A"},
1351 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1352 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1353 {{1, AST_FORMAT_G722}, "audio", "G722"},
1354 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
1355 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1356 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1357 {{0, AST_RTP_CN}, "audio", "CN"},
1358 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1359 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1360 {{1, AST_FORMAT_H261}, "video", "H261"},
1361 {{1, AST_FORMAT_H263}, "video", "H263"},
1362 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1363 {{1, AST_FORMAT_H264}, "video", "H264"},
1366 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1367 also, our own choices for dynamic payload types. This is our master
1368 table for transmission */
1369 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1370 [0] = {1, AST_FORMAT_ULAW},
1371 #ifdef USE_DEPRECATED_G726
1372 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1373 #endif
1374 [3] = {1, AST_FORMAT_GSM},
1375 [4] = {1, AST_FORMAT_G723_1},
1376 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1377 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1378 [7] = {1, AST_FORMAT_LPC10},
1379 [8] = {1, AST_FORMAT_ALAW},
1380 [9] = {1, AST_FORMAT_G722},
1381 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1382 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1383 [13] = {0, AST_RTP_CN},
1384 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1385 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1386 [18] = {1, AST_FORMAT_G729A},
1387 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1388 [26] = {1, AST_FORMAT_JPEG},
1389 [31] = {1, AST_FORMAT_H261},
1390 [34] = {1, AST_FORMAT_H263},
1391 [103] = {1, AST_FORMAT_H263_PLUS},
1392 [97] = {1, AST_FORMAT_ILBC},
1393 [99] = {1, AST_FORMAT_H264},
1394 [101] = {0, AST_RTP_DTMF},
1395 [110] = {1, AST_FORMAT_SPEEX},
1396 [111] = {1, AST_FORMAT_G726},
1397 [112] = {1, AST_FORMAT_G726_AAL2},
1398 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1401 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1403 int i;
1405 if (!rtp)
1406 return;
1408 ast_mutex_lock(&rtp->bridge_lock);
1410 for (i = 0; i < MAX_RTP_PT; ++i) {
1411 rtp->current_RTP_PT[i].isAstFormat = 0;
1412 rtp->current_RTP_PT[i].code = 0;
1415 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1416 rtp->rtp_lookup_code_cache_code = 0;
1417 rtp->rtp_lookup_code_cache_result = 0;
1419 ast_mutex_unlock(&rtp->bridge_lock);
1422 void ast_rtp_pt_default(struct ast_rtp* rtp)
1424 int i;
1426 ast_mutex_lock(&rtp->bridge_lock);
1428 /* Initialize to default payload types */
1429 for (i = 0; i < MAX_RTP_PT; ++i) {
1430 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1431 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1434 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1435 rtp->rtp_lookup_code_cache_code = 0;
1436 rtp->rtp_lookup_code_cache_result = 0;
1438 ast_mutex_unlock(&rtp->bridge_lock);
1441 void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
1443 unsigned int i;
1445 ast_mutex_lock(&dest->bridge_lock);
1446 ast_mutex_lock(&src->bridge_lock);
1448 for (i=0; i < MAX_RTP_PT; ++i) {
1449 dest->current_RTP_PT[i].isAstFormat =
1450 src->current_RTP_PT[i].isAstFormat;
1451 dest->current_RTP_PT[i].code =
1452 src->current_RTP_PT[i].code;
1454 dest->rtp_lookup_code_cache_isAstFormat = 0;
1455 dest->rtp_lookup_code_cache_code = 0;
1456 dest->rtp_lookup_code_cache_result = 0;
1458 ast_mutex_unlock(&src->bridge_lock);
1459 ast_mutex_unlock(&dest->bridge_lock);
1462 /*! \brief Get channel driver interface structure */
1463 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1465 struct ast_rtp_protocol *cur = NULL;
1467 AST_LIST_LOCK(&protos);
1468 AST_LIST_TRAVERSE(&protos, cur, list) {
1469 if (cur->type == chan->tech->type)
1470 break;
1472 AST_LIST_UNLOCK(&protos);
1474 return cur;
1477 int ast_rtp_early_bridge(struct ast_channel *dest, struct ast_channel *src)
1479 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1480 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1481 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1482 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED;
1483 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED;
1484 int srccodec, destcodec, nat_active = 0;
1486 /* Lock channels */
1487 ast_channel_lock(dest);
1488 if (src) {
1489 while(ast_channel_trylock(src)) {
1490 ast_channel_unlock(dest);
1491 usleep(1);
1492 ast_channel_lock(dest);
1496 /* Find channel driver interfaces */
1497 destpr = get_proto(dest);
1498 if (src)
1499 srcpr = get_proto(src);
1500 if (!destpr) {
1501 if (option_debug)
1502 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1503 ast_channel_unlock(dest);
1504 if (src)
1505 ast_channel_unlock(src);
1506 return 0;
1508 if (!srcpr) {
1509 if (option_debug)
1510 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src ? src->name : "<unspecified>");
1511 ast_channel_unlock(dest);
1512 if (src)
1513 ast_channel_unlock(src);
1514 return 0;
1517 /* Get audio and video interface (if native bridge is possible) */
1518 audio_dest_res = destpr->get_rtp_info(dest, &destp);
1519 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
1520 if (srcpr) {
1521 audio_src_res = srcpr->get_rtp_info(src, &srcp);
1522 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
1525 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1526 if (audio_dest_res != AST_RTP_TRY_NATIVE) {
1527 /* Somebody doesn't want to play... */
1528 ast_channel_unlock(dest);
1529 if (src)
1530 ast_channel_unlock(src);
1531 return 0;
1533 if (audio_src_res == AST_RTP_TRY_NATIVE && srcpr->get_codec)
1534 srccodec = srcpr->get_codec(src);
1535 else
1536 srccodec = 0;
1537 if (audio_dest_res == AST_RTP_TRY_NATIVE && destpr->get_codec)
1538 destcodec = destpr->get_codec(dest);
1539 else
1540 destcodec = 0;
1541 /* Ensure we have at least one matching codec */
1542 if (!(srccodec & destcodec)) {
1543 ast_channel_unlock(dest);
1544 if (src)
1545 ast_channel_unlock(src);
1546 return 0;
1548 /* Consider empty media as non-existant */
1549 if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
1550 srcp = NULL;
1551 /* If the client has NAT stuff turned on then just safe NAT is active */
1552 if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1553 nat_active = 1;
1554 /* Bridge media early */
1555 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, nat_active))
1556 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src ? src->name : "<unspecified>");
1557 ast_channel_unlock(dest);
1558 if (src)
1559 ast_channel_unlock(src);
1560 if (option_debug)
1561 ast_log(LOG_DEBUG, "Setting early bridge SDP of '%s' with that of '%s'\n", dest->name, src ? src->name : "<unspecified>");
1562 return 1;
1565 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1567 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1568 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1569 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1570 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED;
1571 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED;
1572 int srccodec, destcodec;
1574 /* Lock channels */
1575 ast_channel_lock(dest);
1576 while(ast_channel_trylock(src)) {
1577 ast_channel_unlock(dest);
1578 usleep(1);
1579 ast_channel_lock(dest);
1582 /* Find channel driver interfaces */
1583 if (!(destpr = get_proto(dest))) {
1584 if (option_debug)
1585 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1586 ast_channel_unlock(dest);
1587 ast_channel_unlock(src);
1588 return 0;
1590 if (!(srcpr = get_proto(src))) {
1591 if (option_debug)
1592 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
1593 ast_channel_unlock(dest);
1594 ast_channel_unlock(src);
1595 return 0;
1598 /* Get audio and video interface (if native bridge is possible) */
1599 audio_dest_res = destpr->get_rtp_info(dest, &destp);
1600 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
1601 audio_src_res = srcpr->get_rtp_info(src, &srcp);
1602 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
1604 /* Ensure we have at least one matching codec */
1605 if (srcpr->get_codec)
1606 srccodec = srcpr->get_codec(src);
1607 else
1608 srccodec = 0;
1609 if (destpr->get_codec)
1610 destcodec = destpr->get_codec(dest);
1611 else
1612 destcodec = 0;
1614 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1615 if (audio_dest_res != AST_RTP_TRY_NATIVE || audio_src_res != AST_RTP_TRY_NATIVE || !(srccodec & destcodec)) {
1616 /* Somebody doesn't want to play... */
1617 ast_channel_unlock(dest);
1618 ast_channel_unlock(src);
1619 return 0;
1621 ast_rtp_pt_copy(destp, srcp);
1622 if (vdestp && vsrcp)
1623 ast_rtp_pt_copy(vdestp, vsrcp);
1624 if (media) {
1625 /* Bridge early */
1626 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1627 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1629 ast_channel_unlock(dest);
1630 ast_channel_unlock(src);
1631 if (option_debug)
1632 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1633 return 1;
1636 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1637 * By default, use the well-known value for this type (although it may
1638 * still be set to a different value by a subsequent "a=rtpmap:" line)
1640 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1642 if (pt < 0 || pt > MAX_RTP_PT || static_RTP_PT[pt].code == 0)
1643 return; /* bogus payload type */
1645 ast_mutex_lock(&rtp->bridge_lock);
1646 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1647 ast_mutex_unlock(&rtp->bridge_lock);
1650 /*! \brief remove setting from payload type list if the rtpmap header indicates
1651 an unknown media type */
1652 void ast_rtp_unset_m_type(struct ast_rtp* rtp, int pt)
1654 if (pt < 0 || pt > MAX_RTP_PT)
1655 return; /* bogus payload type */
1657 ast_mutex_lock(&rtp->bridge_lock);
1658 rtp->current_RTP_PT[pt].isAstFormat = 0;
1659 rtp->current_RTP_PT[pt].code = 0;
1660 ast_mutex_unlock(&rtp->bridge_lock);
1663 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1664 * an SDP "a=rtpmap:" line.
1665 * \return 0 if the MIME type was found and set, -1 if it wasn't found
1667 int ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
1668 char *mimeType, char *mimeSubtype,
1669 enum ast_rtp_options options)
1671 unsigned int i;
1672 int found = 0;
1674 if (pt < 0 || pt > MAX_RTP_PT)
1675 return -1; /* bogus payload type */
1677 ast_mutex_lock(&rtp->bridge_lock);
1679 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1680 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1681 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1682 found = 1;
1683 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1684 if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
1685 mimeTypes[i].payloadType.isAstFormat &&
1686 (options & AST_RTP_OPT_G726_NONSTANDARD))
1687 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
1688 break;
1692 ast_mutex_unlock(&rtp->bridge_lock);
1694 return (found ? 0 : -1);
1697 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
1698 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1699 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1700 int* astFormats, int* nonAstFormats)
1702 int pt;
1704 ast_mutex_lock(&rtp->bridge_lock);
1706 *astFormats = *nonAstFormats = 0;
1707 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1708 if (rtp->current_RTP_PT[pt].isAstFormat) {
1709 *astFormats |= rtp->current_RTP_PT[pt].code;
1710 } else {
1711 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
1715 ast_mutex_unlock(&rtp->bridge_lock);
1717 return;
1720 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
1722 struct rtpPayloadType result;
1724 result.isAstFormat = result.code = 0;
1726 if (pt < 0 || pt > MAX_RTP_PT)
1727 return result; /* bogus payload type */
1729 /* Start with negotiated codecs */
1730 ast_mutex_lock(&rtp->bridge_lock);
1731 result = rtp->current_RTP_PT[pt];
1732 ast_mutex_unlock(&rtp->bridge_lock);
1734 /* If it doesn't exist, check our static RTP type list, just in case */
1735 if (!result.code)
1736 result = static_RTP_PT[pt];
1738 return result;
1741 /*! \brief Looks up an RTP code out of our *static* outbound list */
1742 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
1744 int pt = 0;
1746 ast_mutex_lock(&rtp->bridge_lock);
1748 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
1749 code == rtp->rtp_lookup_code_cache_code) {
1750 /* Use our cached mapping, to avoid the overhead of the loop below */
1751 pt = rtp->rtp_lookup_code_cache_result;
1752 ast_mutex_unlock(&rtp->bridge_lock);
1753 return pt;
1756 /* Check the dynamic list first */
1757 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1758 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
1759 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1760 rtp->rtp_lookup_code_cache_code = code;
1761 rtp->rtp_lookup_code_cache_result = pt;
1762 ast_mutex_unlock(&rtp->bridge_lock);
1763 return pt;
1767 /* Then the static list */
1768 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1769 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
1770 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1771 rtp->rtp_lookup_code_cache_code = code;
1772 rtp->rtp_lookup_code_cache_result = pt;
1773 ast_mutex_unlock(&rtp->bridge_lock);
1774 return pt;
1778 ast_mutex_unlock(&rtp->bridge_lock);
1780 return -1;
1783 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
1784 enum ast_rtp_options options)
1786 unsigned int i;
1788 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1789 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
1790 if (isAstFormat &&
1791 (code == AST_FORMAT_G726_AAL2) &&
1792 (options & AST_RTP_OPT_G726_NONSTANDARD))
1793 return "G726-32";
1794 else
1795 return mimeTypes[i].subtype;
1799 return "";
1802 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
1803 const int isAstFormat, enum ast_rtp_options options)
1805 int format;
1806 unsigned len;
1807 char *end = buf;
1808 char *start = buf;
1810 if (!buf || !size)
1811 return NULL;
1813 snprintf(end, size, "0x%x (", capability);
1815 len = strlen(end);
1816 end += len;
1817 size -= len;
1818 start = end;
1820 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
1821 if (capability & format) {
1822 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
1824 snprintf(end, size, "%s|", name);
1825 len = strlen(end);
1826 end += len;
1827 size -= len;
1831 if (start == end)
1832 snprintf(start, size, "nothing)");
1833 else if (size > 1)
1834 *(end -1) = ')';
1836 return buf;
1839 static int rtp_socket(void)
1841 int s;
1842 long flags;
1843 s = socket(AF_INET, SOCK_DGRAM, 0);
1844 if (s > -1) {
1845 flags = fcntl(s, F_GETFL);
1846 fcntl(s, F_SETFL, flags | O_NONBLOCK);
1847 #ifdef SO_NO_CHECK
1848 if (nochecksums)
1849 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
1850 #endif
1852 return s;
1856 * \brief Initialize a new RTCP session.
1858 * \returns The newly initialized RTCP session.
1860 static struct ast_rtcp *ast_rtcp_new(void)
1862 struct ast_rtcp *rtcp;
1864 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
1865 return NULL;
1866 rtcp->s = rtp_socket();
1867 rtcp->us.sin_family = AF_INET;
1868 rtcp->them.sin_family = AF_INET;
1869 rtcp->schedid = -1;
1871 if (rtcp->s < 0) {
1872 free(rtcp);
1873 ast_log(LOG_WARNING, "Unable to allocate RTCP socket: %s\n", strerror(errno));
1874 return NULL;
1877 return rtcp;
1881 * \brief Initialize a new RTP structure.
1884 void ast_rtp_new_init(struct ast_rtp *rtp)
1886 ast_mutex_init(&rtp->bridge_lock);
1888 rtp->them.sin_family = AF_INET;
1889 rtp->us.sin_family = AF_INET;
1890 rtp->ssrc = ast_random();
1891 rtp->seqno = ast_random() & 0xffff;
1892 ast_set_flag(rtp, FLAG_HAS_DTMF);
1894 return;
1897 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
1899 struct ast_rtp *rtp;
1900 int x;
1901 int first;
1902 int startplace;
1904 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
1905 return NULL;
1907 ast_rtp_new_init(rtp);
1909 rtp->s = rtp_socket();
1910 if (rtp->s < 0) {
1911 free(rtp);
1912 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1913 return NULL;
1915 if (sched && rtcpenable) {
1916 rtp->sched = sched;
1917 rtp->rtcp = ast_rtcp_new();
1920 /* Select a random port number in the range of possible RTP */
1921 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
1922 x = x & ~1;
1923 /* Save it for future references. */
1924 startplace = x;
1925 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1926 for (;;) {
1927 /* Must be an even port number by RTP spec */
1928 rtp->us.sin_port = htons(x);
1929 rtp->us.sin_addr = addr;
1930 /* If there's rtcp, initialize it as well. */
1931 if (rtp->rtcp) {
1932 rtp->rtcp->us.sin_port = htons(x + 1);
1933 rtp->rtcp->us.sin_addr = addr;
1935 /* Try to bind it/them. */
1936 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1937 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1938 break;
1939 if (!first) {
1940 /* Primary bind succeeded! Gotta recreate it */
1941 close(rtp->s);
1942 rtp->s = rtp_socket();
1944 if (errno != EADDRINUSE) {
1945 /* We got an error that wasn't expected, abort! */
1946 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1947 close(rtp->s);
1948 if (rtp->rtcp) {
1949 close(rtp->rtcp->s);
1950 free(rtp->rtcp);
1952 free(rtp);
1953 return NULL;
1955 /* The port was used, increment it (by two). */
1956 x += 2;
1957 /* Did we go over the limit ? */
1958 if (x > rtpend)
1959 /* then, start from the begingig. */
1960 x = (rtpstart + 1) & ~1;
1961 /* Check if we reached the place were we started. */
1962 if (x == startplace) {
1963 /* If so, there's no ports available. */
1964 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1965 close(rtp->s);
1966 if (rtp->rtcp) {
1967 close(rtp->rtcp->s);
1968 free(rtp->rtcp);
1970 free(rtp);
1971 return NULL;
1974 rtp->sched = sched;
1975 rtp->io = io;
1976 if (callbackmode) {
1977 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1978 ast_set_flag(rtp, FLAG_CALLBACK_MODE);
1980 ast_rtp_pt_default(rtp);
1981 return rtp;
1984 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1986 struct in_addr ia;
1988 memset(&ia, 0, sizeof(ia));
1989 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1992 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1994 int res;
1996 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1997 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1998 return res;
2001 void ast_rtp_new_source(struct ast_rtp *rtp)
2003 rtp->set_marker_bit = 1;
2004 return;
2007 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2009 rtp->them.sin_port = them->sin_port;
2010 rtp->them.sin_addr = them->sin_addr;
2011 if (rtp->rtcp) {
2012 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
2013 rtp->rtcp->them.sin_addr = them->sin_addr;
2015 rtp->rxseqno = 0;
2018 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2020 if ((them->sin_family != AF_INET) ||
2021 (them->sin_port != rtp->them.sin_port) ||
2022 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
2023 them->sin_family = AF_INET;
2024 them->sin_port = rtp->them.sin_port;
2025 them->sin_addr = rtp->them.sin_addr;
2026 return 1;
2028 return 0;
2031 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
2033 *us = rtp->us;
2036 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
2038 struct ast_rtp *bridged = NULL;
2040 ast_mutex_lock(&rtp->bridge_lock);
2041 bridged = rtp->bridged;
2042 ast_mutex_unlock(&rtp->bridge_lock);
2044 return bridged;
2047 void ast_rtp_stop(struct ast_rtp *rtp)
2049 if (rtp->rtcp) {
2050 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2053 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
2054 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
2055 if (rtp->rtcp) {
2056 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
2057 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
2060 ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
2063 void ast_rtp_reset(struct ast_rtp *rtp)
2065 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
2066 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
2067 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
2068 rtp->lastts = 0;
2069 rtp->lastdigitts = 0;
2070 rtp->lastrxts = 0;
2071 rtp->lastividtimestamp = 0;
2072 rtp->lastovidtimestamp = 0;
2073 rtp->lasteventseqn = 0;
2074 rtp->lastevent = 0;
2075 rtp->lasttxformat = 0;
2076 rtp->lastrxformat = 0;
2077 rtp->dtmfcount = 0;
2078 rtp->dtmfsamples = 0;
2079 rtp->seqno = 0;
2080 rtp->rxseqno = 0;
2083 char *ast_rtp_get_quality(struct ast_rtp *rtp, struct ast_rtp_quality *qual)
2086 *ssrc our ssrc
2087 *themssrc their ssrc
2088 *lp lost packets
2089 *rxjitter our calculated jitter(rx)
2090 *rxcount no. received packets
2091 *txjitter reported jitter of the other end
2092 *txcount transmitted packets
2093 *rlp remote lost packets
2094 *rtt round trip time
2097 if (qual && rtp) {
2098 qual->local_ssrc = rtp->ssrc;
2099 qual->local_jitter = rtp->rxjitter;
2100 qual->local_count = rtp->rxcount;
2101 qual->remote_ssrc = rtp->themssrc;
2102 qual->remote_count = rtp->txcount;
2103 if (rtp->rtcp) {
2104 qual->local_lostpackets = rtp->rtcp->expected_prior - rtp->rtcp->received_prior;
2105 qual->remote_lostpackets = rtp->rtcp->reported_lost;
2106 qual->remote_jitter = rtp->rtcp->reported_jitter / 65536.0;
2107 qual->rtt = rtp->rtcp->rtt;
2110 if (rtp->rtcp) {
2111 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality),
2112 "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
2113 rtp->ssrc,
2114 rtp->themssrc,
2115 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2116 rtp->rxjitter,
2117 rtp->rxcount,
2118 (double)rtp->rtcp->reported_jitter / 65536.0,
2119 rtp->txcount,
2120 rtp->rtcp->reported_lost,
2121 rtp->rtcp->rtt);
2122 return rtp->rtcp->quality;
2123 } else
2124 return "<Unknown> - RTP/RTCP has already been destroyed";
2127 void ast_rtp_destroy(struct ast_rtp *rtp)
2129 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
2130 /*Print some info on the call here */
2131 ast_verbose(" RTP-stats\n");
2132 ast_verbose("* Our Receiver:\n");
2133 ast_verbose(" SSRC: %u\n", rtp->themssrc);
2134 ast_verbose(" Received packets: %u\n", rtp->rxcount);
2135 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
2136 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
2137 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
2138 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
2139 ast_verbose("* Our Sender:\n");
2140 ast_verbose(" SSRC: %u\n", rtp->ssrc);
2141 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2142 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
2143 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter / (unsigned int)65536.0);
2144 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
2145 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
2148 if (rtp->smoother)
2149 ast_smoother_free(rtp->smoother);
2150 if (rtp->ioid)
2151 ast_io_remove(rtp->io, rtp->ioid);
2152 if (rtp->s > -1)
2153 close(rtp->s);
2154 if (rtp->rtcp) {
2155 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2156 close(rtp->rtcp->s);
2157 free(rtp->rtcp);
2158 rtp->rtcp=NULL;
2161 ast_mutex_destroy(&rtp->bridge_lock);
2163 free(rtp);
2166 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2168 struct timeval t;
2169 long ms;
2170 if (ast_tvzero(rtp->txcore)) {
2171 rtp->txcore = ast_tvnow();
2172 /* Round to 20ms for nice, pretty timestamps */
2173 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2175 /* Use previous txcore if available */
2176 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2177 ms = ast_tvdiff_ms(t, rtp->txcore);
2178 if (ms < 0)
2179 ms = 0;
2180 /* Use what we just got for next time */
2181 rtp->txcore = t;
2182 return (unsigned int) ms;
2185 /*! \brief Send begin frames for DTMF */
2186 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
2188 unsigned int *rtpheader;
2189 int hdrlen = 12, res = 0, i = 0, payload = 0;
2190 char data[256];
2192 if ((digit <= '9') && (digit >= '0'))
2193 digit -= '0';
2194 else if (digit == '*')
2195 digit = 10;
2196 else if (digit == '#')
2197 digit = 11;
2198 else if ((digit >= 'A') && (digit <= 'D'))
2199 digit = digit - 'A' + 12;
2200 else if ((digit >= 'a') && (digit <= 'd'))
2201 digit = digit - 'a' + 12;
2202 else {
2203 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2204 return 0;
2207 /* If we have no peer, return immediately */
2208 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2209 return 0;
2211 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
2213 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2214 rtp->send_duration = 160;
2216 /* Get a pointer to the header */
2217 rtpheader = (unsigned int *)data;
2218 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2219 rtpheader[1] = htonl(rtp->lastdigitts);
2220 rtpheader[2] = htonl(rtp->ssrc);
2222 for (i = 0; i < 2; i++) {
2223 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2224 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2225 if (res < 0)
2226 ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
2227 ast_inet_ntoa(rtp->them.sin_addr),
2228 ntohs(rtp->them.sin_port), strerror(errno));
2229 if (rtp_debug_test_addr(&rtp->them))
2230 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2231 ast_inet_ntoa(rtp->them.sin_addr),
2232 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2233 /* Increment sequence number */
2234 rtp->seqno++;
2235 /* Increment duration */
2236 rtp->send_duration += 160;
2237 /* Clear marker bit and set seqno */
2238 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2241 /* Since we received a begin, we can safely store the digit and disable any compensation */
2242 rtp->sending_digit = 1;
2243 rtp->send_digit = digit;
2244 rtp->send_payload = payload;
2246 return 0;
2249 /*! \brief Send continuation frame for DTMF */
2250 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
2252 unsigned int *rtpheader;
2253 int hdrlen = 12, res = 0;
2254 char data[256];
2256 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2257 return 0;
2259 /* Setup packet to send */
2260 rtpheader = (unsigned int *)data;
2261 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2262 rtpheader[1] = htonl(rtp->lastdigitts);
2263 rtpheader[2] = htonl(rtp->ssrc);
2264 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2265 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2267 /* Transmit */
2268 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2269 if (res < 0)
2270 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2271 ast_inet_ntoa(rtp->them.sin_addr),
2272 ntohs(rtp->them.sin_port), strerror(errno));
2273 if (rtp_debug_test_addr(&rtp->them))
2274 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2275 ast_inet_ntoa(rtp->them.sin_addr),
2276 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2278 /* Increment sequence number */
2279 rtp->seqno++;
2280 /* Increment duration */
2281 rtp->send_duration += 160;
2283 return 0;
2286 /*! \brief Send end packets for DTMF */
2287 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
2289 unsigned int *rtpheader;
2290 int hdrlen = 12, res = 0, i = 0;
2291 char data[256];
2293 /* If no address, then bail out */
2294 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2295 return 0;
2297 if ((digit <= '9') && (digit >= '0'))
2298 digit -= '0';
2299 else if (digit == '*')
2300 digit = 10;
2301 else if (digit == '#')
2302 digit = 11;
2303 else if ((digit >= 'A') && (digit <= 'D'))
2304 digit = digit - 'A' + 12;
2305 else if ((digit >= 'a') && (digit <= 'd'))
2306 digit = digit - 'a' + 12;
2307 else {
2308 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2309 return 0;
2312 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2314 rtpheader = (unsigned int *)data;
2315 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2316 rtpheader[1] = htonl(rtp->lastdigitts);
2317 rtpheader[2] = htonl(rtp->ssrc);
2318 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2319 /* Set end bit */
2320 rtpheader[3] |= htonl((1 << 23));
2321 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2322 /* Send 3 termination packets */
2323 for (i = 0; i < 3; i++) {
2324 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2325 if (res < 0)
2326 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2327 ast_inet_ntoa(rtp->them.sin_addr),
2328 ntohs(rtp->them.sin_port), strerror(errno));
2329 if (rtp_debug_test_addr(&rtp->them))
2330 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2331 ast_inet_ntoa(rtp->them.sin_addr),
2332 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2334 rtp->sending_digit = 0;
2335 rtp->send_digit = 0;
2336 /* Increment lastdigitts */
2337 rtp->lastdigitts += 960;
2338 rtp->seqno++;
2340 return res;
2343 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
2344 int ast_rtcp_send_h261fur(void *data)
2346 struct ast_rtp *rtp = data;
2347 int res;
2349 rtp->rtcp->sendfur = 1;
2350 res = ast_rtcp_write(data);
2352 return res;
2355 /*! \brief Send RTCP sender's report */
2356 static int ast_rtcp_write_sr(const void *data)
2358 struct ast_rtp *rtp = (struct ast_rtp *)data;
2359 int res;
2360 int len = 0;
2361 struct timeval now;
2362 unsigned int now_lsw;
2363 unsigned int now_msw;
2364 unsigned int *rtcpheader;
2365 unsigned int lost;
2366 unsigned int extended;
2367 unsigned int expected;
2368 unsigned int expected_interval;
2369 unsigned int received_interval;
2370 int lost_interval;
2371 int fraction;
2372 struct timeval dlsr;
2373 char bdata[512];
2375 /* Commented condition is always not NULL if rtp->rtcp is not NULL */
2376 if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
2377 return 0;
2379 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
2380 ast_verbose("RTCP SR transmission error, rtcp halted\n");
2381 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2382 return 0;
2385 gettimeofday(&now, NULL);
2386 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
2387 rtcpheader = (unsigned int *)bdata;
2388 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
2389 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
2390 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
2391 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
2392 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
2393 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
2394 len += 28;
2396 extended = rtp->cycles + rtp->lastrxseqno;
2397 expected = extended - rtp->seedrxseqno + 1;
2398 if (rtp->rxcount > expected)
2399 expected += rtp->rxcount - expected;
2400 lost = expected - rtp->rxcount;
2401 expected_interval = expected - rtp->rtcp->expected_prior;
2402 rtp->rtcp->expected_prior = expected;
2403 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2404 rtp->rtcp->received_prior = rtp->rxcount;
2405 lost_interval = expected_interval - received_interval;
2406 if (expected_interval == 0 || lost_interval <= 0)
2407 fraction = 0;
2408 else
2409 fraction = (lost_interval << 8) / expected_interval;
2410 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2411 rtcpheader[7] = htonl(rtp->themssrc);
2412 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2413 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2414 rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
2415 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2416 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2417 len += 24;
2419 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2421 if (rtp->rtcp->sendfur) {
2422 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2423 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
2424 len += 8;
2425 rtp->rtcp->sendfur = 0;
2428 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2429 /* it can change mid call, and SDES can't) */
2430 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2431 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2432 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2433 len += 12;
2435 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2436 if (res < 0) {
2437 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));
2438 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2439 return 0;
2442 /* FIXME Don't need to get a new one */
2443 gettimeofday(&rtp->rtcp->txlsr, NULL);
2444 rtp->rtcp->sr_count++;
2446 rtp->rtcp->lastsrtxcount = rtp->txcount;
2448 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2449 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2450 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
2451 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2452 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
2453 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2454 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
2455 ast_verbose(" Report block:\n");
2456 ast_verbose(" Fraction lost: %u\n", fraction);
2457 ast_verbose(" Cumulative loss: %u\n", lost);
2458 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
2459 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
2460 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2462 return res;
2465 /*! \brief Send RTCP recepient's report */
2466 static int ast_rtcp_write_rr(const void *data)
2468 struct ast_rtp *rtp = (struct ast_rtp *)data;
2469 int res;
2470 int len = 32;
2471 unsigned int lost;
2472 unsigned int extended;
2473 unsigned int expected;
2474 unsigned int expected_interval;
2475 unsigned int received_interval;
2476 int lost_interval;
2477 struct timeval now;
2478 unsigned int *rtcpheader;
2479 char bdata[1024];
2480 struct timeval dlsr;
2481 int fraction;
2483 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2484 return 0;
2486 if (!rtp->rtcp->them.sin_addr.s_addr) {
2487 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
2488 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2489 return 0;
2492 extended = rtp->cycles + rtp->lastrxseqno;
2493 expected = extended - rtp->seedrxseqno + 1;
2494 lost = expected - rtp->rxcount;
2495 expected_interval = expected - rtp->rtcp->expected_prior;
2496 rtp->rtcp->expected_prior = expected;
2497 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2498 rtp->rtcp->received_prior = rtp->rxcount;
2499 lost_interval = expected_interval - received_interval;
2500 if (expected_interval == 0 || lost_interval <= 0)
2501 fraction = 0;
2502 else
2503 fraction = (lost_interval << 8) / expected_interval;
2504 gettimeofday(&now, NULL);
2505 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2506 rtcpheader = (unsigned int *)bdata;
2507 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2508 rtcpheader[1] = htonl(rtp->ssrc);
2509 rtcpheader[2] = htonl(rtp->themssrc);
2510 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2511 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2512 rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
2513 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2514 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2516 if (rtp->rtcp->sendfur) {
2517 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2518 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
2519 len += 8;
2520 rtp->rtcp->sendfur = 0;
2523 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2524 it can change mid call, and SDES can't) */
2525 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2526 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2527 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2528 len += 12;
2530 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2532 if (res < 0) {
2533 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2534 /* Remove the scheduler */
2535 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2536 return 0;
2539 rtp->rtcp->rr_count++;
2541 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2542 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2543 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2544 " IA jitter: %.4f\n"
2545 " Their last SR: %u\n"
2546 " DLSR: %4.4f (sec)\n\n",
2547 ast_inet_ntoa(rtp->rtcp->them.sin_addr),
2548 ntohs(rtp->rtcp->them.sin_port),
2549 rtp->ssrc, rtp->themssrc, fraction, lost,
2550 rtp->rxjitter,
2551 rtp->rtcp->themrxlsr,
2552 (double)(ntohl(rtcpheader[7])/65536.0));
2555 return res;
2558 /*! \brief Write and RTCP packet to the far end
2559 * \note Decide if we are going to send an SR (with Reception Block) or RR
2560 * RR is sent if we have not sent any rtp packets in the previous interval */
2561 static int ast_rtcp_write(const void *data)
2563 struct ast_rtp *rtp = (struct ast_rtp *)data;
2564 int res;
2566 if (!rtp || !rtp->rtcp)
2567 return 0;
2569 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2570 res = ast_rtcp_write_sr(data);
2571 else
2572 res = ast_rtcp_write_rr(data);
2574 return res;
2577 /*! \brief generate comfort noice (CNG) */
2578 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2580 unsigned int *rtpheader;
2581 int hdrlen = 12;
2582 int res;
2583 int payload;
2584 char data[256];
2585 level = 127 - (level & 0x7f);
2586 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2588 /* If we have no peer, return immediately */
2589 if (!rtp->them.sin_addr.s_addr)
2590 return 0;
2592 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2594 /* Get a pointer to the header */
2595 rtpheader = (unsigned int *)data;
2596 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2597 rtpheader[1] = htonl(rtp->lastts);
2598 rtpheader[2] = htonl(rtp->ssrc);
2599 data[12] = level;
2600 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2601 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2602 if (res <0)
2603 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));
2604 if (rtp_debug_test_addr(&rtp->them))
2605 ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
2606 , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
2609 return 0;
2612 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2614 unsigned char *rtpheader;
2615 int hdrlen = 12;
2616 int res;
2617 unsigned int ms;
2618 int pred;
2619 int mark = 0;
2621 ms = calc_txstamp(rtp, &f->delivery);
2622 /* Default prediction */
2623 if (f->frametype == AST_FRAME_VOICE) {
2624 pred = rtp->lastts + f->samples;
2626 /* Re-calculate last TS */
2627 rtp->lastts = rtp->lastts + ms * 8;
2628 if (ast_tvzero(f->delivery)) {
2629 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
2630 and if so, go with our prediction */
2631 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
2632 rtp->lastts = pred;
2633 else {
2634 if (option_debug > 2)
2635 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2636 mark = 1;
2639 } else if (f->frametype == AST_FRAME_VIDEO) {
2640 mark = f->subclass & 0x1;
2641 pred = rtp->lastovidtimestamp + f->samples;
2642 /* Re-calculate last TS */
2643 rtp->lastts = rtp->lastts + ms * 90;
2644 /* If it's close to our prediction, go for it */
2645 if (ast_tvzero(f->delivery)) {
2646 if (abs(rtp->lastts - pred) < 7200) {
2647 rtp->lastts = pred;
2648 rtp->lastovidtimestamp += f->samples;
2649 } else {
2650 if (option_debug > 2)
2651 ast_log(LOG_DEBUG, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, f->samples);
2652 rtp->lastovidtimestamp = rtp->lastts;
2657 /* If we have been explicitly told to set the marker bit do so */
2658 if (rtp->set_marker_bit) {
2659 mark = 1;
2660 rtp->set_marker_bit = 0;
2663 /* If the timestamp for non-digit packets has moved beyond the timestamp
2664 for digits, update the digit timestamp.
2666 if (rtp->lastts > rtp->lastdigitts)
2667 rtp->lastdigitts = rtp->lastts;
2669 if (ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO))
2670 rtp->lastts = f->ts * 8;
2672 /* Get a pointer to the header */
2673 rtpheader = (unsigned char *)(f->data - hdrlen);
2675 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
2676 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
2677 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
2679 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2680 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2681 if (res <0) {
2682 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
2683 ast_log(LOG_DEBUG, "RTP Transmission error of packet %d to %s:%d: %s\n", rtp->seqno, ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
2684 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
2685 /* Only give this error message once if we are not RTP debugging */
2686 if (option_debug || rtpdebug)
2687 ast_log(LOG_DEBUG, "RTP NAT: Can't write RTP to private address %s:%d, waiting for other end to send audio...\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
2688 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
2690 } else {
2691 rtp->txcount++;
2692 rtp->txoctetcount +=(res - hdrlen);
2694 if (rtp->rtcp && rtp->rtcp->schedid < 1)
2695 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
2698 if (rtp_debug_test_addr(&rtp->them))
2699 ast_verbose("Sent RTP packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2700 ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
2703 rtp->seqno++;
2705 return 0;
2708 int ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
2710 int x;
2711 for (x = 0; x < 32; x++) { /* Ugly way */
2712 rtp->pref.order[x] = prefs->order[x];
2713 rtp->pref.framing[x] = prefs->framing[x];
2715 if (rtp->smoother)
2716 ast_smoother_free(rtp->smoother);
2717 rtp->smoother = NULL;
2718 return 0;
2721 struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
2723 return &rtp->pref;
2726 int ast_rtp_codec_getformat(int pt)
2728 if (pt < 0 || pt > MAX_RTP_PT)
2729 return 0; /* bogus payload type */
2731 if (static_RTP_PT[pt].isAstFormat)
2732 return static_RTP_PT[pt].code;
2733 else
2734 return 0;
2737 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
2739 struct ast_frame *f;
2740 int codec;
2741 int hdrlen = 12;
2742 int subclass;
2745 /* If we have no peer, return immediately */
2746 if (!rtp->them.sin_addr.s_addr)
2747 return 0;
2749 /* If there is no data length, return immediately */
2750 if (!_f->datalen)
2751 return 0;
2753 /* Make sure we have enough space for RTP header */
2754 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
2755 ast_log(LOG_WARNING, "RTP can only send voice and video\n");
2756 return -1;
2759 subclass = _f->subclass;
2760 if (_f->frametype == AST_FRAME_VIDEO)
2761 subclass &= ~0x1;
2763 codec = ast_rtp_lookup_code(rtp, 1, subclass);
2764 if (codec < 0) {
2765 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
2766 return -1;
2769 if (rtp->lasttxformat != subclass) {
2770 /* New format, reset the smoother */
2771 if (option_debug)
2772 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
2773 rtp->lasttxformat = subclass;
2774 if (rtp->smoother)
2775 ast_smoother_free(rtp->smoother);
2776 rtp->smoother = NULL;
2779 if (!rtp->smoother && subclass != AST_FORMAT_SPEEX && subclass != AST_FORMAT_G723_1) {
2780 struct ast_format_list fmt = ast_codec_pref_getsize(&rtp->pref, subclass);
2781 if (fmt.inc_ms) { /* if codec parameters is set / avoid division by zero */
2782 if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
2783 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));
2784 return -1;
2786 if (fmt.flags)
2787 ast_smoother_set_flags(rtp->smoother, fmt.flags);
2788 if (option_debug)
2789 ast_log(LOG_DEBUG, "Created smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
2792 if (rtp->smoother) {
2793 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
2794 ast_smoother_feed_be(rtp->smoother, _f);
2795 } else {
2796 ast_smoother_feed(rtp->smoother, _f);
2799 while ((f = ast_smoother_read(rtp->smoother)) && (f->data)) {
2800 if (f->subclass == AST_FORMAT_G722) {
2801 /* G.722 is silllllllllllllly */
2802 f->samples /= 2;
2805 ast_rtp_raw_write(rtp, f, codec);
2807 } else {
2808 /* Don't buffer outgoing frames; send them one-per-packet: */
2809 if (_f->offset < hdrlen) {
2810 f = ast_frdup(_f);
2811 } else {
2812 f = _f;
2814 if (f->data) {
2815 if (f->subclass == AST_FORMAT_G722) {
2816 /* G.722 is silllllllllllllly */
2817 f->samples /= 2;
2819 ast_rtp_raw_write(rtp, f, codec);
2821 if (f != _f)
2822 ast_frfree(f);
2825 return 0;
2828 /*! \brief Unregister interface to channel driver */
2829 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
2831 AST_LIST_LOCK(&protos);
2832 AST_LIST_REMOVE(&protos, proto, list);
2833 AST_LIST_UNLOCK(&protos);
2836 /*! \brief Register interface to channel driver */
2837 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
2839 struct ast_rtp_protocol *cur;
2841 AST_LIST_LOCK(&protos);
2842 AST_LIST_TRAVERSE(&protos, cur, list) {
2843 if (!strcmp(cur->type, proto->type)) {
2844 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
2845 AST_LIST_UNLOCK(&protos);
2846 return -1;
2849 AST_LIST_INSERT_HEAD(&protos, proto, list);
2850 AST_LIST_UNLOCK(&protos);
2852 return 0;
2855 /*! \brief Bridge loop for true native bridge (reinvite) */
2856 static enum ast_bridge_result bridge_native_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp *p0, struct ast_rtp *p1, struct ast_rtp *vp0, struct ast_rtp *vp1, struct ast_rtp_protocol *pr0, struct ast_rtp_protocol *pr1, int codec0, int codec1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
2858 struct ast_frame *fr = NULL;
2859 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
2860 int oldcodec0 = codec0, oldcodec1 = codec1;
2861 struct sockaddr_in ac1 = {0,}, vac1 = {0,}, ac0 = {0,}, vac0 = {0,};
2862 struct sockaddr_in t1 = {0,}, vt1 = {0,}, t0 = {0,}, vt0 = {0,};
2864 /* Set it up so audio goes directly between the two endpoints */
2866 /* Test the first channel */
2867 if (!(pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))) {
2868 ast_rtp_get_peer(p1, &ac1);
2869 if (vp1)
2870 ast_rtp_get_peer(vp1, &vac1);
2871 } else
2872 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
2874 /* Test the second channel */
2875 if (!(pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))) {
2876 ast_rtp_get_peer(p0, &ac0);
2877 if (vp0)
2878 ast_rtp_get_peer(vp0, &vac0);
2879 } else
2880 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c1->name, c0->name);
2882 /* Now we can unlock and move into our loop */
2883 ast_channel_unlock(c0);
2884 ast_channel_unlock(c1);
2886 /* Throw our channels into the structure and enter the loop */
2887 cs[0] = c0;
2888 cs[1] = c1;
2889 cs[2] = NULL;
2890 for (;;) {
2891 /* Check if anything changed */
2892 if ((c0->tech_pvt != pvt0) ||
2893 (c1->tech_pvt != pvt1) ||
2894 (c0->masq || c0->masqr || c1->masq || c1->masqr) ||
2895 (c0->monitor || c0->audiohooks || c1->monitor || c1->audiohooks)) {
2896 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
2897 if (c0->tech_pvt == pvt0)
2898 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2899 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2900 if (c1->tech_pvt == pvt1)
2901 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2902 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2903 return AST_BRIDGE_RETRY;
2906 /* Check if they have changed their address */
2907 ast_rtp_get_peer(p1, &t1);
2908 if (vp1)
2909 ast_rtp_get_peer(vp1, &vt1);
2910 if (pr1->get_codec)
2911 codec1 = pr1->get_codec(c1);
2912 ast_rtp_get_peer(p0, &t0);
2913 if (vp0)
2914 ast_rtp_get_peer(vp0, &vt0);
2915 if (pr0->get_codec)
2916 codec0 = pr0->get_codec(c0);
2917 if ((inaddrcmp(&t1, &ac1)) ||
2918 (vp1 && inaddrcmp(&vt1, &vac1)) ||
2919 (codec1 != oldcodec1)) {
2920 if (option_debug > 1) {
2921 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2922 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
2923 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
2924 c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
2925 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2926 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
2927 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2928 c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
2930 if (pr0->set_rtp_peer(c0, t1.sin_addr.s_addr ? p1 : NULL, vt1.sin_addr.s_addr ? vp1 : NULL, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
2931 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
2932 memcpy(&ac1, &t1, sizeof(ac1));
2933 memcpy(&vac1, &vt1, sizeof(vac1));
2934 oldcodec1 = codec1;
2936 if ((inaddrcmp(&t0, &ac0)) ||
2937 (vp0 && inaddrcmp(&vt0, &vac0))) {
2938 if (option_debug > 1) {
2939 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2940 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
2941 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2942 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
2944 if (pr1->set_rtp_peer(c1, t0.sin_addr.s_addr ? p0 : NULL, vt0.sin_addr.s_addr ? vp0 : NULL, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
2945 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
2946 memcpy(&ac0, &t0, sizeof(ac0));
2947 memcpy(&vac0, &vt0, sizeof(vac0));
2948 oldcodec0 = codec0;
2951 /* Wait for frame to come in on the channels */
2952 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
2953 if (!timeoutms) {
2954 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2955 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2956 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2957 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2958 return AST_BRIDGE_RETRY;
2960 if (option_debug)
2961 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2962 if (ast_check_hangup(c0) || ast_check_hangup(c1))
2963 break;
2964 continue;
2966 fr = ast_read(who);
2967 other = (who == c0) ? c1 : c0;
2968 if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
2969 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
2970 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
2971 /* Break out of bridge */
2972 *fo = fr;
2973 *rc = who;
2974 if (option_debug)
2975 ast_log(LOG_DEBUG, "Oooh, got a %s\n", fr ? "digit" : "hangup");
2976 if (c0->tech_pvt == pvt0)
2977 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2978 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2979 if (c1->tech_pvt == pvt1)
2980 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2981 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2982 return AST_BRIDGE_COMPLETE;
2983 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2984 if ((fr->subclass == AST_CONTROL_HOLD) ||
2985 (fr->subclass == AST_CONTROL_UNHOLD) ||
2986 (fr->subclass == AST_CONTROL_VIDUPDATE) ||
2987 (fr->subclass == AST_CONTROL_SRCUPDATE)) {
2988 if (fr->subclass == AST_CONTROL_HOLD) {
2989 /* If we someone went on hold we want the other side to reinvite back to us */
2990 if (who == c0)
2991 pr1->set_rtp_peer(c1, NULL, NULL, 0, 0);
2992 else
2993 pr0->set_rtp_peer(c0, NULL, NULL, 0, 0);
2994 } else if (fr->subclass == AST_CONTROL_UNHOLD) {
2995 /* If they went off hold they should go back to being direct */
2996 if (who == c0)
2997 pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE));
2998 else
2999 pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE));
3001 /* Update local address information */
3002 ast_rtp_get_peer(p0, &t0);
3003 memcpy(&ac0, &t0, sizeof(ac0));
3004 ast_rtp_get_peer(p1, &t1);
3005 memcpy(&ac1, &t1, sizeof(ac1));
3006 /* Update codec information */
3007 if (pr0->get_codec && c0->tech_pvt)
3008 oldcodec0 = codec0 = pr0->get_codec(c0);
3009 if (pr1->get_codec && c1->tech_pvt)
3010 oldcodec1 = codec1 = pr1->get_codec(c1);
3011 ast_indicate_data(other, fr->subclass, fr->data, fr->datalen);
3012 ast_frfree(fr);
3013 } else {
3014 *fo = fr;
3015 *rc = who;
3016 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
3017 return AST_BRIDGE_COMPLETE;
3019 } else {
3020 if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
3021 (fr->frametype == AST_FRAME_DTMF_END) ||
3022 (fr->frametype == AST_FRAME_VOICE) ||
3023 (fr->frametype == AST_FRAME_VIDEO) ||
3024 (fr->frametype == AST_FRAME_IMAGE) ||
3025 (fr->frametype == AST_FRAME_HTML) ||
3026 (fr->frametype == AST_FRAME_MODEM) ||
3027 (fr->frametype == AST_FRAME_TEXT)) {
3028 ast_write(other, fr);
3030 ast_frfree(fr);
3032 /* Swap priority */
3033 cs[2] = cs[0];
3034 cs[0] = cs[1];
3035 cs[1] = cs[2];
3038 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
3039 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
3040 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
3041 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
3043 return AST_BRIDGE_FAILED;
3046 /*! \brief P2P RTP Callback */
3047 #ifdef P2P_INTENSE
3048 static int p2p_rtp_callback(int *id, int fd, short events, void *cbdata)
3050 int res = 0, hdrlen = 12;
3051 struct sockaddr_in sin;
3052 socklen_t len;
3053 unsigned int *header;
3054 struct ast_rtp *rtp = cbdata, *bridged = NULL;
3056 if (!rtp)
3057 return 1;
3059 len = sizeof(sin);
3060 if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
3061 return 1;
3063 header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
3065 /* If NAT support is turned on, then see if we need to change their address */
3066 if ((rtp->nat) &&
3067 ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
3068 (rtp->them.sin_port != sin.sin_port))) {
3069 rtp->them = sin;
3070 rtp->rxseqno = 0;
3071 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
3072 if (option_debug || rtpdebug)
3073 ast_log(LOG_DEBUG, "P2P RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
3076 /* Write directly out to other RTP stream if bridged */
3077 if ((bridged = ast_rtp_get_bridged(rtp)))
3078 bridge_p2p_rtp_write(rtp, bridged, header, res, hdrlen);
3080 return 1;
3083 /*! \brief Helper function to switch a channel and RTP stream into callback mode */
3084 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int *fds, int **iod)
3086 /* If we need DTMF, are looking for STUN, or we have no IO structure then we can't do direct callback */
3087 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) || ast_test_flag(rtp, FLAG_HAS_STUN) || !rtp->io)
3088 return 0;
3090 /* If the RTP structure is already in callback mode, remove it temporarily */
3091 if (rtp->ioid) {
3092 ast_io_remove(rtp->io, rtp->ioid);
3093 rtp->ioid = NULL;
3096 /* Steal the file descriptors from the channel and stash them away */
3097 fds[0] = chan->fds[0];
3098 chan->fds[0] = -1;
3100 /* Now, fire up callback mode */
3101 iod[0] = ast_io_add(rtp->io, fds[0], p2p_rtp_callback, AST_IO_IN, rtp);
3103 return 1;
3105 #else
3106 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int *fds, int **iod)
3108 return 0;
3110 #endif
3112 /*! \brief Helper function to switch a channel and RTP stream out of callback mode */
3113 static int p2p_callback_disable(struct ast_channel *chan, struct ast_rtp *rtp, int *fds, int **iod)
3115 ast_channel_lock(chan);
3117 /* Remove the callback from the IO context */
3118 ast_io_remove(rtp->io, iod[0]);
3120 /* Restore file descriptors */
3121 chan->fds[0] = fds[0];
3122 ast_channel_unlock(chan);
3124 /* Restore callback mode if previously used */
3125 if (ast_test_flag(rtp, FLAG_CALLBACK_MODE))
3126 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
3128 return 0;
3131 /*! \brief Helper function that sets what an RTP structure is bridged to */
3132 static void p2p_set_bridge(struct ast_rtp *rtp0, struct ast_rtp *rtp1)
3134 ast_mutex_lock(&rtp0->bridge_lock);
3135 rtp0->bridged = rtp1;
3136 ast_mutex_unlock(&rtp0->bridge_lock);
3138 return;
3141 /*! \brief Bridge loop for partial native bridge (packet2packet) */
3142 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)
3144 struct ast_frame *fr = NULL;
3145 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
3146 int p0_fds[2] = {-1, -1}, p1_fds[2] = {-1, -1};
3147 int *p0_iod[2] = {NULL, NULL}, *p1_iod[2] = {NULL, NULL};
3148 int p0_callback = 0, p1_callback = 0;
3149 enum ast_bridge_result res = AST_BRIDGE_FAILED;
3151 /* Okay, setup each RTP structure to do P2P forwarding */
3152 ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
3153 p2p_set_bridge(p0, p1);
3154 ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
3155 p2p_set_bridge(p1, p0);
3157 /* Activate callback modes if possible */
3158 p0_callback = p2p_callback_enable(c0, p0, &p0_fds[0], &p0_iod[0]);
3159 p1_callback = p2p_callback_enable(c1, p1, &p1_fds[0], &p1_iod[0]);
3161 /* Now let go of the channel locks and be on our way */
3162 ast_channel_unlock(c0);
3163 ast_channel_unlock(c1);
3165 /* Go into a loop forwarding frames until we don't need to anymore */
3166 cs[0] = c0;
3167 cs[1] = c1;
3168 cs[2] = NULL;
3169 for (;;) {
3170 /* If the underlying formats have changed force this bridge to break */
3171 if ((c0->rawreadformat != c1->rawwriteformat) || (c1->rawreadformat != c0->rawwriteformat)) {
3172 ast_log(LOG_DEBUG, "Oooh, formats changed, backing out\n");
3173 res = AST_BRIDGE_FAILED_NOWARN;
3174 break;
3176 /* Check if anything changed */
3177 if ((c0->tech_pvt != pvt0) ||
3178 (c1->tech_pvt != pvt1) ||
3179 (c0->masq || c0->masqr || c1->masq || c1->masqr) ||
3180 (c0->monitor || c0->audiohooks || c1->monitor || c1->audiohooks)) {
3181 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
3182 if ((c0->masq || c0->masqr) && (fr = ast_read(c0)))
3183 ast_frfree(fr);
3184 if ((c1->masq || c1->masqr) && (fr = ast_read(c1)))
3185 ast_frfree(fr);
3186 res = AST_BRIDGE_RETRY;
3187 break;
3189 /* Wait on a channel to feed us a frame */
3190 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
3191 if (!timeoutms) {
3192 res = AST_BRIDGE_RETRY;
3193 break;
3195 if (option_debug)
3196 ast_log(LOG_NOTICE, "Ooh, empty read...\n");
3197 if (ast_check_hangup(c0) || ast_check_hangup(c1))
3198 break;
3199 continue;
3201 /* Read in frame from channel */
3202 fr = ast_read(who);
3203 other = (who == c0) ? c1 : c0;
3204 /* Dependong on the frame we may need to break out of our bridge */
3205 if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
3206 ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
3207 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
3208 /* Record received frame and who */
3209 *fo = fr;
3210 *rc = who;
3211 if (option_debug)
3212 ast_log(LOG_DEBUG, "Oooh, got a %s\n", fr ? "digit" : "hangup");
3213 res = AST_BRIDGE_COMPLETE;
3214 break;
3215 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3216 if ((fr->subclass == AST_CONTROL_HOLD) ||
3217 (fr->subclass == AST_CONTROL_UNHOLD) ||
3218 (fr->subclass == AST_CONTROL_VIDUPDATE) ||
3219 (fr->subclass == AST_CONTROL_SRCUPDATE)) {
3220 /* If we are going on hold, then break callback mode and P2P bridging */
3221 if (fr->subclass == AST_CONTROL_HOLD) {
3222 if (p0_callback)
3223 p0_callback = p2p_callback_disable(c0, p0, &p0_fds[0], &p0_iod[0]);
3224 if (p1_callback)
3225 p1_callback = p2p_callback_disable(c1, p1, &p1_fds[0], &p1_iod[0]);
3226 p2p_set_bridge(p0, NULL);
3227 p2p_set_bridge(p1, NULL);
3228 } else if (fr->subclass == AST_CONTROL_UNHOLD) {
3229 /* If we are off hold, then go back to callback mode and P2P bridging */
3230 ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
3231 p2p_set_bridge(p0, p1);
3232 ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
3233 p2p_set_bridge(p1, p0);
3234 p0_callback = p2p_callback_enable(c0, p0, &p0_fds[0], &p0_iod[0]);
3235 p1_callback = p2p_callback_enable(c1, p1, &p1_fds[0], &p1_iod[0]);
3237 ast_indicate_data(other, fr->subclass, fr->data, fr->datalen);
3238 ast_frfree(fr);
3239 } else {
3240 *fo = fr;
3241 *rc = who;
3242 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
3243 res = AST_BRIDGE_COMPLETE;
3244 break;
3246 } else {
3247 if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
3248 (fr->frametype == AST_FRAME_DTMF_END) ||
3249 (fr->frametype == AST_FRAME_VOICE) ||
3250 (fr->frametype == AST_FRAME_VIDEO) ||
3251 (fr->frametype == AST_FRAME_IMAGE) ||
3252 (fr->frametype == AST_FRAME_HTML) ||
3253 (fr->frametype == AST_FRAME_MODEM) ||
3254 (fr->frametype == AST_FRAME_TEXT)) {
3255 ast_write(other, fr);
3258 ast_frfree(fr);
3260 /* Swap priority */
3261 cs[2] = cs[0];
3262 cs[0] = cs[1];
3263 cs[1] = cs[2];
3266 /* If we are totally avoiding the core, then restore our link to it */
3267 if (p0_callback)
3268 p0_callback = p2p_callback_disable(c0, p0, &p0_fds[0], &p0_iod[0]);
3269 if (p1_callback)
3270 p1_callback = p2p_callback_disable(c1, p1, &p1_fds[0], &p1_iod[0]);
3272 /* Break out of the direct bridge */
3273 p2p_set_bridge(p0, NULL);
3274 p2p_set_bridge(p1, NULL);
3276 return res;
3279 /*! \brief Bridge calls. If possible and allowed, initiate
3280 re-invite so the peers exchange media directly outside
3281 of Asterisk. */
3282 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)
3284 struct ast_rtp *p0 = NULL, *p1 = NULL; /* Audio RTP Channels */
3285 struct ast_rtp *vp0 = NULL, *vp1 = NULL; /* Video RTP channels */
3286 struct ast_rtp_protocol *pr0 = NULL, *pr1 = NULL;
3287 enum ast_rtp_get_result audio_p0_res = AST_RTP_GET_FAILED, video_p0_res = AST_RTP_GET_FAILED;
3288 enum ast_rtp_get_result audio_p1_res = AST_RTP_GET_FAILED, video_p1_res = AST_RTP_GET_FAILED;
3289 enum ast_bridge_result res = AST_BRIDGE_FAILED;
3290 int codec0 = 0, codec1 = 0;
3291 void *pvt0 = NULL, *pvt1 = NULL;
3293 /* Lock channels */
3294 ast_channel_lock(c0);
3295 while(ast_channel_trylock(c1)) {
3296 ast_channel_unlock(c0);
3297 usleep(1);
3298 ast_channel_lock(c0);
3301 /* Ensure neither channel got hungup during lock avoidance */
3302 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3303 ast_log(LOG_WARNING, "Got hangup while attempting to bridge '%s' and '%s'\n", c0->name, c1->name);
3304 ast_channel_unlock(c0);
3305 ast_channel_unlock(c1);
3306 return AST_BRIDGE_FAILED;
3309 /* Find channel driver interfaces */
3310 if (!(pr0 = get_proto(c0))) {
3311 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
3312 ast_channel_unlock(c0);
3313 ast_channel_unlock(c1);
3314 return AST_BRIDGE_FAILED;
3316 if (!(pr1 = get_proto(c1))) {
3317 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
3318 ast_channel_unlock(c0);
3319 ast_channel_unlock(c1);
3320 return AST_BRIDGE_FAILED;
3323 /* Get channel specific interface structures */
3324 pvt0 = c0->tech_pvt;
3325 pvt1 = c1->tech_pvt;
3327 /* Get audio and video interface (if native bridge is possible) */
3328 audio_p0_res = pr0->get_rtp_info(c0, &p0);
3329 video_p0_res = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
3330 audio_p1_res = pr1->get_rtp_info(c1, &p1);
3331 video_p1_res = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
3333 /* If we are carrying video, and both sides are not reinviting... then fail the native bridge */
3334 if (video_p0_res != AST_RTP_GET_FAILED && (audio_p0_res != AST_RTP_TRY_NATIVE || video_p0_res != AST_RTP_TRY_NATIVE))
3335 audio_p0_res = AST_RTP_GET_FAILED;
3336 if (video_p1_res != AST_RTP_GET_FAILED && (audio_p1_res != AST_RTP_TRY_NATIVE || video_p1_res != AST_RTP_TRY_NATIVE))
3337 audio_p1_res = AST_RTP_GET_FAILED;
3339 /* Check if a bridge is possible (partial/native) */
3340 if (audio_p0_res == AST_RTP_GET_FAILED || audio_p1_res == AST_RTP_GET_FAILED) {
3341 /* Somebody doesn't want to play... */
3342 ast_channel_unlock(c0);
3343 ast_channel_unlock(c1);
3344 return AST_BRIDGE_FAILED_NOWARN;
3347 /* If we need to feed DTMF frames into the core then only do a partial native bridge */
3348 if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
3349 ast_set_flag(p0, FLAG_P2P_NEED_DTMF);
3350 audio_p0_res = AST_RTP_TRY_PARTIAL;
3353 if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
3354 ast_set_flag(p1, FLAG_P2P_NEED_DTMF);
3355 audio_p1_res = AST_RTP_TRY_PARTIAL;
3358 /* If both sides are not using the same method of DTMF transmission
3359 * (ie: one is RFC2833, other is INFO... then we can not do direct media.
3360 * --------------------------------------------------
3361 * | DTMF Mode | HAS_DTMF | Accepts Begin Frames |
3362 * |-----------|------------|-----------------------|
3363 * | Inband | False | True |
3364 * | RFC2833 | True | True |
3365 * | SIP INFO | False | False |
3366 * --------------------------------------------------
3367 * However, if DTMF from both channels is being monitored by the core, then
3368 * we can still do packet-to-packet bridging, because passing through the
3369 * core will handle DTMF mode translation.
3371 if ( (ast_test_flag(p0, FLAG_HAS_DTMF) != ast_test_flag(p1, FLAG_HAS_DTMF)) ||
3372 (!c0->tech->send_digit_begin != !c1->tech->send_digit_begin)) {
3373 if (!ast_test_flag(p0, FLAG_P2P_NEED_DTMF) || !ast_test_flag(p1, FLAG_P2P_NEED_DTMF)) {
3374 ast_channel_unlock(c0);
3375 ast_channel_unlock(c1);
3376 return AST_BRIDGE_FAILED_NOWARN;
3378 audio_p0_res = AST_RTP_TRY_PARTIAL;
3379 audio_p1_res = AST_RTP_TRY_PARTIAL;
3382 /* If we need to feed frames into the core don't do a P2P bridge */
3383 if ((audio_p0_res == AST_RTP_TRY_PARTIAL && ast_test_flag(p0, FLAG_P2P_NEED_DTMF)) ||
3384 (audio_p1_res == AST_RTP_TRY_PARTIAL && ast_test_flag(p1, FLAG_P2P_NEED_DTMF))) {
3385 ast_channel_unlock(c0);
3386 ast_channel_unlock(c1);
3387 return AST_BRIDGE_FAILED_NOWARN;
3390 /* Get codecs from both sides */
3391 codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
3392 codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
3393 if (codec0 && codec1 && !(codec0 & codec1)) {
3394 /* Hey, we can't do native bridging if both parties speak different codecs */
3395 if (option_debug)
3396 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
3397 ast_channel_unlock(c0);
3398 ast_channel_unlock(c1);
3399 return AST_BRIDGE_FAILED_NOWARN;
3402 /* If either side can only do a partial bridge, then don't try for a true native bridge */
3403 if (audio_p0_res == AST_RTP_TRY_PARTIAL || audio_p1_res == AST_RTP_TRY_PARTIAL) {
3404 struct ast_format_list fmt0, fmt1;
3406 /* In order to do Packet2Packet bridging both sides must be in the same rawread/rawwrite */
3407 if (c0->rawreadformat != c1->rawwriteformat || c1->rawreadformat != c0->rawwriteformat) {
3408 if (option_debug)
3409 ast_log(LOG_DEBUG, "Cannot packet2packet bridge - raw formats are incompatible\n");
3410 ast_channel_unlock(c0);
3411 ast_channel_unlock(c1);
3412 return AST_BRIDGE_FAILED_NOWARN;
3414 /* They must also be using the same packetization */
3415 fmt0 = ast_codec_pref_getsize(&p0->pref, c0->rawreadformat);
3416 fmt1 = ast_codec_pref_getsize(&p1->pref, c1->rawreadformat);
3417 if (fmt0.cur_ms != fmt1.cur_ms) {
3418 if (option_debug)
3419 ast_log(LOG_DEBUG, "Cannot packet2packet bridge - packetization settings prevent it\n");
3420 ast_channel_unlock(c0);
3421 ast_channel_unlock(c1);
3422 return AST_BRIDGE_FAILED_NOWARN;
3425 if (option_verbose > 2)
3426 ast_verbose(VERBOSE_PREFIX_3 "Packet2Packet bridging %s and %s\n", c0->name, c1->name);
3427 res = bridge_p2p_loop(c0, c1, p0, p1, timeoutms, flags, fo, rc, pvt0, pvt1);
3428 } else {
3429 if (option_verbose > 2)
3430 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
3431 res = bridge_native_loop(c0, c1, p0, p1, vp0, vp1, pr0, pr1, codec0, codec1, timeoutms, flags, fo, rc, pvt0, pvt1);
3434 return res;
3437 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
3439 struct hostent *hp;
3440 struct ast_hostent ahp;
3441 int port = 0;
3442 char *p, *arg;
3444 if (argc != 4)
3445 return RESULT_SHOWUSAGE;
3446 arg = argv[3];
3447 p = strstr(arg, ":");
3448 if (p) {
3449 *p = '\0';
3450 p++;
3451 port = atoi(p);
3453 hp = ast_gethostbyname(arg, &ahp);
3454 if (hp == NULL)
3455 return RESULT_SHOWUSAGE;
3456 rtpdebugaddr.sin_family = AF_INET;
3457 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
3458 rtpdebugaddr.sin_port = htons(port);
3459 if (port == 0)
3460 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr.sin_addr));
3461 else
3462 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr.sin_addr), port);
3463 rtpdebug = 1;
3464 return RESULT_SUCCESS;
3467 static int rtcp_do_debug_ip_deprecated(int fd, int argc, char *argv[])
3469 struct hostent *hp;
3470 struct ast_hostent ahp;
3471 int port = 0;
3472 char *p, *arg;
3473 if (argc != 5)
3474 return RESULT_SHOWUSAGE;
3476 arg = argv[4];
3477 p = strstr(arg, ":");
3478 if (p) {
3479 *p = '\0';
3480 p++;
3481 port = atoi(p);
3483 hp = ast_gethostbyname(arg, &ahp);
3484 if (hp == NULL)
3485 return RESULT_SHOWUSAGE;
3486 rtcpdebugaddr.sin_family = AF_INET;
3487 memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
3488 rtcpdebugaddr.sin_port = htons(port);
3489 if (port == 0)
3490 ast_cli(fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
3491 else
3492 ast_cli(fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
3493 rtcpdebug = 1;
3494 return RESULT_SUCCESS;
3497 static int rtcp_do_debug_ip(int fd, int argc, char *argv[])
3499 struct hostent *hp;
3500 struct ast_hostent ahp;
3501 int port = 0;
3502 char *p, *arg;
3503 if (argc != 4)
3504 return RESULT_SHOWUSAGE;
3506 arg = argv[3];
3507 p = strstr(arg, ":");
3508 if (p) {
3509 *p = '\0';
3510 p++;
3511 port = atoi(p);
3513 hp = ast_gethostbyname(arg, &ahp);
3514 if (hp == NULL)
3515 return RESULT_SHOWUSAGE;
3516 rtcpdebugaddr.sin_family = AF_INET;
3517 memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
3518 rtcpdebugaddr.sin_port = htons(port);
3519 if (port == 0)
3520 ast_cli(fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
3521 else
3522 ast_cli(fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
3523 rtcpdebug = 1;
3524 return RESULT_SUCCESS;
3527 static int rtp_do_debug(int fd, int argc, char *argv[])
3529 if (argc != 2) {
3530 if (argc != 4)
3531 return RESULT_SHOWUSAGE;
3532 return rtp_do_debug_ip(fd, argc, argv);
3534 rtpdebug = 1;
3535 memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
3536 ast_cli(fd, "RTP Debugging Enabled\n");
3537 return RESULT_SUCCESS;
3540 static int rtcp_do_debug_deprecated(int fd, int argc, char *argv[]) {
3541 if (argc != 3) {
3542 if (argc != 5)
3543 return RESULT_SHOWUSAGE;
3544 return rtcp_do_debug_ip_deprecated(fd, argc, argv);
3546 rtcpdebug = 1;
3547 memset(&rtcpdebugaddr,0,sizeof(rtcpdebugaddr));
3548 ast_cli(fd, "RTCP Debugging Enabled\n");
3549 return RESULT_SUCCESS;
3552 static int rtcp_do_debug(int fd, int argc, char *argv[]) {
3553 if (argc != 2) {
3554 if (argc != 4)
3555 return RESULT_SHOWUSAGE;
3556 return rtcp_do_debug_ip(fd, argc, argv);
3558 rtcpdebug = 1;
3559 memset(&rtcpdebugaddr,0,sizeof(rtcpdebugaddr));
3560 ast_cli(fd, "RTCP Debugging Enabled\n");
3561 return RESULT_SUCCESS;
3564 static int rtcp_do_stats_deprecated(int fd, int argc, char *argv[]) {
3565 if (argc != 3) {
3566 return RESULT_SHOWUSAGE;
3568 rtcpstats = 1;
3569 ast_cli(fd, "RTCP Stats Enabled\n");
3570 return RESULT_SUCCESS;
3573 static int rtcp_do_stats(int fd, int argc, char *argv[]) {
3574 if (argc != 2) {
3575 return RESULT_SHOWUSAGE;
3577 rtcpstats = 1;
3578 ast_cli(fd, "RTCP Stats Enabled\n");
3579 return RESULT_SUCCESS;
3582 static int rtp_no_debug(int fd, int argc, char *argv[])
3584 if (argc != 3)
3585 return RESULT_SHOWUSAGE;
3586 rtpdebug = 0;
3587 ast_cli(fd,"RTP Debugging Disabled\n");
3588 return RESULT_SUCCESS;
3591 static int rtcp_no_debug_deprecated(int fd, int argc, char *argv[])
3593 if (argc != 4)
3594 return RESULT_SHOWUSAGE;
3595 rtcpdebug = 0;
3596 ast_cli(fd,"RTCP Debugging Disabled\n");
3597 return RESULT_SUCCESS;
3600 static int rtcp_no_debug(int fd, int argc, char *argv[])
3602 if (argc != 3)
3603 return RESULT_SHOWUSAGE;
3604 rtcpdebug = 0;
3605 ast_cli(fd,"RTCP Debugging Disabled\n");
3606 return RESULT_SUCCESS;
3609 static int rtcp_no_stats_deprecated(int fd, int argc, char *argv[])
3611 if (argc != 4)
3612 return RESULT_SHOWUSAGE;
3613 rtcpstats = 0;
3614 ast_cli(fd,"RTCP Stats Disabled\n");
3615 return RESULT_SUCCESS;
3618 static int rtcp_no_stats(int fd, int argc, char *argv[])
3620 if (argc != 3)
3621 return RESULT_SHOWUSAGE;
3622 rtcpstats = 0;
3623 ast_cli(fd,"RTCP Stats Disabled\n");
3624 return RESULT_SUCCESS;
3627 static int stun_do_debug(int fd, int argc, char *argv[])
3629 if (argc != 2) {
3630 return RESULT_SHOWUSAGE;
3632 stundebug = 1;
3633 ast_cli(fd, "STUN Debugging Enabled\n");
3634 return RESULT_SUCCESS;
3637 static int stun_no_debug(int fd, int argc, char *argv[])
3639 if (argc != 3)
3640 return RESULT_SHOWUSAGE;
3641 stundebug = 0;
3642 ast_cli(fd, "STUN Debugging Disabled\n");
3643 return RESULT_SUCCESS;
3646 static char debug_usage[] =
3647 "Usage: rtp debug [ip host[:port]]\n"
3648 " Enable dumping of all RTP packets to and from host.\n";
3650 static char no_debug_usage[] =
3651 "Usage: rtp debug off\n"
3652 " Disable all RTP debugging\n";
3654 static char stun_debug_usage[] =
3655 "Usage: stun debug\n"
3656 " Enable STUN (Simple Traversal of UDP through NATs) debugging\n";
3658 static char stun_no_debug_usage[] =
3659 "Usage: stun debug off\n"
3660 " Disable STUN debugging\n";
3662 static char rtcp_debug_usage[] =
3663 "Usage: rtcp debug [ip host[:port]]\n"
3664 " Enable dumping of all RTCP packets to and from host.\n";
3666 static char rtcp_no_debug_usage[] =
3667 "Usage: rtcp debug off\n"
3668 " Disable all RTCP debugging\n";
3670 static char rtcp_stats_usage[] =
3671 "Usage: rtcp stats\n"
3672 " Enable dumping of RTCP stats.\n";
3674 static char rtcp_no_stats_usage[] =
3675 "Usage: rtcp stats off\n"
3676 " Disable all RTCP stats\n";
3678 static struct ast_cli_entry cli_rtp_no_debug_deprecated = {
3679 { "rtp", "no", "debug", NULL },
3680 rtp_no_debug, NULL,
3681 NULL };
3683 static struct ast_cli_entry cli_rtp_rtcp_debug_ip_deprecated = {
3684 { "rtp", "rtcp", "debug", "ip", NULL },
3685 rtcp_do_debug_deprecated, NULL,
3686 NULL };
3688 static struct ast_cli_entry cli_rtp_rtcp_debug_deprecated = {
3689 { "rtp", "rtcp", "debug", NULL },
3690 rtcp_do_debug_deprecated, NULL,
3691 NULL };
3693 static struct ast_cli_entry cli_rtp_rtcp_no_debug_deprecated = {
3694 { "rtp", "rtcp", "no", "debug", NULL },
3695 rtcp_no_debug_deprecated, NULL,
3696 NULL };
3698 static struct ast_cli_entry cli_rtp_rtcp_stats_deprecated = {
3699 { "rtp", "rtcp", "stats", NULL },
3700 rtcp_do_stats_deprecated, NULL,
3701 NULL };
3703 static struct ast_cli_entry cli_rtp_rtcp_no_stats_deprecated = {
3704 { "rtp", "rtcp", "no", "stats", NULL },
3705 rtcp_no_stats_deprecated, NULL,
3706 NULL };
3708 static struct ast_cli_entry cli_stun_no_debug_deprecated = {
3709 { "stun", "no", "debug", NULL },
3710 stun_no_debug, NULL,
3711 NULL };
3713 static struct ast_cli_entry cli_rtp[] = {
3714 { { "rtp", "debug", "ip", NULL },
3715 rtp_do_debug, "Enable RTP debugging on IP",
3716 debug_usage },
3718 { { "rtp", "debug", NULL },
3719 rtp_do_debug, "Enable RTP debugging",
3720 debug_usage },
3722 { { "rtp", "debug", "off", NULL },
3723 rtp_no_debug, "Disable RTP debugging",
3724 no_debug_usage, NULL, &cli_rtp_no_debug_deprecated },
3726 { { "rtcp", "debug", "ip", NULL },
3727 rtcp_do_debug, "Enable RTCP debugging on IP",
3728 rtcp_debug_usage, NULL, &cli_rtp_rtcp_debug_ip_deprecated },
3730 { { "rtcp", "debug", NULL },
3731 rtcp_do_debug, "Enable RTCP debugging",
3732 rtcp_debug_usage, NULL, &cli_rtp_rtcp_debug_deprecated },
3734 { { "rtcp", "debug", "off", NULL },
3735 rtcp_no_debug, "Disable RTCP debugging",
3736 rtcp_no_debug_usage, NULL, &cli_rtp_rtcp_no_debug_deprecated },
3738 { { "rtcp", "stats", NULL },
3739 rtcp_do_stats, "Enable RTCP stats",
3740 rtcp_stats_usage, NULL, &cli_rtp_rtcp_stats_deprecated },
3742 { { "rtcp", "stats", "off", NULL },
3743 rtcp_no_stats, "Disable RTCP stats",
3744 rtcp_no_stats_usage, NULL, &cli_rtp_rtcp_no_stats_deprecated },
3746 { { "stun", "debug", NULL },
3747 stun_do_debug, "Enable STUN debugging",
3748 stun_debug_usage },
3750 { { "stun", "debug", "off", NULL },
3751 stun_no_debug, "Disable STUN debugging",
3752 stun_no_debug_usage, NULL, &cli_stun_no_debug_deprecated },
3755 int ast_rtp_reload(void)
3757 struct ast_config *cfg;
3758 const char *s;
3760 rtpstart = 5000;
3761 rtpend = 31000;
3762 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
3763 cfg = ast_config_load("rtp.conf");
3764 if (cfg) {
3765 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
3766 rtpstart = atoi(s);
3767 if (rtpstart < 1024)
3768 rtpstart = 1024;
3769 if (rtpstart > 65535)
3770 rtpstart = 65535;
3772 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
3773 rtpend = atoi(s);
3774 if (rtpend < 1024)
3775 rtpend = 1024;
3776 if (rtpend > 65535)
3777 rtpend = 65535;
3779 if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
3780 rtcpinterval = atoi(s);
3781 if (rtcpinterval == 0)
3782 rtcpinterval = 0; /* Just so we're clear... it's zero */
3783 if (rtcpinterval < RTCP_MIN_INTERVALMS)
3784 rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
3785 if (rtcpinterval > RTCP_MAX_INTERVALMS)
3786 rtcpinterval = RTCP_MAX_INTERVALMS;
3788 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
3789 #ifdef SO_NO_CHECK
3790 if (ast_false(s))
3791 nochecksums = 1;
3792 else
3793 nochecksums = 0;
3794 #else
3795 if (ast_false(s))
3796 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
3797 #endif
3799 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
3800 dtmftimeout = atoi(s);
3801 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
3802 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
3803 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
3804 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
3807 ast_config_destroy(cfg);
3809 if (rtpstart >= rtpend) {
3810 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
3811 rtpstart = 5000;
3812 rtpend = 31000;
3814 if (option_verbose > 1)
3815 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
3816 return 0;
3819 /*! \brief Initialize the RTP system in Asterisk */
3820 void ast_rtp_init(void)
3822 ast_cli_register_multiple(cli_rtp, sizeof(cli_rtp) / sizeof(struct ast_cli_entry));
3823 ast_rtp_reload();