update cleancount because the channel structure changed today
[asterisk-bristuff.git] / rtp.c
blob67e5952bb6677eaa28e188352d8eb6dbe1eb9042
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 = 0; /*!< First port for RTP sessions (set in rtp.conf) */
81 static int rtpend = 0; /*!< Last port for RTP sessions (set in rtp.conf) */
82 static int rtpdebug = 0; /*!< Are we debugging? */
83 static int rtcpdebug = 0; /*!< Are we debugging RTCP? */
84 static int rtcpstats = 0; /*!< Are we debugging RTCP? */
85 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
86 static int stundebug = 0; /*!< Are we debugging stun? */
87 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
88 static struct sockaddr_in rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
89 #ifdef SO_NO_CHECK
90 static int nochecksums = 0;
91 #endif
93 /*!
94 * \brief Structure representing a RTP session.
96 * RTP session is defined on page 9 of RFC 3550: "An association among a set of participants communicating with RTP. A participant may be involved in multiple RTP sessions at the same time [...]"
99 /*! \brief The value of each payload format mapping: */
100 struct rtpPayloadType {
101 int isAstFormat; /*!< whether the following code is an AST_FORMAT */
102 int code;
106 /*! \brief RTP session description */
107 struct ast_rtp {
108 int s;
109 char resp;
110 struct ast_frame f;
111 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
112 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
113 unsigned int themssrc; /*!< Their SSRC */
114 unsigned int rxssrc;
115 unsigned int lastts;
116 unsigned int lastdigitts;
117 unsigned int lastrxts;
118 unsigned int lastividtimestamp;
119 unsigned int lastovidtimestamp;
120 unsigned int lasteventseqn;
121 int lastrxseqno; /*!< Last received sequence number */
122 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
123 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
124 unsigned int rxcount; /*!< How many packets have we received? */
125 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
126 unsigned int txcount; /*!< How many packets have we sent? */
127 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
128 unsigned int cycles; /*!< Shifted count of sequence number cycles */
129 double rxjitter; /*!< Interarrival jitter at the moment */
130 double rxtransit; /*!< Relative transit time for previous packet */
131 unsigned int lasteventendseqn;
132 int lasttxformat;
133 int lastrxformat;
134 int dtmfcount;
135 unsigned int dtmfduration;
136 int nat;
137 unsigned int flags;
138 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
139 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
140 struct timeval rxcore;
141 struct timeval txcore;
142 double drxcore; /*!< The double representation of the first received packet */
143 struct timeval lastrx; /*!< timeval when we last received a packet */
144 struct timeval dtmfmute;
145 struct ast_smoother *smoother;
146 int *ioid;
147 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
148 unsigned short rxseqno;
149 struct sched_context *sched;
150 struct io_context *io;
151 void *data;
152 ast_rtp_callback callback;
153 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
154 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
155 int rtp_lookup_code_cache_code;
156 int rtp_lookup_code_cache_result;
157 struct ast_rtcp *rtcp;
160 /* Forward declarations */
161 static int ast_rtcp_write(void *data);
162 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
163 static int ast_rtcp_write_sr(void *data);
164 static int ast_rtcp_write_rr(void *data);
165 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
167 #define FLAG_3389_WARNING (1 << 0)
168 #define FLAG_NAT_ACTIVE (3 << 1)
169 #define FLAG_NAT_INACTIVE (0 << 1)
170 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
171 #define FLAG_HAS_DTMF (1 << 3)
174 * \brief Structure defining an RTCP session.
176 * The concept "RTCP session" is not defined in RFC 3550, but since
177 * this structure is analogous to ast_rtp, which tracks a RTP session,
178 * it is logical to think of this as a RTCP session.
180 * RTCP packet is defined on page 9 of RFC 3550.
183 struct ast_rtcp {
184 int s; /*!< Socket */
185 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
186 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
187 unsigned int soc; /*!< What they told us */
188 unsigned int spc; /*!< What they told us */
189 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
190 struct timeval rxlsr; /*!< Time when we got their last SR */
191 struct timeval txlsr; /*!< Time when we sent or last SR*/
192 unsigned int expected_prior; /*!< no. packets in previous interval */
193 unsigned int received_prior; /*!< no. packets received in previous interval */
194 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
195 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
196 unsigned int sr_count; /*!< number of SRs we've sent */
197 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
198 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
199 double rtt; /*!< Last reported rtt */
200 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
201 unsigned int reported_lost; /*!< Reported lost packets in their RR */
202 char quality[AST_MAX_USER_FIELD];
203 double maxrxjitter;
204 double minrxjitter;
205 double maxrtt;
206 double minrtt;
207 int sendfur;
211 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
213 /* XXX Maybe stun belongs in another file if it ever has use outside of RTP */
214 struct stun_header {
215 unsigned short msgtype;
216 unsigned short msglen;
217 stun_trans_id id;
218 unsigned char ies[0];
219 } __attribute__((packed));
221 struct stun_attr {
222 unsigned short attr;
223 unsigned short len;
224 unsigned char value[0];
225 } __attribute__((packed));
227 struct stun_addr {
228 unsigned char unused;
229 unsigned char family;
230 unsigned short port;
231 unsigned int addr;
232 } __attribute__((packed));
234 #define STUN_IGNORE (0)
235 #define STUN_ACCEPT (1)
237 #define STUN_BINDREQ 0x0001
238 #define STUN_BINDRESP 0x0101
239 #define STUN_BINDERR 0x0111
240 #define STUN_SECREQ 0x0002
241 #define STUN_SECRESP 0x0102
242 #define STUN_SECERR 0x0112
244 #define STUN_MAPPED_ADDRESS 0x0001
245 #define STUN_RESPONSE_ADDRESS 0x0002
246 #define STUN_CHANGE_REQUEST 0x0003
247 #define STUN_SOURCE_ADDRESS 0x0004
248 #define STUN_CHANGED_ADDRESS 0x0005
249 #define STUN_USERNAME 0x0006
250 #define STUN_PASSWORD 0x0007
251 #define STUN_MESSAGE_INTEGRITY 0x0008
252 #define STUN_ERROR_CODE 0x0009
253 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
254 #define STUN_REFLECTED_FROM 0x000b
256 static const char *stun_msg2str(int msg)
258 switch(msg) {
259 case STUN_BINDREQ:
260 return "Binding Request";
261 case STUN_BINDRESP:
262 return "Binding Response";
263 case STUN_BINDERR:
264 return "Binding Error Response";
265 case STUN_SECREQ:
266 return "Shared Secret Request";
267 case STUN_SECRESP:
268 return "Shared Secret Response";
269 case STUN_SECERR:
270 return "Shared Secret Error Response";
272 return "Non-RFC3489 Message";
275 static const char *stun_attr2str(int msg)
277 switch(msg) {
278 case STUN_MAPPED_ADDRESS:
279 return "Mapped Address";
280 case STUN_RESPONSE_ADDRESS:
281 return "Response Address";
282 case STUN_CHANGE_REQUEST:
283 return "Change Request";
284 case STUN_SOURCE_ADDRESS:
285 return "Source Address";
286 case STUN_CHANGED_ADDRESS:
287 return "Changed Address";
288 case STUN_USERNAME:
289 return "Username";
290 case STUN_PASSWORD:
291 return "Password";
292 case STUN_MESSAGE_INTEGRITY:
293 return "Message Integrity";
294 case STUN_ERROR_CODE:
295 return "Error Code";
296 case STUN_UNKNOWN_ATTRIBUTES:
297 return "Unknown Attributes";
298 case STUN_REFLECTED_FROM:
299 return "Reflected From";
301 return "Non-RFC3489 Attribute";
304 struct stun_state {
305 const char *username;
306 const char *password;
309 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
311 if (stundebug)
312 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
313 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
314 switch(ntohs(attr->attr)) {
315 case STUN_USERNAME:
316 state->username = (const char *) (attr->value);
317 break;
318 case STUN_PASSWORD:
319 state->password = (const char *) (attr->value);
320 break;
321 default:
322 if (stundebug)
323 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
324 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
326 return 0;
329 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
331 int size = sizeof(**attr) + strlen(s);
332 if (*left > size) {
333 (*attr)->attr = htons(attrval);
334 (*attr)->len = htons(strlen(s));
335 memcpy((*attr)->value, s, strlen(s));
336 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
337 *len += size;
338 *left -= size;
342 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
344 int size = sizeof(**attr) + 8;
345 struct stun_addr *addr;
346 if (*left > size) {
347 (*attr)->attr = htons(attrval);
348 (*attr)->len = htons(8);
349 addr = (struct stun_addr *)((*attr)->value);
350 addr->unused = 0;
351 addr->family = 0x01;
352 addr->port = sin->sin_port;
353 addr->addr = sin->sin_addr.s_addr;
354 (*attr) = (struct stun_attr *)((*attr)->value + 8);
355 *len += size;
356 *left -= size;
360 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
362 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
363 (struct sockaddr *)dst, sizeof(*dst));
366 static void stun_req_id(struct stun_header *req)
368 int x;
369 for (x=0;x<4;x++)
370 req->id.id[x] = ast_random();
373 size_t ast_rtp_alloc_size(void)
375 return sizeof(struct ast_rtp);
378 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
380 struct stun_header *req;
381 unsigned char reqdata[1024];
382 int reqlen, reqleft;
383 struct stun_attr *attr;
385 req = (struct stun_header *)reqdata;
386 stun_req_id(req);
387 reqlen = 0;
388 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
389 req->msgtype = 0;
390 req->msglen = 0;
391 attr = (struct stun_attr *)req->ies;
392 if (username)
393 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
394 req->msglen = htons(reqlen);
395 req->msgtype = htons(STUN_BINDREQ);
396 stun_send(rtp->s, suggestion, req);
399 static int stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len)
401 struct stun_header *resp, *hdr = (struct stun_header *)data;
402 struct stun_attr *attr;
403 struct stun_state st;
404 int ret = STUN_IGNORE;
405 unsigned char respdata[1024];
406 int resplen, respleft;
408 if (len < sizeof(struct stun_header)) {
409 if (option_debug)
410 ast_log(LOG_DEBUG, "Runt STUN packet (only %zd, wanting at least %zd)\n", len, sizeof(struct stun_header));
411 return -1;
413 if (stundebug)
414 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), ntohs(hdr->msglen));
415 if (ntohs(hdr->msglen) > len - sizeof(struct stun_header)) {
416 if (option_debug)
417 ast_log(LOG_DEBUG, "Scrambled STUN packet length (got %d, expecting %zd)\n", ntohs(hdr->msglen), len - sizeof(struct stun_header));
418 } else
419 len = ntohs(hdr->msglen);
420 data += sizeof(struct stun_header);
421 memset(&st, 0, sizeof(st));
422 while(len) {
423 if (len < sizeof(struct stun_attr)) {
424 if (option_debug)
425 ast_log(LOG_DEBUG, "Runt Attribute (got %zd, expecting %zd)\n", len, sizeof(struct stun_attr));
426 break;
428 attr = (struct stun_attr *)data;
429 if (ntohs(attr->len) > len) {
430 if (option_debug)
431 ast_log(LOG_DEBUG, "Inconsistent Attribute (length %d exceeds remaining msg len %zd)\n", ntohs(attr->len), len);
432 break;
434 if (stun_process_attr(&st, attr)) {
435 if (option_debug)
436 ast_log(LOG_DEBUG, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
437 break;
439 /* Clear attribute in case previous entry was a string */
440 attr->attr = 0;
441 data += ntohs(attr->len) + sizeof(struct stun_attr);
442 len -= ntohs(attr->len) + sizeof(struct stun_attr);
444 /* Null terminate any string */
445 *data = '\0';
446 resp = (struct stun_header *)respdata;
447 resplen = 0;
448 respleft = sizeof(respdata) - sizeof(struct stun_header);
449 resp->id = hdr->id;
450 resp->msgtype = 0;
451 resp->msglen = 0;
452 attr = (struct stun_attr *)resp->ies;
453 if (!len) {
454 switch(ntohs(hdr->msgtype)) {
455 case STUN_BINDREQ:
456 if (stundebug)
457 ast_verbose("STUN Bind Request, username: %s\n",
458 st.username ? st.username : "<none>");
459 if (st.username)
460 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
461 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
462 resp->msglen = htons(resplen);
463 resp->msgtype = htons(STUN_BINDRESP);
464 stun_send(s, src, resp);
465 ret = STUN_ACCEPT;
466 break;
467 default:
468 if (stundebug)
469 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
472 return ret;
475 /*! \brief List of current sessions */
476 static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
478 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
480 unsigned int sec, usec, frac;
481 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
482 usec = tv.tv_usec;
483 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
484 *msw = sec;
485 *lsw = frac;
488 int ast_rtp_fd(struct ast_rtp *rtp)
490 return rtp->s;
493 int ast_rtcp_fd(struct ast_rtp *rtp)
495 if (rtp->rtcp)
496 return rtp->rtcp->s;
497 return -1;
500 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
502 unsigned int interval;
503 /*! \todo XXX Do a more reasonable calculation on this one
504 * Look in RFC 3550 Section A.7 for an example*/
505 interval = rtcpinterval;
506 return interval;
509 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
511 rtp->data = data;
514 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
516 rtp->callback = callback;
519 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
521 rtp->nat = nat;
524 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
526 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
529 static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
531 if (ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
532 if (option_debug)
533 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
534 rtp->resp = 0;
535 rtp->dtmfduration = 0;
536 return &ast_null_frame;
538 if (option_debug)
539 ast_log(LOG_DEBUG, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
540 if (rtp->resp == 'X') {
541 rtp->f.frametype = AST_FRAME_CONTROL;
542 rtp->f.subclass = AST_CONTROL_FLASH;
543 } else {
544 rtp->f.frametype = AST_FRAME_DTMF;
545 rtp->f.subclass = rtp->resp;
547 rtp->f.datalen = 0;
548 rtp->f.samples = 0;
549 rtp->f.mallocd = 0;
550 rtp->f.src = "RTP";
551 rtp->resp = 0;
552 rtp->dtmfduration = 0;
553 return &rtp->f;
557 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
559 if (rtpdebug == 0)
560 return 0;
561 if (rtpdebugaddr.sin_addr.s_addr) {
562 if (((ntohs(rtpdebugaddr.sin_port) != 0)
563 && (rtpdebugaddr.sin_port != addr->sin_port))
564 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
565 return 0;
567 return 1;
570 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
572 if (rtcpdebug == 0)
573 return 0;
574 if (rtcpdebugaddr.sin_addr.s_addr) {
575 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
576 && (rtcpdebugaddr.sin_port != addr->sin_port))
577 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
578 return 0;
580 return 1;
584 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
586 unsigned int event;
587 char resp = 0;
588 struct ast_frame *f = NULL;
589 event = ntohl(*((unsigned int *)(data)));
590 event &= 0x001F;
591 if (option_debug > 2 || rtpdebug)
592 ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
593 if (event < 10) {
594 resp = '0' + event;
595 } else if (event < 11) {
596 resp = '*';
597 } else if (event < 12) {
598 resp = '#';
599 } else if (event < 16) {
600 resp = 'A' + (event - 12);
601 } else if (event < 17) {
602 resp = 'X';
604 if (rtp->resp && (rtp->resp != resp)) {
605 f = send_dtmf(rtp);
607 rtp->resp = resp;
608 rtp->dtmfcount = dtmftimeout;
609 return f;
612 /*!
613 * \brief Process RTP DTMF and events according to RFC 2833.
615 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
617 * \param rtp
618 * \param data
619 * \param len
620 * \param seqno
621 * \returns
623 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
625 unsigned int event;
626 unsigned int event_end;
627 unsigned int duration;
628 char resp = 0;
629 struct ast_frame *f = NULL;
631 event = ntohl(*((unsigned int *)(data)));
632 event >>= 24;
633 event_end = ntohl(*((unsigned int *)(data)));
634 event_end <<= 8;
635 event_end >>= 24;
636 duration = ntohl(*((unsigned int *)(data)));
637 duration &= 0xFFFF;
638 if (rtpdebug || option_debug > 2)
639 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
640 if (event < 10) {
641 resp = '0' + event;
642 } else if (event < 11) {
643 resp = '*';
644 } else if (event < 12) {
645 resp = '#';
646 } else if (event < 16) {
647 resp = 'A' + (event - 12);
648 } else if (event < 17) { /* Event 16: Hook flash */
649 resp = 'X';
651 if (rtp->resp && (rtp->resp != resp)) {
652 f = send_dtmf(rtp);
653 } else if (event_end & 0x80) {
654 if (rtp->resp) {
655 if (rtp->lasteventendseqn != seqno) {
656 f = send_dtmf(rtp);
657 rtp->lasteventendseqn = seqno;
659 rtp->resp = 0;
661 resp = 0;
662 duration = 0;
663 } else if (rtp->resp && rtp->dtmfduration && (duration < rtp->dtmfduration)) {
664 f = send_dtmf(rtp);
666 if (!(event_end & 0x80))
667 rtp->resp = resp;
668 rtp->dtmfcount = dtmftimeout;
669 rtp->dtmfduration = duration;
670 return f;
674 * \brief Process Comfort Noise RTP.
676 * This is incomplete at the moment.
679 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
681 struct ast_frame *f = NULL;
682 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
683 totally help us out becuase we don't have an engine to keep it going and we are not
684 guaranteed to have it every 20ms or anything */
685 if (rtpdebug)
686 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
688 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
689 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
690 ast_inet_ntoa(rtp->them.sin_addr));
691 ast_set_flag(rtp, FLAG_3389_WARNING);
694 /* Must have at least one byte */
695 if (!len)
696 return NULL;
697 if (len < 24) {
698 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
699 rtp->f.datalen = len - 1;
700 rtp->f.offset = AST_FRIENDLY_OFFSET;
701 memcpy(rtp->f.data, data + 1, len - 1);
702 } else {
703 rtp->f.data = NULL;
704 rtp->f.offset = 0;
705 rtp->f.datalen = 0;
707 rtp->f.frametype = AST_FRAME_CNG;
708 rtp->f.subclass = data[0] & 0x7f;
709 rtp->f.datalen = len - 1;
710 rtp->f.samples = 0;
711 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
712 f = &rtp->f;
713 return f;
716 static int rtpread(int *id, int fd, short events, void *cbdata)
718 struct ast_rtp *rtp = cbdata;
719 struct ast_frame *f;
720 f = ast_rtp_read(rtp);
721 if (f) {
722 if (rtp->callback)
723 rtp->callback(rtp, f, rtp->data);
725 return 1;
728 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
730 socklen_t len;
731 int position, i, packetwords;
732 int res;
733 struct sockaddr_in sin;
734 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
735 unsigned int *rtcpheader;
736 int pt;
737 struct timeval now;
738 unsigned int length;
739 int rc;
740 double rtt = 0;
741 double a;
742 double dlsr;
743 double lsr;
744 unsigned int msw;
745 unsigned int lsw;
746 unsigned int comp;
747 struct ast_frame *f = &ast_null_frame;
749 if (!rtp || !rtp->rtcp)
750 return &ast_null_frame;
752 len = sizeof(sin);
754 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
755 0, (struct sockaddr *)&sin, &len);
756 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
758 if (res < 0) {
759 if (errno != EAGAIN)
760 ast_log(LOG_WARNING, "RTCP Read error: %s\n", strerror(errno));
761 if (errno == EBADF)
762 CRASH;
763 return &ast_null_frame;
766 packetwords = res / 4;
768 if (rtp->nat) {
769 /* Send to whoever sent to us */
770 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
771 (rtp->rtcp->them.sin_port != sin.sin_port)) {
772 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
773 if (option_debug || rtpdebug)
774 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));
777 if (option_debug)
778 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
780 /* Process a compound packet */
781 position = 0;
782 while (position < packetwords) {
783 i = position;
784 length = ntohl(rtcpheader[i]);
785 pt = (length & 0xff0000) >> 16;
786 rc = (length & 0x1f000000) >> 24;
787 length &= 0xffff;
789 if ((i + length) > packetwords) {
790 ast_log(LOG_WARNING, "RTCP Read too short\n");
791 return &ast_null_frame;
794 if (rtcp_debug_test_addr(&sin)) {
795 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
796 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
797 ast_verbose("Reception reports: %d\n", rc);
798 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
801 i += 2; /* Advance past header and ssrc */
803 switch (pt) {
804 case RTCP_PT_SR:
805 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
806 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
807 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
808 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff) >> 16); /* Going to LSR in RR*/
810 if (rtcp_debug_test_addr(&sin)) {
811 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
812 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
813 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
815 i += 5;
816 if (rc < 1)
817 break;
818 /* Intentional fall through */
819 case RTCP_PT_RR:
820 /* This is the place to calculate RTT */
821 /* Don't handle multiple reception reports (rc > 1) yet */
822 gettimeofday(&now, NULL);
823 timeval2ntp(now, &msw, &lsw);
824 /* Use the one we sent them in our SR instead, rtcp->txlsr could have been rewritten if the dlsr is large */
825 if (ntohl(rtcpheader[i + 4])) { /* We must have the LSR */
826 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
827 a = (double)((comp & 0xffff0000) >> 16) + (double)((double)(comp & 0xffff)/1000000.);
828 lsr = (double)((ntohl(rtcpheader[i + 4]) & 0xffff0000) >> 16) + (double)((double)(ntohl(rtcpheader[i + 4]) & 0xffff) / 1000000.);
829 dlsr = (double)(ntohl(rtcpheader[i + 5])/65536.);
830 rtt = a - dlsr - lsr;
831 rtp->rtcp->accumulated_transit += rtt;
832 rtp->rtcp->rtt = rtt;
833 if (rtp->rtcp->maxrtt<rtt)
834 rtp->rtcp->maxrtt = rtt;
835 if (rtp->rtcp->minrtt>rtt)
836 rtp->rtcp->minrtt = rtt;
838 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
839 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
840 if (rtcp_debug_test_addr(&sin)) {
841 ast_verbose("Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
842 ast_verbose("Packets lost so far: %d\n", rtp->rtcp->reported_lost);
843 ast_verbose("Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
844 ast_verbose("Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
845 ast_verbose("Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
846 ast_verbose("Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
847 ast_verbose("DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
848 if (rtt)
849 ast_verbose("RTT: %f(sec)\n", rtt);
851 break;
852 case RTCP_PT_FUR:
853 if (rtcp_debug_test_addr(&sin))
854 ast_verbose("Received an RTCP Fast Update Request\n");
855 rtp->f.frametype = AST_FRAME_CONTROL;
856 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
857 rtp->f.datalen = 0;
858 rtp->f.samples = 0;
859 rtp->f.mallocd = 0;
860 rtp->f.src = "RTP";
861 f = &rtp->f;
862 break;
863 case RTCP_PT_SDES:
864 if (rtcp_debug_test_addr(&sin))
865 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
866 break;
867 case RTCP_PT_BYE:
868 if (rtcp_debug_test_addr(&sin))
869 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
870 break;
871 default:
872 ast_log(LOG_NOTICE, "Unknown RTCP packet (pt=%d) received from %s:%d\n", pt, ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
873 break;
875 position += (length + 1);
878 return f;
881 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
883 struct timeval now;
884 double transit;
885 double current_time;
886 double d;
887 double dtv;
888 double prog;
890 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
891 gettimeofday(&rtp->rxcore, NULL);
892 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
893 /* map timestamp to a real time */
894 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
895 rtp->rxcore.tv_sec -= timestamp / 8000;
896 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
897 /* Round to 0.1ms for nice, pretty timestamps */
898 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
899 if (rtp->rxcore.tv_usec < 0) {
900 /* Adjust appropriately if necessary */
901 rtp->rxcore.tv_usec += 1000000;
902 rtp->rxcore.tv_sec -= 1;
906 gettimeofday(&now,NULL);
907 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
908 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
909 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
910 if (tv->tv_usec >= 1000000) {
911 tv->tv_usec -= 1000000;
912 tv->tv_sec += 1;
914 prog = (double)((timestamp-rtp->seedrxts)/8000.);
915 dtv = (double)rtp->drxcore + (double)(prog);
916 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
917 transit = current_time - dtv;
918 d = transit - rtp->rxtransit;
919 rtp->rxtransit = transit;
920 if (d<0)
921 d=-d;
922 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
923 if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
924 rtp->rtcp->maxrxjitter = rtp->rxjitter;
925 if (rtp->rxjitter < rtp->rtcp->minrxjitter)
926 rtp->rtcp->minrxjitter = rtp->rxjitter;
929 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
931 int res;
932 struct sockaddr_in sin;
933 socklen_t len;
934 unsigned int seqno;
935 int version;
936 int payloadtype;
937 int tseqno;
938 int hdrlen = 12;
939 int padding;
940 int mark;
941 int ext;
942 unsigned int ssrc;
943 unsigned int timestamp;
944 unsigned int *rtpheader;
945 struct rtpPayloadType rtpPT;
947 len = sizeof(sin);
949 /* Cache where the header will go */
950 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
951 0, (struct sockaddr *)&sin, &len);
953 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
954 if (res < 0) {
955 if (errno != EAGAIN)
956 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
957 if (errno == EBADF)
958 CRASH;
959 return &ast_null_frame;
962 if (res < hdrlen) {
963 ast_log(LOG_WARNING, "RTP Read too short\n");
964 return &ast_null_frame;
967 /* Get fields */
968 seqno = ntohl(rtpheader[0]);
970 /* Check RTP version */
971 version = (seqno & 0xC0000000) >> 30;
972 if (!version) {
973 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res) == STUN_ACCEPT) &&
974 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
975 memcpy(&rtp->them, &sin, sizeof(rtp->them));
977 return &ast_null_frame;
980 if (version != 2)
981 return &ast_null_frame;
982 /* Ignore if the other side hasn't been given an address
983 yet. */
984 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
985 return &ast_null_frame;
987 if (rtp->nat) {
988 /* Send to whoever sent to us */
989 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
990 (rtp->them.sin_port != sin.sin_port)) {
991 rtp->them = sin;
992 if (rtp->rtcp) {
993 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
994 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
996 rtp->rxseqno = 0;
997 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
998 if (option_debug || rtpdebug)
999 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));
1003 payloadtype = (seqno & 0x7f0000) >> 16;
1004 padding = seqno & (1 << 29);
1005 mark = seqno & (1 << 23);
1006 ext = seqno & (1 << 28);
1007 seqno &= 0xffff;
1008 timestamp = ntohl(rtpheader[1]);
1009 ssrc = ntohl(rtpheader[2]);
1011 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1012 if (option_debug || rtpdebug)
1013 ast_log(LOG_DEBUG, "Forcing Marker bit, because SSRC has changed\n");
1014 mark = 1;
1017 rtp->rxssrc = ssrc;
1019 if (padding) {
1020 /* Remove padding bytes */
1021 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1024 if (ext) {
1025 /* RTP Extension present */
1026 hdrlen += 4;
1027 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
1030 if (res < hdrlen) {
1031 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1032 return &ast_null_frame;
1035 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1037 tseqno = rtp->lastrxseqno +1;
1039 if (rtp->rxcount==1) {
1040 /* This is the first RTP packet successfully received from source */
1041 rtp->seedrxseqno = seqno;
1044 if (rtp->rtcp->schedid < 1) {
1045 /* Schedule transmission of Receiver Report */
1046 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1049 if (tseqno > RTP_SEQ_MOD) { /* if tseqno is greater than RTP_SEQ_MOD it would indicate that the sender cycled */
1050 rtp->cycles += RTP_SEQ_MOD;
1051 ast_verbose("SEQNO cycled: %u\t%d\n", rtp->cycles, seqno);
1054 rtp->lastrxseqno = seqno;
1056 if (rtp->themssrc==0)
1057 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1059 if (rtp_debug_test_addr(&sin))
1060 ast_verbose("Got RTP packet from %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1061 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1063 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1064 if (!rtpPT.isAstFormat) {
1065 struct ast_frame *f = NULL;
1067 /* This is special in-band data that's not one of our codecs */
1068 if (rtpPT.code == AST_RTP_DTMF) {
1069 /* It's special -- rfc2833 process it */
1070 if (rtp_debug_test_addr(&sin)) {
1071 unsigned char *data;
1072 unsigned int event;
1073 unsigned int event_end;
1074 unsigned int duration;
1075 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1076 event = ntohl(*((unsigned int *)(data)));
1077 event >>= 24;
1078 event_end = ntohl(*((unsigned int *)(data)));
1079 event_end <<= 8;
1080 event_end >>= 24;
1081 duration = ntohl(*((unsigned int *)(data)));
1082 duration &= 0xFFFF;
1083 ast_verbose("Got RTP RFC2833 from %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
1085 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
1086 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
1087 rtp->lasteventseqn = seqno;
1089 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1090 /* It's really special -- process it the Cisco way */
1091 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
1092 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1093 rtp->lasteventseqn = seqno;
1095 } else if (rtpPT.code == AST_RTP_CN) {
1096 /* Comfort Noise */
1097 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1098 } else {
1099 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1101 return f ? f : &ast_null_frame;
1103 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1104 rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : AST_FRAME_VIDEO;
1106 if (!rtp->lastrxts)
1107 rtp->lastrxts = timestamp;
1109 rtp->rxseqno = seqno;
1111 if (rtp->dtmfcount) {
1112 #if 0
1113 printf("dtmfcount was %d\n", rtp->dtmfcount);
1114 #endif
1115 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
1116 if (rtp->dtmfcount < 0)
1117 rtp->dtmfcount = 0;
1118 #if 0
1119 if (dtmftimeout != rtp->dtmfcount)
1120 printf("dtmfcount is %d\n", rtp->dtmfcount);
1121 #endif
1123 rtp->lastrxts = timestamp;
1125 /* Send any pending DTMF */
1126 if (rtp->resp && !rtp->dtmfcount) {
1127 if (option_debug)
1128 ast_log(LOG_DEBUG, "Sending pending DTMF\n");
1129 return send_dtmf(rtp);
1131 rtp->f.mallocd = 0;
1132 rtp->f.datalen = res - hdrlen;
1133 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1134 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1135 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
1136 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1137 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1138 ast_frame_byteswap_be(&rtp->f);
1139 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1140 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1141 rtp->f.has_timing_info = 1;
1142 rtp->f.ts = timestamp / 8;
1143 rtp->f.len = rtp->f.samples / 8;
1144 rtp->f.seqno = seqno;
1145 } else {
1146 /* Video -- samples is # of samples vs. 90000 */
1147 if (!rtp->lastividtimestamp)
1148 rtp->lastividtimestamp = timestamp;
1149 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1150 rtp->lastividtimestamp = timestamp;
1151 rtp->f.delivery.tv_sec = 0;
1152 rtp->f.delivery.tv_usec = 0;
1153 if (mark)
1154 rtp->f.subclass |= 0x1;
1157 rtp->f.src = "RTP";
1158 return &rtp->f;
1161 /* The following array defines the MIME Media type (and subtype) for each
1162 of our codecs, or RTP-specific data type. */
1163 static struct {
1164 struct rtpPayloadType payloadType;
1165 char* type;
1166 char* subtype;
1167 } mimeTypes[] = {
1168 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1169 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1170 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1171 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1172 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1173 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1174 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1175 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1176 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1177 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1178 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1179 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
1180 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1181 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1182 {{0, AST_RTP_CN}, "audio", "CN"},
1183 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1184 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1185 {{1, AST_FORMAT_H261}, "video", "H261"},
1186 {{1, AST_FORMAT_H263}, "video", "H263"},
1187 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1188 {{1, AST_FORMAT_H264}, "video", "H264"},
1191 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1192 also, our own choices for dynamic payload types. This is our master
1193 table for transmission */
1194 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1195 [0] = {1, AST_FORMAT_ULAW},
1196 #ifdef USE_DEPRECATED_G726
1197 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1198 #endif
1199 [3] = {1, AST_FORMAT_GSM},
1200 [4] = {1, AST_FORMAT_G723_1},
1201 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1202 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1203 [7] = {1, AST_FORMAT_LPC10},
1204 [8] = {1, AST_FORMAT_ALAW},
1205 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1206 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1207 [13] = {0, AST_RTP_CN},
1208 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1209 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1210 [18] = {1, AST_FORMAT_G729A},
1211 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1212 [26] = {1, AST_FORMAT_JPEG},
1213 [31] = {1, AST_FORMAT_H261},
1214 [34] = {1, AST_FORMAT_H263},
1215 [103] = {1, AST_FORMAT_H263_PLUS},
1216 [97] = {1, AST_FORMAT_ILBC},
1217 [99] = {1, AST_FORMAT_H264},
1218 [101] = {0, AST_RTP_DTMF},
1219 [110] = {1, AST_FORMAT_SPEEX},
1220 [111] = {1, AST_FORMAT_G726},
1221 [112] = {1, AST_FORMAT_G726_AAL2},
1222 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1225 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1227 int i;
1228 if (!rtp)
1229 return;
1231 for (i = 0; i < MAX_RTP_PT; ++i) {
1232 rtp->current_RTP_PT[i].isAstFormat = 0;
1233 rtp->current_RTP_PT[i].code = 0;
1236 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1237 rtp->rtp_lookup_code_cache_code = 0;
1238 rtp->rtp_lookup_code_cache_result = 0;
1241 void ast_rtp_pt_default(struct ast_rtp* rtp)
1243 int i;
1245 /* Initialize to default payload types */
1246 for (i = 0; i < MAX_RTP_PT; ++i) {
1247 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1248 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1251 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1252 rtp->rtp_lookup_code_cache_code = 0;
1253 rtp->rtp_lookup_code_cache_result = 0;
1256 void ast_rtp_pt_copy(struct ast_rtp *dest, const struct ast_rtp *src)
1258 unsigned int i;
1260 for (i=0; i < MAX_RTP_PT; ++i) {
1261 dest->current_RTP_PT[i].isAstFormat =
1262 src->current_RTP_PT[i].isAstFormat;
1263 dest->current_RTP_PT[i].code =
1264 src->current_RTP_PT[i].code;
1266 dest->rtp_lookup_code_cache_isAstFormat = 0;
1267 dest->rtp_lookup_code_cache_code = 0;
1268 dest->rtp_lookup_code_cache_result = 0;
1271 /*! \brief Get channel driver interface structure */
1272 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1274 struct ast_rtp_protocol *cur = NULL;
1276 AST_LIST_LOCK(&protos);
1277 AST_LIST_TRAVERSE(&protos, cur, list) {
1278 if (cur->type == chan->tech->type)
1279 break;
1281 AST_LIST_UNLOCK(&protos);
1283 return cur;
1286 int ast_rtp_early_bridge(struct ast_channel *dest, struct ast_channel *src)
1288 struct ast_rtp *destp, *srcp=NULL; /* Audio RTP Channels */
1289 struct ast_rtp *vdestp, *vsrcp=NULL; /* Video RTP channels */
1290 struct ast_rtp_protocol *destpr, *srcpr=NULL;
1291 int srccodec;
1293 /* Lock channels */
1294 ast_channel_lock(dest);
1295 if (src) {
1296 while(ast_channel_trylock(src)) {
1297 ast_channel_unlock(dest);
1298 usleep(1);
1299 ast_channel_lock(dest);
1303 /* Find channel driver interfaces */
1304 destpr = get_proto(dest);
1305 if (src)
1306 srcpr = get_proto(src);
1307 if (!destpr) {
1308 if (option_debug)
1309 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1310 ast_channel_unlock(dest);
1311 if (src)
1312 ast_channel_unlock(src);
1313 return 0;
1315 if (!srcpr) {
1316 if (option_debug)
1317 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src ? src->name : "<unspecified>");
1318 ast_channel_unlock(dest);
1319 if (src)
1320 ast_channel_unlock(src);
1321 return 0;
1324 /* Get audio and video interface (if native bridge is possible) */
1325 destp = destpr->get_rtp_info(dest);
1326 vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
1327 if (srcpr) {
1328 srcp = srcpr->get_rtp_info(src);
1329 vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
1332 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1333 if (!destp) {
1334 /* Somebody doesn't want to play... */
1335 ast_channel_unlock(dest);
1336 if (src)
1337 ast_channel_unlock(src);
1338 return 0;
1340 if (srcpr && srcpr->get_codec)
1341 srccodec = srcpr->get_codec(src);
1342 else
1343 srccodec = 0;
1344 /* Consider empty media as non-existant */
1345 if (srcp && !srcp->them.sin_addr.s_addr)
1346 srcp = NULL;
1347 /* Bridge media early */
1348 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, srcp ? ast_test_flag(srcp, FLAG_NAT_ACTIVE) : 0))
1349 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src ? src->name : "<unspecified>");
1350 ast_channel_unlock(dest);
1351 if (src)
1352 ast_channel_unlock(src);
1353 if (option_debug)
1354 ast_log(LOG_DEBUG, "Setting early bridge SDP of '%s' with that of '%s'\n", dest->name, src ? src->name : "<unspecified>");
1355 return 1;
1358 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1360 struct ast_rtp *destp, *srcp; /* Audio RTP Channels */
1361 struct ast_rtp *vdestp, *vsrcp; /* Video RTP channels */
1362 struct ast_rtp_protocol *destpr, *srcpr;
1363 int srccodec;
1364 /* Lock channels */
1365 ast_channel_lock(dest);
1366 while(ast_channel_trylock(src)) {
1367 ast_channel_unlock(dest);
1368 usleep(1);
1369 ast_channel_lock(dest);
1372 /* Find channel driver interfaces */
1373 destpr = get_proto(dest);
1374 srcpr = get_proto(src);
1375 if (!destpr) {
1376 if (option_debug)
1377 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1378 ast_channel_unlock(dest);
1379 ast_channel_unlock(src);
1380 return 0;
1382 if (!srcpr) {
1383 if (option_debug)
1384 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
1385 ast_channel_unlock(dest);
1386 ast_channel_unlock(src);
1387 return 0;
1390 /* Get audio and video interface (if native bridge is possible) */
1391 destp = destpr->get_rtp_info(dest);
1392 vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
1393 srcp = srcpr->get_rtp_info(src);
1394 vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
1396 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1397 if (!destp || !srcp) {
1398 /* Somebody doesn't want to play... */
1399 ast_channel_unlock(dest);
1400 ast_channel_unlock(src);
1401 return 0;
1403 ast_rtp_pt_copy(destp, srcp);
1404 if (vdestp && vsrcp)
1405 ast_rtp_pt_copy(vdestp, vsrcp);
1406 if (srcpr->get_codec)
1407 srccodec = srcpr->get_codec(src);
1408 else
1409 srccodec = 0;
1410 if (media) {
1411 /* Bridge early */
1412 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1413 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1415 ast_channel_unlock(dest);
1416 ast_channel_unlock(src);
1417 if (option_debug)
1418 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1419 return 1;
1422 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1423 * By default, use the well-known value for this type (although it may
1424 * still be set to a different value by a subsequent "a=rtpmap:" line)
1426 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1428 if (pt < 0 || pt > MAX_RTP_PT)
1429 return; /* bogus payload type */
1431 if (static_RTP_PT[pt].code != 0)
1432 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1435 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1436 * an SDP "a=rtpmap:" line.
1438 void ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
1439 char *mimeType, char *mimeSubtype,
1440 enum ast_rtp_options options)
1442 unsigned int i;
1444 if (pt < 0 || pt > MAX_RTP_PT)
1445 return; /* bogus payload type */
1447 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1448 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1449 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1450 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1451 if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
1452 mimeTypes[i].payloadType.isAstFormat &&
1453 (options & AST_RTP_OPT_G726_NONSTANDARD))
1454 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
1455 return;
1460 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
1461 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1462 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1463 int* astFormats, int* nonAstFormats) {
1464 int pt;
1466 *astFormats = *nonAstFormats = 0;
1467 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1468 if (rtp->current_RTP_PT[pt].isAstFormat) {
1469 *astFormats |= rtp->current_RTP_PT[pt].code;
1470 } else {
1471 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
1476 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
1478 struct rtpPayloadType result;
1480 result.isAstFormat = result.code = 0;
1481 if (pt < 0 || pt > MAX_RTP_PT)
1482 return result; /* bogus payload type */
1484 /* Start with negotiated codecs */
1485 result = rtp->current_RTP_PT[pt];
1487 /* If it doesn't exist, check our static RTP type list, just in case */
1488 if (!result.code)
1489 result = static_RTP_PT[pt];
1490 return result;
1493 /*! \brief Looks up an RTP code out of our *static* outbound list */
1494 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
1496 int pt;
1498 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
1499 code == rtp->rtp_lookup_code_cache_code) {
1501 /* Use our cached mapping, to avoid the overhead of the loop below */
1502 return rtp->rtp_lookup_code_cache_result;
1505 /* Check the dynamic list first */
1506 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1507 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
1508 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1509 rtp->rtp_lookup_code_cache_code = code;
1510 rtp->rtp_lookup_code_cache_result = pt;
1511 return pt;
1515 /* Then the static list */
1516 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1517 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
1518 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1519 rtp->rtp_lookup_code_cache_code = code;
1520 rtp->rtp_lookup_code_cache_result = pt;
1521 return pt;
1524 return -1;
1527 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
1528 enum ast_rtp_options options)
1530 unsigned int i;
1532 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1533 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
1534 if (isAstFormat &&
1535 (code == AST_FORMAT_G726_AAL2) &&
1536 (options & AST_RTP_OPT_G726_NONSTANDARD))
1537 return "AAL2-G726-32";
1538 else
1539 return mimeTypes[i].subtype;
1543 return "";
1546 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
1547 const int isAstFormat, enum ast_rtp_options options)
1549 int format;
1550 unsigned len;
1551 char *end = buf;
1552 char *start = buf;
1554 if (!buf || !size)
1555 return NULL;
1557 snprintf(end, size, "0x%x (", capability);
1559 len = strlen(end);
1560 end += len;
1561 size -= len;
1562 start = end;
1564 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
1565 if (capability & format) {
1566 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
1568 snprintf(end, size, "%s|", name);
1569 len = strlen(end);
1570 end += len;
1571 size -= len;
1575 if (start == end)
1576 snprintf(start, size, "nothing)");
1577 else if (size > 1)
1578 *(end -1) = ')';
1580 return buf;
1583 static int rtp_socket(void)
1585 int s;
1586 long flags;
1587 s = socket(AF_INET, SOCK_DGRAM, 0);
1588 if (s > -1) {
1589 flags = fcntl(s, F_GETFL);
1590 fcntl(s, F_SETFL, flags | O_NONBLOCK);
1591 #ifdef SO_NO_CHECK
1592 if (nochecksums)
1593 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
1594 #endif
1596 return s;
1600 * \brief Initialize a new RTCP session.
1602 * \returns The newly initialized RTCP session.
1604 static struct ast_rtcp *ast_rtcp_new(void)
1606 struct ast_rtcp *rtcp;
1608 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
1609 return NULL;
1610 rtcp->s = rtp_socket();
1611 rtcp->us.sin_family = AF_INET;
1612 rtcp->them.sin_family = AF_INET;
1614 if (rtcp->s < 0) {
1615 free(rtcp);
1616 ast_log(LOG_WARNING, "Unable to allocate RTCP socket: %s\n", strerror(errno));
1617 return NULL;
1620 return rtcp;
1623 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
1625 struct ast_rtp *rtp;
1626 int x;
1627 int first;
1628 int startplace;
1630 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
1631 return NULL;
1632 rtp->them.sin_family = AF_INET;
1633 rtp->us.sin_family = AF_INET;
1634 rtp->s = rtp_socket();
1635 rtp->ssrc = ast_random();
1636 rtp->seqno = ast_random() & 0xffff;
1637 ast_set_flag(rtp, FLAG_HAS_DTMF);
1638 if (rtp->s < 0) {
1639 free(rtp);
1640 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1641 return NULL;
1643 if (sched && rtcpenable) {
1644 rtp->sched = sched;
1645 rtp->rtcp = ast_rtcp_new();
1648 /* Select a random port number in the range of possible RTP */
1649 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
1650 x = x & ~1;
1651 /* Save it for future references. */
1652 startplace = x;
1653 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1654 for (;;) {
1655 /* Must be an even port number by RTP spec */
1656 rtp->us.sin_port = htons(x);
1657 rtp->us.sin_addr = addr;
1658 /* If there's rtcp, initialize it as well. */
1659 if (rtp->rtcp)
1660 rtp->rtcp->us.sin_port = htons(x + 1);
1661 /* Try to bind it/them. */
1662 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1663 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1664 break;
1665 if (!first) {
1666 /* Primary bind succeeded! Gotta recreate it */
1667 close(rtp->s);
1668 rtp->s = rtp_socket();
1670 if (errno != EADDRINUSE) {
1671 /* We got an error that wasn't expected, abort! */
1672 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1673 close(rtp->s);
1674 if (rtp->rtcp) {
1675 close(rtp->rtcp->s);
1676 free(rtp->rtcp);
1678 free(rtp);
1679 return NULL;
1681 /* The port was used, increment it (by two). */
1682 x += 2;
1683 /* Did we go over the limit ? */
1684 if (x > rtpend)
1685 /* then, start from the begingig. */
1686 x = (rtpstart + 1) & ~1;
1687 /* Check if we reached the place were we started. */
1688 if (x == startplace) {
1689 /* If so, there's no ports available. */
1690 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1691 close(rtp->s);
1692 if (rtp->rtcp) {
1693 close(rtp->rtcp->s);
1694 free(rtp->rtcp);
1696 free(rtp);
1697 return NULL;
1700 if (io && sched && callbackmode) {
1701 /* Operate this one in a callback mode */
1702 rtp->sched = sched;
1703 rtp->io = io;
1704 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1706 ast_rtp_pt_default(rtp);
1707 return rtp;
1710 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1712 struct in_addr ia;
1714 memset(&ia, 0, sizeof(ia));
1715 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1718 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1720 int res;
1722 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1723 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1724 return res;
1727 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1729 rtp->them.sin_port = them->sin_port;
1730 rtp->them.sin_addr = them->sin_addr;
1731 if (rtp->rtcp) {
1732 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1733 rtp->rtcp->them.sin_addr = them->sin_addr;
1735 rtp->rxseqno = 0;
1738 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1740 if ((them->sin_family != AF_INET) ||
1741 (them->sin_port != rtp->them.sin_port) ||
1742 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
1743 them->sin_family = AF_INET;
1744 them->sin_port = rtp->them.sin_port;
1745 them->sin_addr = rtp->them.sin_addr;
1746 return 1;
1748 return 0;
1751 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1753 *us = rtp->us;
1756 void ast_rtp_stop(struct ast_rtp *rtp)
1758 if (rtp->rtcp->schedid > 0) {
1759 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1760 rtp->rtcp->schedid = -1;
1763 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1764 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1765 if (rtp->rtcp) {
1766 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
1767 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
1771 void ast_rtp_reset(struct ast_rtp *rtp)
1773 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1774 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1775 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1776 rtp->lastts = 0;
1777 rtp->lastdigitts = 0;
1778 rtp->lastrxts = 0;
1779 rtp->lastividtimestamp = 0;
1780 rtp->lastovidtimestamp = 0;
1781 rtp->lasteventseqn = 0;
1782 rtp->lasteventendseqn = 0;
1783 rtp->lasttxformat = 0;
1784 rtp->lastrxformat = 0;
1785 rtp->dtmfcount = 0;
1786 rtp->dtmfduration = 0;
1787 rtp->seqno = 0;
1788 rtp->rxseqno = 0;
1791 char *ast_rtp_get_quality(struct ast_rtp *rtp)
1794 *ssrc our ssrc
1795 *themssrc their ssrc
1796 *lp lost packets
1797 *rxjitter our calculated jitter(rx)
1798 *rxcount no. received packets
1799 *txjitter reported jitter of the other end
1800 *txcount transmitted packets
1801 *rlp remote lost packets
1804 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality), "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f", rtp->ssrc, rtp->themssrc, rtp->rtcp->expected_prior - rtp->rtcp->received_prior, rtp->rxjitter, rtp->rxcount, (double)rtp->rtcp->reported_jitter/65536., rtp->txcount, rtp->rtcp->reported_lost, rtp->rtcp->rtt);
1806 return rtp->rtcp->quality;
1809 void ast_rtp_destroy(struct ast_rtp *rtp)
1811 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
1812 /*Print some info on the call here */
1813 ast_verbose(" RTP-stats\n");
1814 ast_verbose("* Our Receiver:\n");
1815 ast_verbose(" SSRC: %u\n", rtp->themssrc);
1816 ast_verbose(" Received packets: %u\n", rtp->rxcount);
1817 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
1818 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
1819 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
1820 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
1821 ast_verbose("* Our Sender:\n");
1822 ast_verbose(" SSRC: %u\n", rtp->ssrc);
1823 ast_verbose(" Sent packets: %u\n", rtp->txcount);
1824 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
1825 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter);
1826 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
1827 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
1830 if (rtp->rtcp->schedid > 0) {
1831 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1832 rtp->rtcp->schedid = -1;
1835 if (rtp->smoother)
1836 ast_smoother_free(rtp->smoother);
1837 if (rtp->ioid)
1838 ast_io_remove(rtp->io, rtp->ioid);
1839 if (rtp->s > -1)
1840 close(rtp->s);
1841 if (rtp->rtcp) {
1842 close(rtp->rtcp->s);
1843 free(rtp->rtcp);
1844 rtp->rtcp=NULL;
1846 free(rtp);
1849 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1851 struct timeval t;
1852 long ms;
1853 if (ast_tvzero(rtp->txcore)) {
1854 rtp->txcore = ast_tvnow();
1855 /* Round to 20ms for nice, pretty timestamps */
1856 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1858 /* Use previous txcore if available */
1859 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
1860 ms = ast_tvdiff_ms(t, rtp->txcore);
1861 if (ms < 0)
1862 ms = 0;
1863 /* Use what we just got for next time */
1864 rtp->txcore = t;
1865 return (unsigned int) ms;
1868 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
1870 unsigned int *rtpheader;
1871 int hdrlen = 12;
1872 int res;
1873 int x;
1874 int payload;
1875 char data[256];
1877 if ((digit <= '9') && (digit >= '0'))
1878 digit -= '0';
1879 else if (digit == '*')
1880 digit = 10;
1881 else if (digit == '#')
1882 digit = 11;
1883 else if ((digit >= 'A') && (digit <= 'D'))
1884 digit = digit - 'A' + 12;
1885 else if ((digit >= 'a') && (digit <= 'd'))
1886 digit = digit - 'a' + 12;
1887 else {
1888 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
1889 return -1;
1891 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
1893 /* If we have no peer, return immediately */
1894 if (!rtp->them.sin_addr.s_addr)
1895 return 0;
1897 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1899 /* Get a pointer to the header */
1900 rtpheader = (unsigned int *)data;
1901 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
1902 rtpheader[1] = htonl(rtp->lastdigitts);
1903 rtpheader[2] = htonl(rtp->ssrc);
1904 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
1905 for (x = 0; x < 6; x++) {
1906 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1907 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
1908 if (res < 0)
1909 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
1910 ast_inet_ntoa(rtp->them.sin_addr),
1911 ntohs(rtp->them.sin_port), strerror(errno));
1912 if (rtp_debug_test_addr(&rtp->them))
1913 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1914 ast_inet_ntoa(rtp->them.sin_addr),
1915 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
1917 /* Sequence number of last two end packets does not get incremented */
1918 if (x < 3)
1919 rtp->seqno++;
1920 /* Clear marker bit and set seqno */
1921 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
1922 /* For the last three packets, set the duration and the end bit */
1923 if (x == 2) {
1924 #if 0
1925 /* No, this is wrong... Do not increment lastdigitts, that's not according
1926 to the RFC, as best we can determine */
1927 rtp->lastdigitts++; /* or else the SPA3000 will click instead of beeping... */
1928 rtpheader[1] = htonl(rtp->lastdigitts);
1929 #endif
1930 /* Make duration 800 (100ms) */
1931 rtpheader[3] |= htonl((800));
1932 /* Set the End bit */
1933 rtpheader[3] |= htonl((1 << 23));
1936 /*! \note Increment the digit timestamp by 120ms, to ensure that digits
1937 sent sequentially with no intervening non-digit packets do not
1938 get sent with the same timestamp, and that sequential digits
1939 have some 'dead air' in between them
1941 rtp->lastdigitts += 960;
1942 /* Increment the sequence number to reflect the last packet
1943 that was sent
1945 rtp->seqno++;
1946 return 0;
1949 /* \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
1950 int ast_rtcp_send_h261fur(void *data)
1952 struct ast_rtp *rtp = data;
1953 int res;
1955 rtp->rtcp->sendfur = 1;
1956 res = ast_rtcp_write(data);
1958 return res;
1961 /*! \brief Send RTCP sender's report */
1962 static int ast_rtcp_write_sr(void *data)
1964 struct ast_rtp *rtp = data;
1965 int res;
1966 int len = 0;
1967 struct timeval now;
1968 unsigned int now_lsw;
1969 unsigned int now_msw;
1970 unsigned int *rtcpheader;
1971 unsigned int lost;
1972 unsigned int extended;
1973 unsigned int expected;
1974 unsigned int expected_interval;
1975 unsigned int received_interval;
1976 int lost_interval;
1977 int fraction;
1978 struct timeval dlsr;
1979 char bdata[512];
1981 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
1982 return 0;
1984 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
1985 ast_verbose("RTCP SR transmission error, rtcp halted %s\n",strerror(errno));
1986 if (rtp->rtcp->schedid > 0)
1987 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1988 rtp->rtcp->schedid = -1;
1989 return 0;
1992 gettimeofday(&now, NULL);
1993 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
1994 rtcpheader = (unsigned int *)bdata;
1995 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
1996 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
1997 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
1998 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
1999 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
2000 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
2001 len += 28;
2003 extended = rtp->cycles + rtp->lastrxseqno;
2004 expected = extended - rtp->seedrxseqno + 1;
2005 if (rtp->rxcount > expected)
2006 expected += rtp->rxcount - expected;
2007 lost = expected - rtp->rxcount;
2008 expected_interval = expected - rtp->rtcp->expected_prior;
2009 rtp->rtcp->expected_prior = expected;
2010 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2011 rtp->rtcp->received_prior = rtp->rxcount;
2012 lost_interval = expected_interval - received_interval;
2013 if (expected_interval == 0 || lost_interval <= 0)
2014 fraction = 0;
2015 else
2016 fraction = (lost_interval << 8) / expected_interval;
2017 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2018 rtcpheader[7] = htonl(rtp->themssrc);
2019 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2020 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2021 rtcpheader[10] = htonl((unsigned int)rtp->rxjitter);
2022 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2023 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2024 len += 24;
2026 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2028 if (rtp->rtcp->sendfur) {
2029 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2030 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
2031 len += 8;
2032 rtp->rtcp->sendfur = 0;
2035 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2036 /* it can change mid call, and SDES can't) */
2037 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2038 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2039 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2040 len += 12;
2042 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2043 if (res < 0) {
2044 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));
2045 if (rtp->rtcp->schedid > 0)
2046 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2047 rtp->rtcp->schedid = -1;
2048 return 0;
2051 /* FIXME Don't need to get a new one */
2052 gettimeofday(&rtp->rtcp->txlsr, NULL);
2053 rtp->rtcp->sr_count++;
2055 rtp->rtcp->lastsrtxcount = rtp->txcount;
2057 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2058 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2059 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
2060 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2061 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
2062 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2063 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
2064 ast_verbose(" Report block:\n");
2065 ast_verbose(" Fraction lost: %u\n", fraction);
2066 ast_verbose(" Cumulative loss: %u\n", lost);
2067 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
2068 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
2069 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2071 return res;
2074 /*! \brief Send RTCP recepient's report */
2075 static int ast_rtcp_write_rr(void *data)
2077 struct ast_rtp *rtp = data;
2078 int res;
2079 int len = 32;
2080 unsigned int lost;
2081 unsigned int extended;
2082 unsigned int expected;
2083 unsigned int expected_interval;
2084 unsigned int received_interval;
2085 int lost_interval;
2086 struct timeval now;
2087 unsigned int *rtcpheader;
2088 char bdata[1024];
2089 struct timeval dlsr;
2090 int fraction;
2092 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2093 return 0;
2095 if (!rtp->rtcp->them.sin_addr.s_addr) {
2096 ast_log(LOG_ERROR, "RTCP RR transmission error to, rtcp halted %s\n",strerror(errno));
2097 if (rtp->rtcp->schedid > 0)
2098 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2099 rtp->rtcp->schedid = -1;
2100 return 0;
2103 extended = rtp->cycles + rtp->lastrxseqno;
2104 expected = extended - rtp->seedrxseqno + 1;
2105 lost = expected - rtp->rxcount;
2106 expected_interval = expected - rtp->rtcp->expected_prior;
2107 rtp->rtcp->expected_prior = expected;
2108 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2109 rtp->rtcp->received_prior = rtp->rxcount;
2110 lost_interval = expected_interval - received_interval;
2111 if (expected_interval == 0 || lost_interval <= 0)
2112 fraction = 0;
2113 else
2114 fraction = (lost_interval << 8) / expected_interval;
2115 gettimeofday(&now, NULL);
2116 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2117 rtcpheader = (unsigned int *)bdata;
2118 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2119 rtcpheader[1] = htonl(rtp->ssrc);
2120 rtcpheader[2] = htonl(rtp->themssrc);
2121 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2122 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2123 rtcpheader[5] = htonl((unsigned int)rtp->rxjitter);
2124 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2125 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2127 if (rtp->rtcp->sendfur) {
2128 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2129 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
2130 len += 8;
2131 rtp->rtcp->sendfur = 0;
2134 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2135 it can change mid call, and SDES can't) */
2136 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2137 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2138 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2139 len += 12;
2141 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2143 if (res < 0) {
2144 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2145 /* Remove the scheduler */
2146 if (rtp->rtcp->schedid > 0)
2147 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2148 rtp->rtcp->schedid = -1;
2149 return 0;
2152 rtp->rtcp->rr_count++;
2154 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2155 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2156 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2157 " IA jitter: %.4f\n"
2158 " Their last SR: %u\n"
2159 " DLSR: %4.4f (sec)\n\n",
2160 ast_inet_ntoa(rtp->rtcp->them.sin_addr),
2161 ntohs(rtp->rtcp->them.sin_port),
2162 rtp->ssrc, rtp->themssrc, fraction, lost,
2163 rtp->rxjitter,
2164 rtp->rtcp->themrxlsr,
2165 (double)(ntohl(rtcpheader[7])/65536.0));
2168 return res;
2171 /*! \brief Write and RTCP packet to the far end
2172 * \note Decide if we are going to send an SR (with Reception Block) or RR
2173 * RR is sent if we have not sent any rtp packets in the previous interval */
2174 static int ast_rtcp_write(void *data)
2176 struct ast_rtp *rtp = data;
2177 int res;
2179 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2180 res = ast_rtcp_write_sr(data);
2181 else
2182 res = ast_rtcp_write_rr(data);
2184 return res;
2187 /*! \brief generate comfort noice (CNG) */
2188 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2190 unsigned int *rtpheader;
2191 int hdrlen = 12;
2192 int res;
2193 int payload;
2194 char data[256];
2195 level = 127 - (level & 0x7f);
2196 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2198 /* If we have no peer, return immediately */
2199 if (!rtp->them.sin_addr.s_addr)
2200 return 0;
2202 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2204 /* Get a pointer to the header */
2205 rtpheader = (unsigned int *)data;
2206 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2207 rtpheader[1] = htonl(rtp->lastts);
2208 rtpheader[2] = htonl(rtp->ssrc);
2209 data[12] = level;
2210 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2211 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2212 if (res <0)
2213 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));
2214 if (rtp_debug_test_addr(&rtp->them))
2215 ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %u, len %d)\n"
2216 , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
2219 return 0;
2222 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2224 unsigned char *rtpheader;
2225 int hdrlen = 12;
2226 int res;
2227 unsigned int ms;
2228 int pred;
2229 int mark = 0;
2231 ms = calc_txstamp(rtp, &f->delivery);
2232 /* Default prediction */
2233 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
2234 pred = rtp->lastts + f->samples;
2236 /* Re-calculate last TS */
2237 rtp->lastts = rtp->lastts + ms * 8;
2238 if (ast_tvzero(f->delivery)) {
2239 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
2240 and if so, go with our prediction */
2241 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
2242 rtp->lastts = pred;
2243 else {
2244 if (option_debug > 2)
2245 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2246 mark = 1;
2249 } else {
2250 mark = f->subclass & 0x1;
2251 pred = rtp->lastovidtimestamp + f->samples;
2252 /* Re-calculate last TS */
2253 rtp->lastts = rtp->lastts + ms * 90;
2254 /* If it's close to our prediction, go for it */
2255 if (ast_tvzero(f->delivery)) {
2256 if (abs(rtp->lastts - pred) < 7200) {
2257 rtp->lastts = pred;
2258 rtp->lastovidtimestamp += f->samples;
2259 } else {
2260 if (option_debug > 2)
2261 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);
2262 rtp->lastovidtimestamp = rtp->lastts;
2266 /* If the timestamp for non-digit packets has moved beyond the timestamp
2267 for digits, update the digit timestamp.
2269 if (rtp->lastts > rtp->lastdigitts)
2270 rtp->lastdigitts = rtp->lastts;
2272 if (f->has_timing_info)
2273 rtp->lastts = f->ts * 8;
2275 /* Get a pointer to the header */
2276 rtpheader = (unsigned char *)(f->data - hdrlen);
2278 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
2279 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
2280 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
2282 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2283 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2284 if (res <0) {
2285 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
2286 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));
2287 } else if ((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) {
2288 /* Only give this error message once if we are not RTP debugging */
2289 if (option_debug || rtpdebug)
2290 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));
2291 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
2293 } else {
2294 rtp->txcount++;
2295 rtp->txoctetcount +=(res - hdrlen);
2297 if (rtp->rtcp->schedid < 1)
2298 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
2301 if (rtp_debug_test_addr(&rtp->them))
2302 ast_verbose("Sent RTP packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2303 ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
2306 rtp->seqno++;
2308 return 0;
2311 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
2313 struct ast_frame *f;
2314 int codec;
2315 int hdrlen = 12;
2316 int subclass;
2319 /* If we have no peer, return immediately */
2320 if (!rtp->them.sin_addr.s_addr)
2321 return 0;
2323 /* If there is no data length, return immediately */
2324 if (!_f->datalen)
2325 return 0;
2327 /* Make sure we have enough space for RTP header */
2328 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
2329 ast_log(LOG_WARNING, "RTP can only send voice and video\n");
2330 return -1;
2333 subclass = _f->subclass;
2334 if (_f->frametype == AST_FRAME_VIDEO)
2335 subclass &= ~0x1;
2337 codec = ast_rtp_lookup_code(rtp, 1, subclass);
2338 if (codec < 0) {
2339 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
2340 return -1;
2343 if (rtp->lasttxformat != subclass) {
2344 /* New format, reset the smoother */
2345 if (option_debug)
2346 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
2347 rtp->lasttxformat = subclass;
2348 if (rtp->smoother)
2349 ast_smoother_free(rtp->smoother);
2350 rtp->smoother = NULL;
2354 switch(subclass) {
2355 case AST_FORMAT_SLINEAR:
2356 if (!rtp->smoother) {
2357 rtp->smoother = ast_smoother_new(320);
2359 if (!rtp->smoother) {
2360 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2361 return -1;
2363 ast_smoother_feed_be(rtp->smoother, _f);
2365 while((f = ast_smoother_read(rtp->smoother)))
2366 ast_rtp_raw_write(rtp, f, codec);
2367 break;
2368 case AST_FORMAT_ULAW:
2369 case AST_FORMAT_ALAW:
2370 if (!rtp->smoother) {
2371 rtp->smoother = ast_smoother_new(160);
2373 if (!rtp->smoother) {
2374 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2375 return -1;
2377 ast_smoother_feed(rtp->smoother, _f);
2379 while((f = ast_smoother_read(rtp->smoother)))
2380 ast_rtp_raw_write(rtp, f, codec);
2381 break;
2382 case AST_FORMAT_ADPCM:
2383 case AST_FORMAT_G726:
2384 case AST_FORMAT_G726_AAL2:
2385 if (!rtp->smoother) {
2386 rtp->smoother = ast_smoother_new(80);
2388 if (!rtp->smoother) {
2389 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2390 return -1;
2392 ast_smoother_feed(rtp->smoother, _f);
2394 while((f = ast_smoother_read(rtp->smoother)))
2395 ast_rtp_raw_write(rtp, f, codec);
2396 break;
2397 case AST_FORMAT_G729A:
2398 if (!rtp->smoother) {
2399 rtp->smoother = ast_smoother_new(20);
2400 if (rtp->smoother)
2401 ast_smoother_set_flags(rtp->smoother, AST_SMOOTHER_FLAG_G729);
2403 if (!rtp->smoother) {
2404 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
2405 return -1;
2407 ast_smoother_feed(rtp->smoother, _f);
2409 while((f = ast_smoother_read(rtp->smoother)))
2410 ast_rtp_raw_write(rtp, f, codec);
2411 break;
2412 case AST_FORMAT_GSM:
2413 if (!rtp->smoother) {
2414 rtp->smoother = ast_smoother_new(33);
2416 if (!rtp->smoother) {
2417 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
2418 return -1;
2420 ast_smoother_feed(rtp->smoother, _f);
2421 while((f = ast_smoother_read(rtp->smoother)))
2422 ast_rtp_raw_write(rtp, f, codec);
2423 break;
2424 case AST_FORMAT_ILBC:
2425 if (!rtp->smoother) {
2426 rtp->smoother = ast_smoother_new(50);
2428 if (!rtp->smoother) {
2429 ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
2430 return -1;
2432 ast_smoother_feed(rtp->smoother, _f);
2433 while((f = ast_smoother_read(rtp->smoother)))
2434 ast_rtp_raw_write(rtp, f, codec);
2435 break;
2436 default:
2437 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
2438 /* fall through to... */
2439 case AST_FORMAT_H261:
2440 case AST_FORMAT_H263:
2441 case AST_FORMAT_H263_PLUS:
2442 case AST_FORMAT_H264:
2443 case AST_FORMAT_G723_1:
2444 case AST_FORMAT_LPC10:
2445 case AST_FORMAT_SPEEX:
2446 /* Don't buffer outgoing frames; send them one-per-packet: */
2447 if (_f->offset < hdrlen) {
2448 f = ast_frdup(_f);
2449 } else {
2450 f = _f;
2452 ast_rtp_raw_write(rtp, f, codec);
2455 return 0;
2458 /*! \brief Unregister interface to channel driver */
2459 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
2461 AST_LIST_LOCK(&protos);
2462 AST_LIST_REMOVE(&protos, proto, list);
2463 AST_LIST_UNLOCK(&protos);
2466 /*! \brief Register interface to channel driver */
2467 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
2469 struct ast_rtp_protocol *cur;
2471 AST_LIST_LOCK(&protos);
2472 AST_LIST_TRAVERSE(&protos, cur, list) {
2473 if (!strcmp(cur->type, proto->type)) {
2474 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
2475 AST_LIST_UNLOCK(&protos);
2476 return -1;
2479 AST_LIST_INSERT_HEAD(&protos, proto, list);
2480 AST_LIST_UNLOCK(&protos);
2482 return 0;
2485 /*! \brief Bridge calls. If possible and allowed, initiate
2486 re-invite so the peers exchange media directly outside
2487 of Asterisk. */
2488 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)
2490 struct ast_frame *f;
2491 struct ast_channel *who, *other, *cs[3];
2492 struct ast_rtp *p0, *p1; /* Audio RTP Channels */
2493 struct ast_rtp *vp0, *vp1; /* Video RTP channels */
2494 struct ast_rtp_protocol *pr0, *pr1;
2495 struct sockaddr_in ac0, ac1;
2496 struct sockaddr_in vac0, vac1;
2497 struct sockaddr_in t0, t1;
2498 struct sockaddr_in vt0, vt1;
2500 void *pvt0, *pvt1;
2501 int codec0,codec1, oldcodec0, oldcodec1;
2503 memset(&vt0, 0, sizeof(vt0));
2504 memset(&vt1, 0, sizeof(vt1));
2505 memset(&vac0, 0, sizeof(vac0));
2506 memset(&vac1, 0, sizeof(vac1));
2508 /* Lock channels */
2509 ast_channel_lock(c0);
2510 while(ast_channel_trylock(c1)) {
2511 ast_channel_unlock(c0);
2512 usleep(1);
2513 ast_channel_lock(c0);
2516 /* Find channel driver interfaces */
2517 pr0 = get_proto(c0);
2518 pr1 = get_proto(c1);
2519 if (!pr0) {
2520 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
2521 ast_channel_unlock(c0);
2522 ast_channel_unlock(c1);
2523 return AST_BRIDGE_FAILED;
2525 if (!pr1) {
2526 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
2527 ast_channel_unlock(c0);
2528 ast_channel_unlock(c1);
2529 return AST_BRIDGE_FAILED;
2532 /* Get channel specific interface structures */
2533 pvt0 = c0->tech_pvt;
2534 pvt1 = c1->tech_pvt;
2536 /* Get audio and video interface (if native bridge is possible) */
2537 p0 = pr0->get_rtp_info(c0);
2538 vp0 = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0) : NULL;
2539 p1 = pr1->get_rtp_info(c1);
2540 vp1 = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1) : NULL;
2542 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
2543 if (!p0 || !p1) {
2544 /* Somebody doesn't want to play... */
2545 ast_channel_unlock(c0);
2546 ast_channel_unlock(c1);
2547 return AST_BRIDGE_FAILED_NOWARN;
2550 if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2551 /* can't bridge, we are carrying DTMF for this channel and the bridge
2552 needs it
2554 ast_channel_unlock(c0);
2555 ast_channel_unlock(c1);
2556 return AST_BRIDGE_FAILED_NOWARN;
2559 if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
2560 /* can't bridge, we are carrying DTMF for this channel and the bridge
2561 needs it
2563 ast_channel_unlock(c0);
2564 ast_channel_unlock(c1);
2565 return AST_BRIDGE_FAILED_NOWARN;
2568 /* Get codecs from both sides */
2569 codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
2570 codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
2571 if (pr0->get_codec && pr1->get_codec) {
2572 /* Hey, we can't do reinvite if both parties speak different codecs */
2573 if (!(codec0 & codec1)) {
2574 if (option_debug)
2575 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
2576 ast_channel_unlock(c0);
2577 ast_channel_unlock(c1);
2578 return AST_BRIDGE_FAILED_NOWARN;
2582 if (option_verbose > 2)
2583 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2585 /* Ok, we should be able to redirect the media. Start with one channel */
2586 if (pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
2587 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
2588 else {
2589 /* Store RTP peer */
2590 ast_rtp_get_peer(p1, &ac1);
2591 if (vp1)
2592 ast_rtp_get_peer(vp1, &vac1);
2594 /* Then test the other channel */
2595 if (pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
2596 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
2597 else {
2598 /* Store RTP peer */
2599 ast_rtp_get_peer(p0, &ac0);
2600 if (vp0)
2601 ast_rtp_get_peer(vp0, &vac0);
2603 ast_channel_unlock(c0);
2604 ast_channel_unlock(c1);
2605 /* External RTP Bridge up, now loop and see if something happes that force us to take the
2606 media back to Asterisk */
2607 cs[0] = c0;
2608 cs[1] = c1;
2609 cs[2] = NULL;
2610 oldcodec0 = codec0;
2611 oldcodec1 = codec1;
2612 for (;;) {
2613 /* Check if something changed... */
2614 if ((c0->tech_pvt != pvt0) ||
2615 (c1->tech_pvt != pvt1) ||
2616 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
2617 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
2618 if (c0->tech_pvt == pvt0) {
2619 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2620 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2622 if (c1->tech_pvt == pvt1) {
2623 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2624 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2626 return AST_BRIDGE_RETRY;
2628 /* Now check if they have changed address */
2629 ast_rtp_get_peer(p1, &t1);
2630 ast_rtp_get_peer(p0, &t0);
2631 if (pr0->get_codec)
2632 codec0 = pr0->get_codec(c0);
2633 if (pr1->get_codec)
2634 codec1 = pr1->get_codec(c1);
2635 if (vp1)
2636 ast_rtp_get_peer(vp1, &vt1);
2637 if (vp0)
2638 ast_rtp_get_peer(vp0, &vt0);
2639 if (inaddrcmp(&t1, &ac1) || (vp1 && inaddrcmp(&vt1, &vac1)) || (codec1 != oldcodec1)) {
2640 if (option_debug > 1) {
2641 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2642 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
2643 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
2644 c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
2645 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2646 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
2647 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2648 c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
2650 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)))
2651 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
2652 memcpy(&ac1, &t1, sizeof(ac1));
2653 memcpy(&vac1, &vt1, sizeof(vac1));
2654 oldcodec1 = codec1;
2656 if (inaddrcmp(&t0, &ac0) || (vp0 && inaddrcmp(&vt0, &vac0))) {
2657 if (option_debug) {
2658 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2659 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
2660 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2661 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
2663 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)))
2664 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
2665 memcpy(&ac0, &t0, sizeof(ac0));
2666 memcpy(&vac0, &vt0, sizeof(vac0));
2667 oldcodec0 = codec0;
2669 who = ast_waitfor_n(cs, 2, &timeoutms);
2670 if (!who) {
2671 if (!timeoutms)
2672 return AST_BRIDGE_RETRY;
2673 if (option_debug)
2674 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2675 /* check for hangup / whentohangup */
2676 if (ast_check_hangup(c0) || ast_check_hangup(c1))
2677 break;
2678 continue;
2680 f = ast_read(who);
2681 other = (who == c0) ? c1 : c0; /* the other channel */
2682 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
2683 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
2684 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
2685 /* breaking out of the bridge. */
2686 *fo = f;
2687 *rc = who;
2688 if (option_debug)
2689 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
2690 if ((c0->tech_pvt == pvt0)) {
2691 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2692 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2694 if ((c1->tech_pvt == pvt1)) {
2695 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2696 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2698 return AST_BRIDGE_COMPLETE;
2699 } else if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2700 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
2701 (f->subclass == AST_CONTROL_VIDUPDATE)) {
2702 ast_indicate(other, f->subclass);
2703 ast_frfree(f);
2704 } else {
2705 *fo = f;
2706 *rc = who;
2707 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2708 return AST_BRIDGE_COMPLETE;
2710 } else {
2711 if ((f->frametype == AST_FRAME_DTMF) ||
2712 (f->frametype == AST_FRAME_VOICE) ||
2713 (f->frametype == AST_FRAME_VIDEO)) {
2714 /* Forward voice or DTMF frames if they happen upon us */
2715 ast_write(other, f);
2717 ast_frfree(f);
2719 /* Swap priority not that it's a big deal at this point */
2720 cs[2] = cs[0];
2721 cs[0] = cs[1];
2722 cs[1] = cs[2];
2725 return AST_BRIDGE_FAILED;
2728 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
2730 struct hostent *hp;
2731 struct ast_hostent ahp;
2732 int port = 0;
2733 char *p, *arg;
2735 if (argc != 4)
2736 return RESULT_SHOWUSAGE;
2737 arg = argv[3];
2738 p = strstr(arg, ":");
2739 if (p) {
2740 *p = '\0';
2741 p++;
2742 port = atoi(p);
2744 hp = ast_gethostbyname(arg, &ahp);
2745 if (hp == NULL)
2746 return RESULT_SHOWUSAGE;
2747 rtpdebugaddr.sin_family = AF_INET;
2748 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
2749 rtpdebugaddr.sin_port = htons(port);
2750 if (port == 0)
2751 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr.sin_addr));
2752 else
2753 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr.sin_addr), port);
2754 rtpdebug = 1;
2755 return RESULT_SUCCESS;
2758 static int rtcp_do_debug_ip(int fd, int argc, char *argv[])
2760 struct hostent *hp;
2761 struct ast_hostent ahp;
2762 int port = 0;
2763 char *p, *arg;
2764 if (argc != 5)
2765 return RESULT_SHOWUSAGE;
2767 arg = argv[4];
2768 p = strstr(arg, ":");
2769 if (p) {
2770 *p = '\0';
2771 p++;
2772 port = atoi(p);
2774 hp = ast_gethostbyname(arg, &ahp);
2775 if (hp == NULL)
2776 return RESULT_SHOWUSAGE;
2777 rtcpdebugaddr.sin_family = AF_INET;
2778 memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
2779 rtcpdebugaddr.sin_port = htons(port);
2780 if (port == 0)
2781 ast_cli(fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
2782 else
2783 ast_cli(fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
2784 rtcpdebug = 1;
2785 return RESULT_SUCCESS;
2788 static int rtp_do_debug(int fd, int argc, char *argv[])
2790 if (argc != 2) {
2791 if (argc != 4)
2792 return RESULT_SHOWUSAGE;
2793 return rtp_do_debug_ip(fd, argc, argv);
2795 rtpdebug = 1;
2796 memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
2797 ast_cli(fd, "RTP Debugging Enabled\n");
2798 return RESULT_SUCCESS;
2801 static int rtcp_do_debug(int fd, int argc, char *argv[]) {
2802 if (argc != 3) {
2803 if (argc != 5)
2804 return RESULT_SHOWUSAGE;
2805 return rtcp_do_debug_ip(fd, argc, argv);
2807 rtcpdebug = 1;
2808 memset(&rtcpdebugaddr,0,sizeof(rtcpdebugaddr));
2809 ast_cli(fd, "RTCP Debugging Enabled\n");
2810 return RESULT_SUCCESS;
2813 static int rtcp_do_stats(int fd, int argc, char *argv[]) {
2814 if (argc != 3) {
2815 return RESULT_SHOWUSAGE;
2817 rtcpstats = 1;
2818 ast_cli(fd, "RTCP Stats Enabled\n");
2819 return RESULT_SUCCESS;
2822 static int rtp_no_debug(int fd, int argc, char *argv[])
2824 if (argc != 3)
2825 return RESULT_SHOWUSAGE;
2826 rtpdebug = 0;
2827 ast_cli(fd,"RTP Debugging Disabled\n");
2828 return RESULT_SUCCESS;
2831 static int rtcp_no_debug(int fd, int argc, char *argv[])
2833 if (argc != 4)
2834 return RESULT_SHOWUSAGE;
2835 rtcpdebug = 0;
2836 ast_cli(fd,"RTCP Debugging Disabled\n");
2837 return RESULT_SUCCESS;
2840 static int rtcp_no_stats(int fd, int argc, char *argv[])
2842 if (argc != 4)
2843 return RESULT_SHOWUSAGE;
2844 rtcpstats = 0;
2845 ast_cli(fd,"RTCP Stats Disabled\n");
2846 return RESULT_SUCCESS;
2850 static int stun_do_debug(int fd, int argc, char *argv[])
2852 if (argc != 2) {
2853 return RESULT_SHOWUSAGE;
2855 stundebug = 1;
2856 ast_cli(fd, "STUN Debugging Enabled\n");
2857 return RESULT_SUCCESS;
2860 static int stun_no_debug(int fd, int argc, char *argv[])
2862 if (argc != 3)
2863 return RESULT_SHOWUSAGE;
2864 stundebug = 0;
2865 ast_cli(fd,"STUN Debugging Disabled\n");
2866 return RESULT_SUCCESS;
2870 static char debug_usage[] =
2871 "Usage: rtp debug [ip host[:port]]\n"
2872 " Enable dumping of all RTP packets to and from host.\n";
2874 static char no_debug_usage[] =
2875 "Usage: rtp no debug\n"
2876 " Disable all RTP debugging\n";
2878 static char stun_debug_usage[] =
2879 "Usage: stun debug\n"
2880 " Enable STUN (Simple Traversal of UDP through NATs) debugging\n";
2882 static char stun_no_debug_usage[] =
2883 "Usage: stun no debug\n"
2884 " Disable STUN debugging\n";
2887 static struct ast_cli_entry cli_debug_ip =
2888 {{ "rtp", "debug", "ip", NULL } , rtp_do_debug, "Enable RTP debugging on IP", debug_usage };
2890 static struct ast_cli_entry cli_debug =
2891 {{ "rtp", "debug", NULL } , rtp_do_debug, "Enable RTP debugging", debug_usage };
2893 static struct ast_cli_entry cli_no_debug =
2894 {{ "rtp", "no", "debug", NULL } , rtp_no_debug, "Disable RTP debugging", no_debug_usage };
2896 static char rtcp_debug_usage[] =
2897 "Usage: rtp rtcp debug [ip host[:port]]\n"
2898 " Enable dumping of all RTCP packets to and from host.\n";
2900 static char rtcp_no_debug_usage[] =
2901 "Usage: rtp rtcp no debug\n"
2902 " Disable all RTCP debugging\n";
2904 static char rtcp_stats_usage[] =
2905 "Usage: rtp rtcp stats\n"
2906 " Enable dumping of RTCP stats.\n";
2908 static char rtcp_no_stats_usage[] =
2909 "Usage: rtp rtcp no stats\n"
2910 " Disable all RTCP stats\n";
2912 static struct ast_cli_entry cli_debug_ip_rtcp =
2913 {{ "rtp", "rtcp", "debug", "ip", NULL } , rtcp_do_debug, "Enable RTCP debugging on IP", rtcp_debug_usage };
2915 static struct ast_cli_entry cli_debug_rtcp =
2916 {{ "rtp", "rtcp", "debug", NULL } , rtcp_do_debug, "Enable RTCP debugging", rtcp_debug_usage };
2918 static struct ast_cli_entry cli_no_debug_rtcp =
2919 {{ "rtp", "rtcp", "no", "debug", NULL } , rtcp_no_debug, "Disable RTCP debugging", rtcp_no_debug_usage };
2921 static struct ast_cli_entry cli_stats_rtcp =
2922 {{ "rtp", "rtcp", "stats", NULL } , rtcp_do_stats, "Enable RTCP stats", rtcp_stats_usage };
2924 static struct ast_cli_entry cli_no_stats_rtcp =
2925 {{ "rtp", "rtcp", "no", "stats", NULL } , rtcp_no_stats, "Disable RTCP stats", rtcp_no_stats_usage };
2927 static struct ast_cli_entry cli_stun_debug =
2928 {{ "stun", "debug", NULL } , stun_do_debug, "Enable STUN debugging", stun_debug_usage };
2930 static struct ast_cli_entry cli_stun_no_debug =
2931 {{ "stun", "no", "debug", NULL } , stun_no_debug, "Disable STUN debugging", stun_no_debug_usage };
2933 int ast_rtp_reload(void)
2935 struct ast_config *cfg;
2936 char *s;
2938 rtpstart = 5000;
2939 rtpend = 31000;
2940 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2941 cfg = ast_config_load("rtp.conf");
2942 if (cfg) {
2943 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
2944 rtpstart = atoi(s);
2945 if (rtpstart < 1024)
2946 rtpstart = 1024;
2947 if (rtpstart > 65535)
2948 rtpstart = 65535;
2950 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
2951 rtpend = atoi(s);
2952 if (rtpend < 1024)
2953 rtpend = 1024;
2954 if (rtpend > 65535)
2955 rtpend = 65535;
2957 if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
2958 rtcpinterval = atoi(s);
2959 if (rtcpinterval == 0)
2960 rtcpinterval = 0; /* Just so we're clear... it's zero */
2961 if (rtcpinterval < RTCP_MIN_INTERVALMS)
2962 rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
2963 if (rtcpinterval > RTCP_MAX_INTERVALMS)
2964 rtcpinterval = RTCP_MAX_INTERVALMS;
2966 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
2967 #ifdef SO_NO_CHECK
2968 if (ast_false(s))
2969 nochecksums = 1;
2970 else
2971 nochecksums = 0;
2972 #else
2973 if (ast_false(s))
2974 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
2975 #endif
2977 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
2978 dtmftimeout = atoi(s);
2979 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
2980 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
2981 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
2982 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2985 ast_config_destroy(cfg);
2987 if (rtpstart >= rtpend) {
2988 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
2989 rtpstart = 5000;
2990 rtpend = 31000;
2992 if (option_verbose > 1)
2993 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
2994 return 0;
2997 /*! \brief Initialize the RTP system in Asterisk */
2998 void ast_rtp_init(void)
3000 ast_cli_register(&cli_debug);
3001 ast_cli_register(&cli_debug_ip);
3002 ast_cli_register(&cli_no_debug);
3004 ast_cli_register(&cli_debug_rtcp);
3005 ast_cli_register(&cli_debug_ip_rtcp);
3006 ast_cli_register(&cli_no_debug_rtcp);
3008 ast_cli_register(&cli_stats_rtcp);
3009 ast_cli_register(&cli_no_stats_rtcp);
3011 ast_cli_register(&cli_stun_debug);
3012 ast_cli_register(&cli_stun_no_debug);
3013 ast_rtp_reload();