officially deprecate the 'roundrobin' queue strategy in favor of 'rrmemory'
[asterisk-bristuff.git] / rtp.c
blobbfb2262038c09df6d221a27b8f1b72ab7163e05c
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 <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/time.h>
33 #include <signal.h>
34 #include <errno.h>
35 #include <unistd.h>
36 #include <netinet/in.h>
37 #include <sys/time.h>
38 #include <sys/socket.h>
39 #include <arpa/inet.h>
40 #include <fcntl.h>
42 #include "asterisk.h"
44 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
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_MTU 1200
64 #define DEFAULT_DTMF_TIMEOUT 3000 /*!< samples */
66 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
68 static int rtpstart = 0; /*!< First port for RTP sessions (set in rtp.conf) */
69 static int rtpend = 0; /*!< Last port for RTP sessions (set in rtp.conf) */
70 static int rtpdebug = 0; /*!< Are we debugging? */
71 static int stundebug = 0; /*!< Are we debugging stun? */
72 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
73 #ifdef SO_NO_CHECK
74 static int nochecksums = 0;
75 #endif
77 /*! \brief The value of each payload format mapping: */
78 struct rtpPayloadType {
79 int isAstFormat; /*!< whether the following code is an AST_FORMAT */
80 int code;
83 #define MAX_RTP_PT 256
85 #define FLAG_3389_WARNING (1 << 0)
86 #define FLAG_NAT_ACTIVE (3 << 1)
87 #define FLAG_NAT_INACTIVE (0 << 1)
88 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
89 #define FLAG_HAS_DTMF (1 << 3)
91 /*! \brief RTP session description */
92 struct ast_rtp {
93 int s;
94 char resp;
95 struct ast_frame f;
96 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
97 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
98 unsigned int rxssrc;
99 unsigned int lastts;
100 unsigned int lastdigitts;
101 unsigned int lastrxts;
102 unsigned int lastividtimestamp;
103 unsigned int lastovidtimestamp;
104 unsigned int lasteventseqn;
105 unsigned int lasteventendseqn;
106 int lasttxformat;
107 int lastrxformat;
108 int dtmfcount;
109 unsigned int dtmfduration;
110 int nat;
111 unsigned int flags;
112 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
113 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
114 struct timeval rxcore;
115 struct timeval txcore;
116 struct timeval dtmfmute;
117 struct ast_smoother *smoother;
118 int *ioid;
119 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
120 unsigned short rxseqno;
121 struct sched_context *sched;
122 struct io_context *io;
123 void *data;
124 ast_rtp_callback callback;
125 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
126 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
127 int rtp_lookup_code_cache_code;
128 int rtp_lookup_code_cache_result;
129 struct ast_rtcp *rtcp;
133 * \brief Structure defining an RTCP session.
135 * The concept "RTCP session" is not defined in RFC 3550, but since
136 * this structure is analogous to ast_rtp, which tracks a RTP session,
137 * it is logical to think of this as a RTCP session.
139 * RTCP packet is defined on page 9 of RFC 3550.
142 struct ast_rtcp {
143 int s; /*!< Socket */
144 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
145 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
149 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
151 /* XXX Maybe stun belongs in another file if it ever has use outside of RTP */
152 struct stun_header {
153 unsigned short msgtype;
154 unsigned short msglen;
155 stun_trans_id id;
156 unsigned char ies[0];
157 } __attribute__((packed));
159 struct stun_attr {
160 unsigned short attr;
161 unsigned short len;
162 unsigned char value[0];
163 } __attribute__((packed));
165 struct stun_addr {
166 unsigned char unused;
167 unsigned char family;
168 unsigned short port;
169 unsigned int addr;
170 } __attribute__((packed));
172 #define STUN_IGNORE (0)
173 #define STUN_ACCEPT (1)
175 #define STUN_BINDREQ 0x0001
176 #define STUN_BINDRESP 0x0101
177 #define STUN_BINDERR 0x0111
178 #define STUN_SECREQ 0x0002
179 #define STUN_SECRESP 0x0102
180 #define STUN_SECERR 0x0112
182 #define STUN_MAPPED_ADDRESS 0x0001
183 #define STUN_RESPONSE_ADDRESS 0x0002
184 #define STUN_CHANGE_REQUEST 0x0003
185 #define STUN_SOURCE_ADDRESS 0x0004
186 #define STUN_CHANGED_ADDRESS 0x0005
187 #define STUN_USERNAME 0x0006
188 #define STUN_PASSWORD 0x0007
189 #define STUN_MESSAGE_INTEGRITY 0x0008
190 #define STUN_ERROR_CODE 0x0009
191 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
192 #define STUN_REFLECTED_FROM 0x000b
194 static const char *stun_msg2str(int msg)
196 switch(msg) {
197 case STUN_BINDREQ:
198 return "Binding Request";
199 case STUN_BINDRESP:
200 return "Binding Response";
201 case STUN_BINDERR:
202 return "Binding Error Response";
203 case STUN_SECREQ:
204 return "Shared Secret Request";
205 case STUN_SECRESP:
206 return "Shared Secret Response";
207 case STUN_SECERR:
208 return "Shared Secret Error Response";
210 return "Non-RFC3489 Message";
213 static const char *stun_attr2str(int msg)
215 switch(msg) {
216 case STUN_MAPPED_ADDRESS:
217 return "Mapped Address";
218 case STUN_RESPONSE_ADDRESS:
219 return "Response Address";
220 case STUN_CHANGE_REQUEST:
221 return "Change Request";
222 case STUN_SOURCE_ADDRESS:
223 return "Source Address";
224 case STUN_CHANGED_ADDRESS:
225 return "Changed Address";
226 case STUN_USERNAME:
227 return "Username";
228 case STUN_PASSWORD:
229 return "Password";
230 case STUN_MESSAGE_INTEGRITY:
231 return "Message Integrity";
232 case STUN_ERROR_CODE:
233 return "Error Code";
234 case STUN_UNKNOWN_ATTRIBUTES:
235 return "Unknown Attributes";
236 case STUN_REFLECTED_FROM:
237 return "Reflected From";
239 return "Non-RFC3489 Attribute";
242 struct stun_state {
243 unsigned char *username;
244 unsigned char *password;
247 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
249 if (stundebug)
250 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
251 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
252 switch(ntohs(attr->attr)) {
253 case STUN_USERNAME:
254 state->username = (unsigned char *)(attr->value);
255 break;
256 case STUN_PASSWORD:
257 state->password = (unsigned char *)(attr->value);
258 break;
259 default:
260 if (stundebug)
261 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
262 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
264 return 0;
267 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
269 int size = sizeof(**attr) + strlen(s);
270 if (*left > size) {
271 (*attr)->attr = htons(attrval);
272 (*attr)->len = htons(strlen(s));
273 memcpy((*attr)->value, s, strlen(s));
274 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
275 *len += size;
276 *left -= size;
280 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
282 int size = sizeof(**attr) + 8;
283 struct stun_addr *addr;
284 if (*left > size) {
285 (*attr)->attr = htons(attrval);
286 (*attr)->len = htons(8);
287 addr = (struct stun_addr *)((*attr)->value);
288 addr->unused = 0;
289 addr->family = 0x01;
290 addr->port = sin->sin_port;
291 addr->addr = sin->sin_addr.s_addr;
292 (*attr) = (struct stun_attr *)((*attr)->value + 8);
293 *len += size;
294 *left -= size;
298 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
300 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
301 (struct sockaddr *)dst, sizeof(*dst));
304 static void stun_req_id(struct stun_header *req)
306 int x;
307 for (x=0;x<4;x++)
308 req->id.id[x] = ast_random();
311 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
313 struct stun_header *req;
314 unsigned char reqdata[1024];
315 int reqlen, reqleft;
316 struct stun_attr *attr;
318 req = (struct stun_header *)reqdata;
319 stun_req_id(req);
320 reqlen = 0;
321 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
322 req->msgtype = 0;
323 req->msglen = 0;
324 attr = (struct stun_attr *)req->ies;
325 if (username)
326 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
327 req->msglen = htons(reqlen);
328 req->msgtype = htons(STUN_BINDREQ);
329 stun_send(rtp->s, suggestion, req);
332 static int stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len)
334 struct stun_header *resp, *hdr = (struct stun_header *)data;
335 struct stun_attr *attr;
336 struct stun_state st;
337 int ret = STUN_IGNORE;
338 unsigned char respdata[1024];
339 int resplen, respleft;
341 if (len < sizeof(struct stun_header)) {
342 if (option_debug)
343 ast_log(LOG_DEBUG, "Runt STUN packet (only %zd, wanting at least %zd)\n", len, sizeof(struct stun_header));
344 return -1;
346 if (stundebug)
347 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), ntohs(hdr->msglen));
348 if (ntohs(hdr->msglen) > len - sizeof(struct stun_header)) {
349 if (option_debug)
350 ast_log(LOG_DEBUG, "Scrambled STUN packet length (got %d, expecting %zd)\n", ntohs(hdr->msglen), len - sizeof(struct stun_header));
351 } else
352 len = ntohs(hdr->msglen);
353 data += sizeof(struct stun_header);
354 memset(&st, 0, sizeof(st));
355 while(len) {
356 if (len < sizeof(struct stun_attr)) {
357 if (option_debug)
358 ast_log(LOG_DEBUG, "Runt Attribute (got %zd, expecting %zd)\n", len, sizeof(struct stun_attr));
359 break;
361 attr = (struct stun_attr *)data;
362 if (ntohs(attr->len) > len) {
363 if (option_debug)
364 ast_log(LOG_DEBUG, "Inconsistant Attribute (length %d exceeds remaining msg len %zd)\n", ntohs(attr->len), len);
365 break;
367 if (stun_process_attr(&st, attr)) {
368 if (option_debug)
369 ast_log(LOG_DEBUG, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
370 break;
372 /* Clear attribute in case previous entry was a string */
373 attr->attr = 0;
374 data += ntohs(attr->len) + sizeof(struct stun_attr);
375 len -= ntohs(attr->len) + sizeof(struct stun_attr);
377 /* Null terminate any string */
378 *data = '\0';
379 resp = (struct stun_header *)respdata;
380 resplen = 0;
381 respleft = sizeof(respdata) - sizeof(struct stun_header);
382 resp->id = hdr->id;
383 resp->msgtype = 0;
384 resp->msglen = 0;
385 attr = (struct stun_attr *)resp->ies;
386 if (!len) {
387 switch(ntohs(hdr->msgtype)) {
388 case STUN_BINDREQ:
389 if (stundebug)
390 ast_verbose("STUN Bind Request, username: %s\n",
391 st.username ? (const char *)st.username : "<none>");
392 if (st.username)
393 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
394 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
395 resp->msglen = htons(resplen);
396 resp->msgtype = htons(STUN_BINDRESP);
397 stun_send(s, src, resp);
398 ret = STUN_ACCEPT;
399 break;
400 default:
401 if (stundebug)
402 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
405 return ret;
408 /*! \brief List of current sessions */
409 static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
411 int ast_rtp_fd(struct ast_rtp *rtp)
413 return rtp->s;
416 int ast_rtcp_fd(struct ast_rtp *rtp)
418 if (rtp->rtcp)
419 return rtp->rtcp->s;
420 return -1;
423 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
425 rtp->data = data;
428 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
430 rtp->callback = callback;
433 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
435 rtp->nat = nat;
438 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
440 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
443 static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
445 char iabuf[INET_ADDRSTRLEN];
447 if (ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
448 if (option_debug)
449 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
450 rtp->resp = 0;
451 rtp->dtmfduration = 0;
452 return &ast_null_frame;
454 if (option_debug)
455 ast_log(LOG_DEBUG, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
456 if (rtp->resp == 'X') {
457 rtp->f.frametype = AST_FRAME_CONTROL;
458 rtp->f.subclass = AST_CONTROL_FLASH;
459 } else {
460 rtp->f.frametype = AST_FRAME_DTMF;
461 rtp->f.subclass = rtp->resp;
463 rtp->f.datalen = 0;
464 rtp->f.samples = 0;
465 rtp->f.mallocd = 0;
466 rtp->f.src = "RTP";
467 rtp->resp = 0;
468 rtp->dtmfduration = 0;
469 return &rtp->f;
473 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
475 if (rtpdebug == 0)
476 return 0;
477 if (rtpdebugaddr.sin_addr.s_addr) {
478 if (((ntohs(rtpdebugaddr.sin_port) != 0)
479 && (rtpdebugaddr.sin_port != addr->sin_port))
480 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
481 return 0;
483 return 1;
486 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
488 unsigned int event;
489 char resp = 0;
490 struct ast_frame *f = NULL;
491 event = ntohl(*((unsigned int *)(data)));
492 event &= 0x001F;
493 if (option_debug > 2 || rtpdebug)
494 ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
495 if (event < 10) {
496 resp = '0' + event;
497 } else if (event < 11) {
498 resp = '*';
499 } else if (event < 12) {
500 resp = '#';
501 } else if (event < 16) {
502 resp = 'A' + (event - 12);
503 } else if (event < 17) {
504 resp = 'X';
506 if (rtp->resp && (rtp->resp != resp)) {
507 f = send_dtmf(rtp);
509 rtp->resp = resp;
510 rtp->dtmfcount = dtmftimeout;
511 return f;
514 /*!
515 * \brief Process RTP DTMF and events according to RFC 2833.
517 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
519 * \param rtp
520 * \param data
521 * \param len
522 * \param seqno
523 * \returns
525 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
527 unsigned int event;
528 unsigned int event_end;
529 unsigned int duration;
530 char resp = 0;
531 struct ast_frame *f = NULL;
533 event = ntohl(*((unsigned int *)(data)));
534 event >>= 24;
535 event_end = ntohl(*((unsigned int *)(data)));
536 event_end <<= 8;
537 event_end >>= 24;
538 duration = ntohl(*((unsigned int *)(data)));
539 duration &= 0xFFFF;
540 if (rtpdebug || option_debug > 2)
541 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
542 if (event < 10) {
543 resp = '0' + event;
544 } else if (event < 11) {
545 resp = '*';
546 } else if (event < 12) {
547 resp = '#';
548 } else if (event < 16) {
549 resp = 'A' + (event - 12);
550 } else if (event < 17) { /* Event 16: Hook flash */
551 resp = 'X';
553 if (rtp->resp && (rtp->resp != resp)) {
554 f = send_dtmf(rtp);
555 } else if(event_end & 0x80) {
556 if (rtp->resp) {
557 if(rtp->lasteventendseqn != seqno) {
558 f = send_dtmf(rtp);
559 rtp->lasteventendseqn = seqno;
561 rtp->resp = 0;
563 resp = 0;
564 duration = 0;
565 } else if (rtp->resp && rtp->dtmfduration && (duration < rtp->dtmfduration)) {
566 f = send_dtmf(rtp);
568 if (!(event_end & 0x80))
569 rtp->resp = resp;
570 rtp->dtmfcount = dtmftimeout;
571 rtp->dtmfduration = duration;
572 return f;
576 * \brief Process Comfort Noise RTP.
578 * This is incomplete at the moment.
581 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
583 struct ast_frame *f = NULL;
584 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
585 totally help us out becuase we don't have an engine to keep it going and we are not
586 guaranteed to have it every 20ms or anything */
587 if (rtpdebug)
588 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
590 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
591 char iabuf[INET_ADDRSTRLEN];
593 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
594 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
595 ast_set_flag(rtp, FLAG_3389_WARNING);
598 /* Must have at least one byte */
599 if (!len)
600 return NULL;
601 if (len < 24) {
602 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
603 rtp->f.datalen = len - 1;
604 rtp->f.offset = AST_FRIENDLY_OFFSET;
605 memcpy(rtp->f.data, data + 1, len - 1);
606 } else {
607 rtp->f.data = NULL;
608 rtp->f.offset = 0;
609 rtp->f.datalen = 0;
611 rtp->f.frametype = AST_FRAME_CNG;
612 rtp->f.subclass = data[0] & 0x7f;
613 rtp->f.datalen = len - 1;
614 rtp->f.samples = 0;
615 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
616 f = &rtp->f;
617 return f;
620 static int rtpread(int *id, int fd, short events, void *cbdata)
622 struct ast_rtp *rtp = cbdata;
623 struct ast_frame *f;
624 f = ast_rtp_read(rtp);
625 if (f) {
626 if (rtp->callback)
627 rtp->callback(rtp, f, rtp->data);
629 return 1;
632 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
634 socklen_t len;
635 int hdrlen = 8;
636 int res;
637 struct sockaddr_in sin;
638 unsigned int rtcpdata[1024];
639 char iabuf[INET_ADDRSTRLEN];
641 if (!rtp || !rtp->rtcp)
642 return &ast_null_frame;
644 len = sizeof(sin);
646 res = recvfrom(rtp->rtcp->s, rtcpdata, sizeof(rtcpdata),
647 0, (struct sockaddr *)&sin, &len);
649 if (res < 0) {
650 if (errno != EAGAIN)
651 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
652 if (errno == EBADF)
653 CRASH;
654 return &ast_null_frame;
657 if (res < hdrlen) {
658 ast_log(LOG_WARNING, "RTP Read too short\n");
659 return &ast_null_frame;
662 if (rtp->nat) {
663 /* Send to whoever sent to us */
664 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
665 (rtp->rtcp->them.sin_port != sin.sin_port)) {
666 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
667 if (option_debug || rtpdebug)
668 ast_log(LOG_DEBUG, "RTCP NAT: Got RTCP from other end. Now sending to address %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
671 if (option_debug)
672 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
673 return &ast_null_frame;
676 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
678 struct timeval ts = ast_samp2tv( timestamp, 8000);
679 if (ast_tvzero(rtp->rxcore) || mark) {
680 rtp->rxcore = ast_tvsub(ast_tvnow(), ts);
681 /* Round to 20ms for nice, pretty timestamps */
682 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 20000;
684 *tv = ast_tvadd(rtp->rxcore, ts);
687 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
689 int res;
690 struct sockaddr_in sin;
691 socklen_t len;
692 unsigned int seqno;
693 int version;
694 int payloadtype;
695 int hdrlen = 12;
696 int padding;
697 int mark;
698 int ext;
699 int x;
700 char iabuf[INET_ADDRSTRLEN];
701 unsigned int ssrc;
702 unsigned int timestamp;
703 unsigned int *rtpheader;
704 struct rtpPayloadType rtpPT;
706 len = sizeof(sin);
708 /* Cache where the header will go */
709 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
710 0, (struct sockaddr *)&sin, &len);
712 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
713 if (res < 0) {
714 if (errno != EAGAIN)
715 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
716 if (errno == EBADF)
717 CRASH;
718 return &ast_null_frame;
720 if (res < hdrlen) {
721 ast_log(LOG_WARNING, "RTP Read too short\n");
722 return &ast_null_frame;
725 /* Get fields */
726 seqno = ntohl(rtpheader[0]);
728 /* Check RTP version */
729 version = (seqno & 0xC0000000) >> 30;
730 if (!version) {
731 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res) == STUN_ACCEPT) &&
732 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
733 memcpy(&rtp->them, &sin, sizeof(rtp->them));
735 return &ast_null_frame;
738 if (version != 2)
739 return &ast_null_frame;
740 /* Ignore if the other side hasn't been given an address
741 yet. */
742 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
743 return &ast_null_frame;
745 if (rtp->nat) {
746 /* Send to whoever sent to us */
747 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
748 (rtp->them.sin_port != sin.sin_port)) {
749 rtp->them = sin;
750 rtp->rxseqno = 0;
751 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
752 if (option_debug || rtpdebug)
753 ast_log(LOG_DEBUG, "RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port));
757 payloadtype = (seqno & 0x7f0000) >> 16;
758 padding = seqno & (1 << 29);
759 mark = seqno & (1 << 23);
760 ext = seqno & (1 << 28);
761 seqno &= 0xffff;
762 timestamp = ntohl(rtpheader[1]);
763 ssrc = ntohl(rtpheader[2]);
765 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
766 ast_log(LOG_WARNING, "Forcing Marker bit, because SSRC has changed\n");
767 mark = 1;
770 rtp->rxssrc = ssrc;
772 if (padding) {
773 /* Remove padding bytes */
774 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
777 if (ext) {
778 /* RTP Extension present */
779 hdrlen += 4;
780 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
783 if (res < hdrlen) {
784 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
785 return &ast_null_frame;
788 if(rtp_debug_test_addr(&sin))
789 ast_verbose("Got RTP packet from %s:%d (type %d, seq %d, ts %d, len %d)\n"
790 , ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
792 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
793 if (!rtpPT.isAstFormat) {
794 struct ast_frame *f = NULL;
796 /* This is special in-band data that's not one of our codecs */
797 if (rtpPT.code == AST_RTP_DTMF) {
798 /* It's special -- rfc2833 process it */
799 if(rtp_debug_test_addr(&sin)) {
800 unsigned char *data;
801 unsigned int event;
802 unsigned int event_end;
803 unsigned int duration;
804 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
805 event = ntohl(*((unsigned int *)(data)));
806 event >>= 24;
807 event_end = ntohl(*((unsigned int *)(data)));
808 event_end <<= 8;
809 event_end >>= 24;
810 duration = ntohl(*((unsigned int *)(data)));
811 duration &= 0xFFFF;
812 ast_verbose("Got rfc2833 RTP packet from %s:%d (type %d, seq %d, ts %d, len %d, mark %d, event %08x, end %d, duration %d) \n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
814 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
815 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
816 rtp->lasteventseqn = seqno;
818 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
819 /* It's really special -- process it the Cisco way */
820 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
821 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
822 rtp->lasteventseqn = seqno;
824 } else if (rtpPT.code == AST_RTP_CN) {
825 /* Comfort Noise */
826 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
827 } else {
828 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
830 return f ? f : &ast_null_frame;
832 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
833 rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : AST_FRAME_VIDEO;
835 if (!rtp->lastrxts)
836 rtp->lastrxts = timestamp;
838 if (rtp->rxseqno) {
839 for (x=rtp->rxseqno + 1; x < seqno; x++) {
840 /* Queue empty frames */
841 rtp->f.mallocd = 0;
842 rtp->f.datalen = 0;
843 rtp->f.data = NULL;
844 rtp->f.offset = 0;
845 rtp->f.samples = 0;
846 rtp->f.src = "RTPMissedFrame";
849 rtp->rxseqno = seqno;
851 if (rtp->dtmfcount) {
852 #if 0
853 printf("dtmfcount was %d\n", rtp->dtmfcount);
854 #endif
855 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
856 if (rtp->dtmfcount < 0)
857 rtp->dtmfcount = 0;
858 #if 0
859 if (dtmftimeout != rtp->dtmfcount)
860 printf("dtmfcount is %d\n", rtp->dtmfcount);
861 #endif
863 rtp->lastrxts = timestamp;
865 /* Send any pending DTMF */
866 if (rtp->resp && !rtp->dtmfcount) {
867 if (option_debug)
868 ast_log(LOG_DEBUG, "Sending pending DTMF\n");
869 return send_dtmf(rtp);
871 rtp->f.mallocd = 0;
872 rtp->f.datalen = res - hdrlen;
873 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
874 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
875 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
876 rtp->f.samples = ast_codec_get_samples(&rtp->f);
877 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
878 ast_frame_byteswap_be(&rtp->f);
879 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
880 } else {
881 /* Video -- samples is # of samples vs. 90000 */
882 if (!rtp->lastividtimestamp)
883 rtp->lastividtimestamp = timestamp;
884 rtp->f.samples = timestamp - rtp->lastividtimestamp;
885 rtp->lastividtimestamp = timestamp;
886 rtp->f.delivery.tv_sec = 0;
887 rtp->f.delivery.tv_usec = 0;
888 if (mark)
889 rtp->f.subclass |= 0x1;
892 rtp->f.src = "RTP";
893 return &rtp->f;
896 /* The following array defines the MIME Media type (and subtype) for each
897 of our codecs, or RTP-specific data type. */
898 static struct {
899 struct rtpPayloadType payloadType;
900 char* type;
901 char* subtype;
902 } mimeTypes[] = {
903 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
904 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
905 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
906 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
907 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
908 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
909 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
910 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
911 {{1, AST_FORMAT_G729A}, "audio", "G729"},
912 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
913 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
914 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
915 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
916 {{0, AST_RTP_CN}, "audio", "CN"},
917 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
918 {{1, AST_FORMAT_PNG}, "video", "PNG"},
919 {{1, AST_FORMAT_H261}, "video", "H261"},
920 {{1, AST_FORMAT_H263}, "video", "H263"},
921 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
922 {{1, AST_FORMAT_H264}, "video", "H264"},
925 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
926 also, our own choices for dynamic payload types. This is our master
927 table for transmission */
928 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
929 [0] = {1, AST_FORMAT_ULAW},
930 #ifdef USE_DEPRECATED_G726
931 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
932 #endif
933 [3] = {1, AST_FORMAT_GSM},
934 [4] = {1, AST_FORMAT_G723_1},
935 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
936 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
937 [7] = {1, AST_FORMAT_LPC10},
938 [8] = {1, AST_FORMAT_ALAW},
939 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
940 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
941 [13] = {0, AST_RTP_CN},
942 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
943 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
944 [18] = {1, AST_FORMAT_G729A},
945 [19] = {0, AST_RTP_CN}, /* Also used for CN */
946 [26] = {1, AST_FORMAT_JPEG},
947 [31] = {1, AST_FORMAT_H261},
948 [34] = {1, AST_FORMAT_H263},
949 [103] = {1, AST_FORMAT_H263_PLUS},
950 [97] = {1, AST_FORMAT_ILBC},
951 [99] = {1, AST_FORMAT_H264},
952 [101] = {0, AST_RTP_DTMF},
953 [110] = {1, AST_FORMAT_SPEEX},
954 [111] = {1, AST_FORMAT_G726},
955 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
958 void ast_rtp_pt_clear(struct ast_rtp* rtp)
960 int i;
961 if (!rtp)
962 return;
964 for (i = 0; i < MAX_RTP_PT; ++i) {
965 rtp->current_RTP_PT[i].isAstFormat = 0;
966 rtp->current_RTP_PT[i].code = 0;
969 rtp->rtp_lookup_code_cache_isAstFormat = 0;
970 rtp->rtp_lookup_code_cache_code = 0;
971 rtp->rtp_lookup_code_cache_result = 0;
974 void ast_rtp_pt_default(struct ast_rtp* rtp)
976 int i;
978 /* Initialize to default payload types */
979 for (i = 0; i < MAX_RTP_PT; ++i) {
980 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
981 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
984 rtp->rtp_lookup_code_cache_isAstFormat = 0;
985 rtp->rtp_lookup_code_cache_code = 0;
986 rtp->rtp_lookup_code_cache_result = 0;
989 static void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
991 int i;
992 /* Copy payload types from source to destination */
993 for (i=0; i < MAX_RTP_PT; ++i) {
994 dest->current_RTP_PT[i].isAstFormat =
995 src->current_RTP_PT[i].isAstFormat;
996 dest->current_RTP_PT[i].code =
997 src->current_RTP_PT[i].code;
999 dest->rtp_lookup_code_cache_isAstFormat = 0;
1000 dest->rtp_lookup_code_cache_code = 0;
1001 dest->rtp_lookup_code_cache_result = 0;
1004 /*! \brief Get channel driver interface structure */
1005 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1007 struct ast_rtp_protocol *cur = NULL;
1009 AST_LIST_LOCK(&protos);
1010 AST_LIST_TRAVERSE(&protos, cur, list) {
1011 if (cur->type == chan->tech->type)
1012 break;
1014 AST_LIST_UNLOCK(&protos);
1016 return cur;
1019 int ast_rtp_early_media(struct ast_channel *dest, struct ast_channel *src)
1021 struct ast_rtp *destp, *srcp=NULL; /* Audio RTP Channels */
1022 struct ast_rtp *vdestp, *vsrcp=NULL; /* Video RTP channels */
1023 struct ast_rtp_protocol *destpr, *srcpr=NULL;
1024 int srccodec;
1025 /* Lock channels */
1026 ast_channel_lock(dest);
1027 if (src) {
1028 while(ast_channel_trylock(src)) {
1029 ast_channel_unlock(dest);
1030 usleep(1);
1031 ast_channel_lock(dest);
1035 /* Find channel driver interfaces */
1036 destpr = get_proto(dest);
1037 if (src)
1038 srcpr = get_proto(src);
1039 if (!destpr) {
1040 if (option_debug)
1041 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1042 ast_channel_unlock(dest);
1043 if (src)
1044 ast_channel_unlock(src);
1045 return 0;
1047 if (!srcpr) {
1048 if (option_debug)
1049 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src ? src->name : "<unspecified>");
1050 ast_channel_unlock(dest);
1051 if (src)
1052 ast_channel_unlock(src);
1053 return 0;
1056 /* Get audio and video interface (if native bridge is possible) */
1057 destp = destpr->get_rtp_info(dest);
1058 vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
1059 if (srcpr) {
1060 srcp = srcpr->get_rtp_info(src);
1061 vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
1064 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1065 if (!destp) {
1066 /* Somebody doesn't want to play... */
1067 ast_channel_unlock(dest);
1068 if (src)
1069 ast_channel_unlock(src);
1070 return 0;
1072 if (srcpr && srcpr->get_codec)
1073 srccodec = srcpr->get_codec(src);
1074 else
1075 srccodec = 0;
1076 /* Consider empty media as non-existant */
1077 if (srcp && !srcp->them.sin_addr.s_addr)
1078 srcp = NULL;
1079 /* Bridge early media */
1080 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, srcp ? ast_test_flag(srcp, FLAG_NAT_ACTIVE) : 0))
1081 ast_log(LOG_WARNING, "Channel '%s' failed to send early media to '%s'\n", dest->name, src ? src->name : "<unspecified>");
1082 ast_channel_unlock(dest);
1083 if (src)
1084 ast_channel_unlock(src);
1085 if (option_debug)
1086 ast_log(LOG_DEBUG, "Setting early media SDP of '%s' with that of '%s'\n", dest->name, src ? src->name : "<unspecified>");
1087 return 1;
1090 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1092 struct ast_rtp *destp, *srcp; /* Audio RTP Channels */
1093 struct ast_rtp *vdestp, *vsrcp; /* Video RTP channels */
1094 struct ast_rtp_protocol *destpr, *srcpr;
1095 int srccodec;
1096 /* Lock channels */
1097 ast_channel_lock(dest);
1098 while(ast_channel_trylock(src)) {
1099 ast_channel_unlock(dest);
1100 usleep(1);
1101 ast_channel_lock(dest);
1104 /* Find channel driver interfaces */
1105 destpr = get_proto(dest);
1106 srcpr = get_proto(src);
1107 if (!destpr) {
1108 if (option_debug)
1109 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1110 ast_channel_unlock(dest);
1111 ast_channel_unlock(src);
1112 return 0;
1114 if (!srcpr) {
1115 if (option_debug)
1116 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
1117 ast_channel_unlock(dest);
1118 ast_channel_unlock(src);
1119 return 0;
1122 /* Get audio and video interface (if native bridge is possible) */
1123 destp = destpr->get_rtp_info(dest);
1124 vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
1125 srcp = srcpr->get_rtp_info(src);
1126 vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
1128 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1129 if (!destp || !srcp) {
1130 /* Somebody doesn't want to play... */
1131 ast_channel_unlock(dest);
1132 ast_channel_unlock(src);
1133 return 0;
1135 ast_rtp_pt_copy(destp, srcp);
1136 if (vdestp && vsrcp)
1137 ast_rtp_pt_copy(vdestp, vsrcp);
1138 if (srcpr->get_codec)
1139 srccodec = srcpr->get_codec(src);
1140 else
1141 srccodec = 0;
1142 if (media) {
1143 /* Bridge early media */
1144 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1145 ast_log(LOG_WARNING, "Channel '%s' failed to send early media to '%s'\n", dest->name, src->name);
1147 ast_channel_unlock(dest);
1148 ast_channel_unlock(src);
1149 if (option_debug)
1150 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1151 return 1;
1154 /*! \brief Make a note of a RTP paymoad type that was seen in a SDP "m=" line.
1155 * By default, use the well-known value for this type (although it may
1156 * still be set to a different value by a subsequent "a=rtpmap:" line)
1158 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1160 if (pt < 0 || pt > MAX_RTP_PT)
1161 return; /* bogus payload type */
1163 if (static_RTP_PT[pt].code != 0) {
1164 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1168 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1169 a SDP "a=rtpmap:" line. */
1170 void ast_rtp_set_rtpmap_type(struct ast_rtp* rtp, int pt,
1171 char* mimeType, char* mimeSubtype)
1173 int i;
1175 if (pt < 0 || pt > MAX_RTP_PT)
1176 return; /* bogus payload type */
1178 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
1179 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1180 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1181 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1182 return;
1187 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
1188 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1189 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1190 int* astFormats, int* nonAstFormats) {
1191 int pt;
1193 *astFormats = *nonAstFormats = 0;
1194 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1195 if (rtp->current_RTP_PT[pt].isAstFormat) {
1196 *astFormats |= rtp->current_RTP_PT[pt].code;
1197 } else {
1198 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
1203 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
1205 struct rtpPayloadType result;
1207 result.isAstFormat = result.code = 0;
1208 if (pt < 0 || pt > MAX_RTP_PT)
1209 return result; /* bogus payload type */
1211 /* Start with the negotiated codecs */
1212 result = rtp->current_RTP_PT[pt];
1214 /* If it doesn't exist, check our static RTP type list, just in case */
1215 if (!result.code)
1216 result = static_RTP_PT[pt];
1217 return result;
1220 /*! \brief Looks up an RTP code out of our *static* outbound list */
1221 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
1223 int pt;
1225 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
1226 code == rtp->rtp_lookup_code_cache_code) {
1228 /* Use our cached mapping, to avoid the overhead of the loop below */
1229 return rtp->rtp_lookup_code_cache_result;
1232 /* Check the dynamic list first */
1233 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1234 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
1235 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1236 rtp->rtp_lookup_code_cache_code = code;
1237 rtp->rtp_lookup_code_cache_result = pt;
1238 return pt;
1242 /* Then the static list */
1243 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1244 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
1245 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1246 rtp->rtp_lookup_code_cache_code = code;
1247 rtp->rtp_lookup_code_cache_result = pt;
1248 return pt;
1251 return -1;
1254 char* ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code)
1257 int i;
1259 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
1260 if (mimeTypes[i].payloadType.code == code && mimeTypes[i].payloadType.isAstFormat == isAstFormat)
1261 return mimeTypes[i].subtype;
1263 return "";
1266 char *ast_rtp_lookup_mime_multiple(char *buf, int size, const int capability, const int isAstFormat)
1268 int format;
1269 unsigned len;
1270 char *end = buf;
1271 char *start = buf;
1273 if (!buf || !size)
1274 return NULL;
1276 snprintf(end, size, "0x%x (", capability);
1278 len = strlen(end);
1279 end += len;
1280 size -= len;
1281 start = end;
1283 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
1284 if (capability & format) {
1285 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format);
1286 snprintf(end, size, "%s|", name);
1287 len = strlen(end);
1288 end += len;
1289 size -= len;
1293 if (start == end)
1294 snprintf(start, size, "nothing)");
1295 else if (size > 1)
1296 *(end -1) = ')';
1298 return buf;
1301 static int rtp_socket(void)
1303 int s;
1304 long flags;
1305 s = socket(AF_INET, SOCK_DGRAM, 0);
1306 if (s > -1) {
1307 flags = fcntl(s, F_GETFL);
1308 fcntl(s, F_SETFL, flags | O_NONBLOCK);
1309 #ifdef SO_NO_CHECK
1310 if (nochecksums)
1311 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
1312 #endif
1314 return s;
1318 * \brief Initialize a new RTCP session.
1320 * \returns The newly initialized RTCP session.
1322 static struct ast_rtcp *ast_rtcp_new(void)
1324 struct ast_rtcp *rtcp;
1326 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
1327 return NULL;
1328 rtcp->s = rtp_socket();
1329 rtcp->us.sin_family = AF_INET;
1330 if (rtcp->s < 0) {
1331 free(rtcp);
1332 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
1333 return NULL;
1336 return rtcp;
1339 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
1341 struct ast_rtp *rtp;
1342 int x;
1343 int first;
1344 int startplace;
1346 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
1347 return NULL;
1348 rtp->them.sin_family = AF_INET;
1349 rtp->us.sin_family = AF_INET;
1350 rtp->s = rtp_socket();
1351 rtp->ssrc = ast_random();
1352 rtp->seqno = ast_random() & 0xffff;
1353 ast_set_flag(rtp, FLAG_HAS_DTMF);
1354 if (rtp->s < 0) {
1355 free(rtp);
1356 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1357 return NULL;
1359 if (sched && rtcpenable) {
1360 rtp->sched = sched;
1361 rtp->rtcp = ast_rtcp_new();
1364 /* Select a random port number in the range of possible RTP */
1365 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
1366 x = x & ~1;
1367 /* Save it for future references. */
1368 startplace = x;
1369 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1370 for (;;) {
1371 /* Must be an even port number by RTP spec */
1372 rtp->us.sin_port = htons(x);
1373 rtp->us.sin_addr = addr;
1374 /* If there's rtcp, initialize it as well. */
1375 if (rtp->rtcp)
1376 rtp->rtcp->us.sin_port = htons(x + 1);
1377 /* Try to bind it/them. */
1378 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1379 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1380 break;
1381 if (!first) {
1382 /* Primary bind succeeded! Gotta recreate it */
1383 close(rtp->s);
1384 rtp->s = rtp_socket();
1386 if (errno != EADDRINUSE) {
1387 /* We got an error that wasn't expected, abort! */
1388 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1389 close(rtp->s);
1390 if (rtp->rtcp) {
1391 close(rtp->rtcp->s);
1392 free(rtp->rtcp);
1394 free(rtp);
1395 return NULL;
1397 /* The port was used, increment it (by two). */
1398 x += 2;
1399 /* Did we go over the limit ? */
1400 if (x > rtpend)
1401 /* then, start from the begingig. */
1402 x = (rtpstart + 1) & ~1;
1403 /* Check if we reached the place were we started. */
1404 if (x == startplace) {
1405 /* If so, there's no ports available. */
1406 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1407 close(rtp->s);
1408 if (rtp->rtcp) {
1409 close(rtp->rtcp->s);
1410 free(rtp->rtcp);
1412 free(rtp);
1413 return NULL;
1416 if (io && sched && callbackmode) {
1417 /* Operate this one in a callback mode */
1418 rtp->sched = sched;
1419 rtp->io = io;
1420 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1422 ast_rtp_pt_default(rtp);
1423 return rtp;
1426 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1428 struct in_addr ia;
1430 memset(&ia, 0, sizeof(ia));
1431 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1434 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1436 int res;
1438 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1439 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1440 return res;
1443 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1445 rtp->them.sin_port = them->sin_port;
1446 rtp->them.sin_addr = them->sin_addr;
1447 if (rtp->rtcp) {
1448 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1449 rtp->rtcp->them.sin_addr = them->sin_addr;
1451 rtp->rxseqno = 0;
1454 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1456 if ((them->sin_family != AF_INET) ||
1457 (them->sin_port != rtp->them.sin_port) ||
1458 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
1459 them->sin_family = AF_INET;
1460 them->sin_port = rtp->them.sin_port;
1461 them->sin_addr = rtp->them.sin_addr;
1462 return 1;
1464 return 0;
1467 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1469 *us = rtp->us;
1472 void ast_rtp_stop(struct ast_rtp *rtp)
1474 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1475 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1476 if (rtp->rtcp) {
1477 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1478 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1482 void ast_rtp_reset(struct ast_rtp *rtp)
1484 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1485 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1486 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1487 rtp->lastts = 0;
1488 rtp->lastdigitts = 0;
1489 rtp->lastrxts = 0;
1490 rtp->lastividtimestamp = 0;
1491 rtp->lastovidtimestamp = 0;
1492 rtp->lasteventseqn = 0;
1493 rtp->lasteventendseqn = 0;
1494 rtp->lasttxformat = 0;
1495 rtp->lastrxformat = 0;
1496 rtp->dtmfcount = 0;
1497 rtp->dtmfduration = 0;
1498 rtp->seqno = 0;
1499 rtp->rxseqno = 0;
1502 void ast_rtp_destroy(struct ast_rtp *rtp)
1504 if (rtp->smoother)
1505 ast_smoother_free(rtp->smoother);
1506 if (rtp->ioid)
1507 ast_io_remove(rtp->io, rtp->ioid);
1508 if (rtp->s > -1)
1509 close(rtp->s);
1510 if (rtp->rtcp) {
1511 close(rtp->rtcp->s);
1512 free(rtp->rtcp);
1514 free(rtp);
1517 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1519 struct timeval t;
1520 long ms;
1521 if (ast_tvzero(rtp->txcore)) {
1522 rtp->txcore = ast_tvnow();
1523 /* Round to 20ms for nice, pretty timestamps */
1524 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1526 /* Use previous txcore if available */
1527 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
1528 ms = ast_tvdiff_ms(t, rtp->txcore);
1529 if (ms < 0)
1530 ms = 0;
1531 /* Use what we just got for next time */
1532 rtp->txcore = t;
1533 return (unsigned int) ms;
1536 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
1538 unsigned int *rtpheader;
1539 int hdrlen = 12;
1540 int res;
1541 int x;
1542 int payload;
1543 char data[256];
1544 char iabuf[INET_ADDRSTRLEN];
1546 if ((digit <= '9') && (digit >= '0'))
1547 digit -= '0';
1548 else if (digit == '*')
1549 digit = 10;
1550 else if (digit == '#')
1551 digit = 11;
1552 else if ((digit >= 'A') && (digit <= 'D'))
1553 digit = digit - 'A' + 12;
1554 else if ((digit >= 'a') && (digit <= 'd'))
1555 digit = digit - 'a' + 12;
1556 else {
1557 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
1558 return -1;
1560 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
1562 /* If we have no peer, return immediately */
1563 if (!rtp->them.sin_addr.s_addr)
1564 return 0;
1566 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1568 /* Get a pointer to the header */
1569 rtpheader = (unsigned int *)data;
1570 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
1571 rtpheader[1] = htonl(rtp->lastdigitts);
1572 rtpheader[2] = htonl(rtp->ssrc);
1573 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
1574 for (x = 0; x < 6; x++) {
1575 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1576 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
1577 if (res < 0)
1578 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
1579 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1580 ntohs(rtp->them.sin_port), strerror(errno));
1581 if (rtp_debug_test_addr(&rtp->them))
1582 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %u, ts %u, len %u)\n",
1583 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1584 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
1586 /* Sequence number of last two end packets does not get incremented */
1587 if (x < 3)
1588 rtp->seqno++;
1589 /* Clear marker bit and set seqno */
1590 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
1591 /* For the last three packets, set the duration and the end bit */
1592 if (x == 2) {
1593 #if 0
1594 /* No, this is wrong... Do not increment lastdigitts, that's not according
1595 to the RFC, as best we can determine */
1596 rtp->lastdigitts++; /* or else the SPA3000 will click instead of beeping... */
1597 rtpheader[1] = htonl(rtp->lastdigitts);
1598 #endif
1599 /* Make duration 800 (100ms) */
1600 rtpheader[3] |= htonl((800));
1601 /* Set the End bit */
1602 rtpheader[3] |= htonl((1 << 23));
1605 /* Increment the digit timestamp by 120ms, to ensure that digits
1606 sent sequentially with no intervening non-digit packets do not
1607 get sent with the same timestamp, and that sequential digits
1608 have some 'dead air' in between them
1610 rtp->lastdigitts += 960;
1611 /* Increment the sequence number to reflect the last packet
1612 that was sent
1614 rtp->seqno++;
1615 return 0;
1618 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
1620 unsigned int *rtpheader;
1621 int hdrlen = 12;
1622 int res;
1623 int payload;
1624 char data[256];
1625 char iabuf[INET_ADDRSTRLEN];
1626 level = 127 - (level & 0x7f);
1627 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
1629 /* If we have no peer, return immediately */
1630 if (!rtp->them.sin_addr.s_addr)
1631 return 0;
1633 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1635 /* Get a pointer to the header */
1636 rtpheader = (unsigned int *)data;
1637 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
1638 rtpheader[1] = htonl(rtp->lastts);
1639 rtpheader[2] = htonl(rtp->ssrc);
1640 data[12] = level;
1641 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1642 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1643 if (res <0)
1644 ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s:%d: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
1645 if(rtp_debug_test_addr(&rtp->them))
1646 ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %d, len %d)\n"
1647 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
1650 return 0;
1653 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
1655 unsigned char *rtpheader;
1656 char iabuf[INET_ADDRSTRLEN];
1657 int hdrlen = 12;
1658 int res;
1659 unsigned int ms;
1660 int pred;
1661 int mark = 0;
1663 ms = calc_txstamp(rtp, &f->delivery);
1664 /* Default prediction */
1665 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
1666 pred = rtp->lastts + f->samples;
1668 /* Re-calculate last TS */
1669 rtp->lastts = rtp->lastts + ms * 8;
1670 if (ast_tvzero(f->delivery)) {
1671 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
1672 and if so, go with our prediction */
1673 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
1674 rtp->lastts = pred;
1675 else {
1676 if (option_debug > 2)
1677 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
1678 mark = 1;
1681 } else {
1682 mark = f->subclass & 0x1;
1683 pred = rtp->lastovidtimestamp + f->samples;
1684 /* Re-calculate last TS */
1685 rtp->lastts = rtp->lastts + ms * 90;
1686 /* If it's close to our prediction, go for it */
1687 if (ast_tvzero(f->delivery)) {
1688 if (abs(rtp->lastts - pred) < 7200) {
1689 rtp->lastts = pred;
1690 rtp->lastovidtimestamp += f->samples;
1691 } else {
1692 if (option_debug > 2)
1693 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);
1694 rtp->lastovidtimestamp = rtp->lastts;
1698 /* If the timestamp for non-digit packets has moved beyond the timestamp
1699 for digits, update the digit timestamp.
1701 if (rtp->lastts > rtp->lastdigitts)
1702 rtp->lastdigitts = rtp->lastts;
1704 /* Get a pointer to the header */
1705 rtpheader = (unsigned char *)(f->data - hdrlen);
1707 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
1708 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
1709 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
1711 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1712 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1713 if (res <0) {
1714 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1715 ast_log(LOG_DEBUG, "RTP Transmission error of packet %d to %s:%d: %s\n", rtp->seqno, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
1716 } else if ((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) {
1717 /* Only give this error message once if we are not RTP debugging */
1718 if (option_debug || rtpdebug)
1719 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(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port));
1720 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
1724 if(rtp_debug_test_addr(&rtp->them))
1725 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %u, ts %u, len %u)\n"
1726 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
1729 rtp->seqno++;
1731 return 0;
1734 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
1736 struct ast_frame *f;
1737 int codec;
1738 int hdrlen = 12;
1739 int subclass;
1742 /* If we have no peer, return immediately */
1743 if (!rtp->them.sin_addr.s_addr)
1744 return 0;
1746 /* If there is no data length, return immediately */
1747 if (!_f->datalen)
1748 return 0;
1750 /* Make sure we have enough space for RTP header */
1751 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
1752 ast_log(LOG_WARNING, "RTP can only send voice\n");
1753 return -1;
1756 subclass = _f->subclass;
1757 if (_f->frametype == AST_FRAME_VIDEO)
1758 subclass &= ~0x1;
1760 codec = ast_rtp_lookup_code(rtp, 1, subclass);
1761 if (codec < 0) {
1762 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
1763 return -1;
1766 if (rtp->lasttxformat != subclass) {
1767 /* New format, reset the smoother */
1768 if (option_debug)
1769 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
1770 rtp->lasttxformat = subclass;
1771 if (rtp->smoother)
1772 ast_smoother_free(rtp->smoother);
1773 rtp->smoother = NULL;
1777 switch(subclass) {
1778 case AST_FORMAT_SLINEAR:
1779 if (!rtp->smoother) {
1780 rtp->smoother = ast_smoother_new(320);
1782 if (!rtp->smoother) {
1783 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1784 return -1;
1786 ast_smoother_feed_be(rtp->smoother, _f);
1788 while((f = ast_smoother_read(rtp->smoother)))
1789 ast_rtp_raw_write(rtp, f, codec);
1790 break;
1791 case AST_FORMAT_ULAW:
1792 case AST_FORMAT_ALAW:
1793 if (!rtp->smoother) {
1794 rtp->smoother = ast_smoother_new(160);
1796 if (!rtp->smoother) {
1797 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1798 return -1;
1800 ast_smoother_feed(rtp->smoother, _f);
1802 while((f = ast_smoother_read(rtp->smoother)))
1803 ast_rtp_raw_write(rtp, f, codec);
1804 break;
1805 case AST_FORMAT_ADPCM:
1806 case AST_FORMAT_G726:
1807 if (!rtp->smoother) {
1808 rtp->smoother = ast_smoother_new(80);
1810 if (!rtp->smoother) {
1811 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1812 return -1;
1814 ast_smoother_feed(rtp->smoother, _f);
1816 while((f = ast_smoother_read(rtp->smoother)))
1817 ast_rtp_raw_write(rtp, f, codec);
1818 break;
1819 case AST_FORMAT_G729A:
1820 if (!rtp->smoother) {
1821 rtp->smoother = ast_smoother_new(20);
1822 if (rtp->smoother)
1823 ast_smoother_set_flags(rtp->smoother, AST_SMOOTHER_FLAG_G729);
1825 if (!rtp->smoother) {
1826 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
1827 return -1;
1829 ast_smoother_feed(rtp->smoother, _f);
1831 while((f = ast_smoother_read(rtp->smoother)))
1832 ast_rtp_raw_write(rtp, f, codec);
1833 break;
1834 case AST_FORMAT_GSM:
1835 if (!rtp->smoother) {
1836 rtp->smoother = ast_smoother_new(33);
1838 if (!rtp->smoother) {
1839 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
1840 return -1;
1842 ast_smoother_feed(rtp->smoother, _f);
1843 while((f = ast_smoother_read(rtp->smoother)))
1844 ast_rtp_raw_write(rtp, f, codec);
1845 break;
1846 case AST_FORMAT_ILBC:
1847 if (!rtp->smoother) {
1848 rtp->smoother = ast_smoother_new(50);
1850 if (!rtp->smoother) {
1851 ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
1852 return -1;
1854 ast_smoother_feed(rtp->smoother, _f);
1855 while((f = ast_smoother_read(rtp->smoother)))
1856 ast_rtp_raw_write(rtp, f, codec);
1857 break;
1858 default:
1859 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
1860 /* fall through to... */
1861 case AST_FORMAT_H261:
1862 case AST_FORMAT_H263:
1863 case AST_FORMAT_H263_PLUS:
1864 case AST_FORMAT_H264:
1865 case AST_FORMAT_G723_1:
1866 case AST_FORMAT_LPC10:
1867 case AST_FORMAT_SPEEX:
1868 /* Don't buffer outgoing frames; send them one-per-packet: */
1869 if (_f->offset < hdrlen) {
1870 f = ast_frdup(_f);
1871 } else {
1872 f = _f;
1874 ast_rtp_raw_write(rtp, f, codec);
1877 return 0;
1880 /*! \brief Unregister interface to channel driver */
1881 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
1883 AST_LIST_LOCK(&protos);
1884 AST_LIST_REMOVE(&protos, proto, list);
1885 AST_LIST_UNLOCK(&protos);
1888 /*! \brief Register interface to channel driver */
1889 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
1891 struct ast_rtp_protocol *cur;
1893 AST_LIST_LOCK(&protos);
1894 AST_LIST_TRAVERSE(&protos, cur, list) {
1895 if (!strcmp(cur->type, proto->type)) {
1896 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1897 AST_LIST_UNLOCK(&protos);
1898 return -1;
1901 AST_LIST_INSERT_HEAD(&protos, proto, list);
1902 AST_LIST_UNLOCK(&protos);
1904 return 0;
1907 /*! \brief Bridge calls. If possible and allowed, initiate
1908 re-invite so the peers exchange media directly outside
1909 of Asterisk. */
1910 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)
1912 struct ast_frame *f;
1913 struct ast_channel *who, *other, *cs[3];
1914 struct ast_rtp *p0, *p1; /* Audio RTP Channels */
1915 struct ast_rtp *vp0, *vp1; /* Video RTP channels */
1916 struct ast_rtp_protocol *pr0, *pr1;
1917 struct sockaddr_in ac0, ac1;
1918 struct sockaddr_in vac0, vac1;
1919 struct sockaddr_in t0, t1;
1920 struct sockaddr_in vt0, vt1;
1921 char iabuf[INET_ADDRSTRLEN];
1923 void *pvt0, *pvt1;
1924 int codec0,codec1, oldcodec0, oldcodec1;
1926 memset(&vt0, 0, sizeof(vt0));
1927 memset(&vt1, 0, sizeof(vt1));
1928 memset(&vac0, 0, sizeof(vac0));
1929 memset(&vac1, 0, sizeof(vac1));
1931 /* Lock channels */
1932 ast_channel_lock(c0);
1933 while(ast_channel_trylock(c1)) {
1934 ast_channel_unlock(c0);
1935 usleep(1);
1936 ast_channel_lock(c0);
1939 /* Find channel driver interfaces */
1940 pr0 = get_proto(c0);
1941 pr1 = get_proto(c1);
1942 if (!pr0) {
1943 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
1944 ast_channel_unlock(c0);
1945 ast_channel_unlock(c1);
1946 return AST_BRIDGE_FAILED;
1948 if (!pr1) {
1949 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1950 ast_channel_unlock(c0);
1951 ast_channel_unlock(c1);
1952 return AST_BRIDGE_FAILED;
1955 /* Get channel specific interface structures */
1956 pvt0 = c0->tech_pvt;
1957 pvt1 = c1->tech_pvt;
1959 /* Get audio and video interface (if native bridge is possible) */
1960 p0 = pr0->get_rtp_info(c0);
1961 vp0 = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0) : NULL;
1962 p1 = pr1->get_rtp_info(c1);
1963 vp1 = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1) : NULL;
1965 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1966 if (!p0 || !p1) {
1967 /* Somebody doesn't want to play... */
1968 ast_channel_unlock(c0);
1969 ast_channel_unlock(c1);
1970 return AST_BRIDGE_FAILED_NOWARN;
1973 if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1974 /* can't bridge, we are carrying DTMF for this channel and the bridge
1975 needs it
1977 ast_channel_unlock(c0);
1978 ast_channel_unlock(c1);
1979 return AST_BRIDGE_FAILED_NOWARN;
1982 if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
1983 /* can't bridge, we are carrying DTMF for this channel and the bridge
1984 needs it
1986 ast_channel_unlock(c0);
1987 ast_channel_unlock(c1);
1988 return AST_BRIDGE_FAILED_NOWARN;
1991 /* Get codecs from both sides */
1992 codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
1993 codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
1994 if (pr0->get_codec && pr1->get_codec) {
1995 /* Hey, we can't do reinvite if both parties speak different codecs */
1996 if (!(codec0 & codec1)) {
1997 if (option_debug)
1998 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
1999 ast_channel_unlock(c0);
2000 ast_channel_unlock(c1);
2001 return AST_BRIDGE_FAILED_NOWARN;
2005 if (option_verbose > 2)
2006 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2008 /* Ok, we should be able to redirect the media. Start with one channel */
2009 if (pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
2010 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
2011 else {
2012 /* Store RTP peer */
2013 ast_rtp_get_peer(p1, &ac1);
2014 if (vp1)
2015 ast_rtp_get_peer(vp1, &vac1);
2017 /* Then test the other channel */
2018 if (pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
2019 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
2020 else {
2021 /* Store RTP peer */
2022 ast_rtp_get_peer(p0, &ac0);
2023 if (vp0)
2024 ast_rtp_get_peer(vp0, &vac0);
2026 ast_channel_unlock(c0);
2027 ast_channel_unlock(c1);
2028 /* External RTP Bridge up, now loop and see if something happes that force us to take the
2029 media back to Asterisk */
2030 cs[0] = c0;
2031 cs[1] = c1;
2032 cs[2] = NULL;
2033 oldcodec0 = codec0;
2034 oldcodec1 = codec1;
2035 for (;;) {
2036 /* Check if something changed... */
2037 if ((c0->tech_pvt != pvt0) ||
2038 (c1->tech_pvt != pvt1) ||
2039 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
2040 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
2041 if (c0->tech_pvt == pvt0) {
2042 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2043 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2045 if (c1->tech_pvt == pvt1) {
2046 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2047 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2049 return AST_BRIDGE_RETRY;
2051 /* Now check if they have changed address */
2052 ast_rtp_get_peer(p1, &t1);
2053 ast_rtp_get_peer(p0, &t0);
2054 if (pr0->get_codec)
2055 codec0 = pr0->get_codec(c0);
2056 if (pr1->get_codec)
2057 codec1 = pr1->get_codec(c1);
2058 if (vp1)
2059 ast_rtp_get_peer(vp1, &vt1);
2060 if (vp0)
2061 ast_rtp_get_peer(vp0, &vt0);
2062 if (inaddrcmp(&t1, &ac1) || (vp1 && inaddrcmp(&vt1, &vac1)) || (codec1 != oldcodec1)) {
2063 if (option_debug > 1) {
2064 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2065 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t1.sin_addr), ntohs(t1.sin_port), codec1);
2066 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
2067 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vt1.sin_addr), ntohs(vt1.sin_port), codec1);
2068 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2069 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
2070 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2071 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
2073 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)))
2074 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
2075 memcpy(&ac1, &t1, sizeof(ac1));
2076 memcpy(&vac1, &vt1, sizeof(vac1));
2077 oldcodec1 = codec1;
2079 if (inaddrcmp(&t0, &ac0) || (vp0 && inaddrcmp(&vt0, &vac0))) {
2080 if (option_debug) {
2081 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
2082 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t0.sin_addr), ntohs(t0.sin_port), codec0);
2083 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
2084 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
2086 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)))
2087 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
2088 memcpy(&ac0, &t0, sizeof(ac0));
2089 memcpy(&vac0, &vt0, sizeof(vac0));
2090 oldcodec0 = codec0;
2092 who = ast_waitfor_n(cs, 2, &timeoutms);
2093 if (!who) {
2094 if (!timeoutms)
2095 return AST_BRIDGE_RETRY;
2096 if (option_debug)
2097 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2098 /* check for hangup / whentohangup */
2099 if (ast_check_hangup(c0) || ast_check_hangup(c1))
2100 break;
2101 continue;
2103 f = ast_read(who);
2104 other = (who == c0) ? c1 : c0; /* the other channel */
2105 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
2106 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
2107 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
2108 /* breaking out of the bridge. */
2109 *fo = f;
2110 *rc = who;
2111 if (option_debug)
2112 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
2113 if ((c0->tech_pvt == pvt0)) {
2114 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
2115 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2117 if ((c1->tech_pvt == pvt1)) {
2118 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
2119 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2121 return AST_BRIDGE_COMPLETE;
2122 } else if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2123 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
2124 (f->subclass == AST_CONTROL_VIDUPDATE)) {
2125 ast_indicate(other, f->subclass);
2126 ast_frfree(f);
2127 } else {
2128 *fo = f;
2129 *rc = who;
2130 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2131 return AST_BRIDGE_COMPLETE;
2133 } else {
2134 if ((f->frametype == AST_FRAME_DTMF) ||
2135 (f->frametype == AST_FRAME_VOICE) ||
2136 (f->frametype == AST_FRAME_VIDEO)) {
2137 /* Forward voice or DTMF frames if they happen upon us */
2138 ast_write(other, f);
2140 ast_frfree(f);
2142 /* Swap priority not that it's a big deal at this point */
2143 cs[2] = cs[0];
2144 cs[0] = cs[1];
2145 cs[1] = cs[2];
2148 return AST_BRIDGE_FAILED;
2151 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
2153 struct hostent *hp;
2154 struct ast_hostent ahp;
2155 char iabuf[INET_ADDRSTRLEN];
2156 int port = 0;
2157 char *p, *arg;
2159 if (argc != 4)
2160 return RESULT_SHOWUSAGE;
2161 arg = argv[3];
2162 p = strstr(arg, ":");
2163 if (p) {
2164 *p = '\0';
2165 p++;
2166 port = atoi(p);
2168 hp = ast_gethostbyname(arg, &ahp);
2169 if (hp == NULL)
2170 return RESULT_SHOWUSAGE;
2171 rtpdebugaddr.sin_family = AF_INET;
2172 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
2173 rtpdebugaddr.sin_port = htons(port);
2174 if (port == 0)
2175 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr));
2176 else
2177 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr), port);
2178 rtpdebug = 1;
2179 return RESULT_SUCCESS;
2182 static int rtp_do_debug(int fd, int argc, char *argv[])
2184 if(argc != 2) {
2185 if(argc != 4)
2186 return RESULT_SHOWUSAGE;
2187 return rtp_do_debug_ip(fd, argc, argv);
2189 rtpdebug = 1;
2190 memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
2191 ast_cli(fd, "RTP Debugging Enabled\n");
2192 return RESULT_SUCCESS;
2195 static int rtp_no_debug(int fd, int argc, char *argv[])
2197 if(argc !=3)
2198 return RESULT_SHOWUSAGE;
2199 rtpdebug = 0;
2200 ast_cli(fd,"RTP Debugging Disabled\n");
2201 return RESULT_SUCCESS;
2204 static int stun_do_debug(int fd, int argc, char *argv[])
2206 if(argc != 2) {
2207 return RESULT_SHOWUSAGE;
2209 stundebug = 1;
2210 ast_cli(fd, "STUN Debugging Enabled\n");
2211 return RESULT_SUCCESS;
2214 static int stun_no_debug(int fd, int argc, char *argv[])
2216 if(argc !=3)
2217 return RESULT_SHOWUSAGE;
2218 stundebug = 0;
2219 ast_cli(fd,"STUN Debugging Disabled\n");
2220 return RESULT_SUCCESS;
2224 static char debug_usage[] =
2225 "Usage: rtp debug [ip host[:port]]\n"
2226 " Enable dumping of all RTP packets to and from host.\n";
2228 static char no_debug_usage[] =
2229 "Usage: rtp no debug\n"
2230 " Disable all RTP debugging\n";
2232 static char stun_debug_usage[] =
2233 "Usage: stun debug\n"
2234 " Enable STUN (Simple Traversal of UDP through NATs) debugging\n";
2236 static char stun_no_debug_usage[] =
2237 "Usage: stun no debug\n"
2238 " Disable STUN debugging\n";
2241 static struct ast_cli_entry cli_debug_ip =
2242 {{ "rtp", "debug", "ip", NULL } , rtp_do_debug, "Enable RTP debugging on IP", debug_usage };
2244 static struct ast_cli_entry cli_debug =
2245 {{ "rtp", "debug", NULL } , rtp_do_debug, "Enable RTP debugging", debug_usage };
2247 static struct ast_cli_entry cli_no_debug =
2248 {{ "rtp", "no", "debug", NULL } , rtp_no_debug, "Disable RTP debugging", no_debug_usage };
2250 static struct ast_cli_entry cli_stun_debug =
2251 {{ "stun", "debug", NULL } , stun_do_debug, "Enable STUN debugging", stun_debug_usage };
2253 static struct ast_cli_entry cli_stun_no_debug =
2254 {{ "stun", "no", "debug", NULL } , stun_no_debug, "Disable STUN debugging", stun_no_debug_usage };
2256 int ast_rtp_reload(void)
2258 struct ast_config *cfg;
2259 char *s;
2261 rtpstart = 5000;
2262 rtpend = 31000;
2263 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2264 cfg = ast_config_load("rtp.conf");
2265 if (cfg) {
2266 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
2267 rtpstart = atoi(s);
2268 if (rtpstart < 1024)
2269 rtpstart = 1024;
2270 if (rtpstart > 65535)
2271 rtpstart = 65535;
2273 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
2274 rtpend = atoi(s);
2275 if (rtpend < 1024)
2276 rtpend = 1024;
2277 if (rtpend > 65535)
2278 rtpend = 65535;
2280 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
2281 #ifdef SO_NO_CHECK
2282 if (ast_false(s))
2283 nochecksums = 1;
2284 else
2285 nochecksums = 0;
2286 #else
2287 if (ast_false(s))
2288 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
2289 #endif
2291 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
2292 dtmftimeout = atoi(s);
2293 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
2294 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
2295 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
2296 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2299 ast_config_destroy(cfg);
2301 if (rtpstart >= rtpend) {
2302 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
2303 rtpstart = 5000;
2304 rtpend = 31000;
2306 if (option_verbose > 1)
2307 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
2308 return 0;
2311 /*! \brief Initialize the RTP system in Asterisk */
2312 void ast_rtp_init(void)
2314 ast_cli_register(&cli_debug);
2315 ast_cli_register(&cli_debug_ip);
2316 ast_cli_register(&cli_no_debug);
2317 ast_cli_register(&cli_stun_debug);
2318 ast_cli_register(&cli_stun_no_debug);
2319 ast_rtp_reload();