2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2005, 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.
21 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
23 * RTP is deffined in RFC 3550.
33 #include <netinet/in.h>
35 #include <sys/socket.h>
36 #include <arpa/inet.h>
41 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43 #include "asterisk/rtp.h"
44 #include "asterisk/frame.h"
45 #include "asterisk/logger.h"
46 #include "asterisk/options.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/acl.h"
49 #include "asterisk/channel.h"
50 #include "asterisk/config.h"
51 #include "asterisk/lock.h"
52 #include "asterisk/utils.h"
53 #include "asterisk/cli.h"
54 #include "asterisk/unaligned.h"
55 #include "asterisk/utils.h"
57 #define MAX_TIMESTAMP_SKEW 640
61 #define DEFAULT_DTMF_TIMEOUT 3000 /* samples */
63 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
65 static int rtpstart = 0;
66 static int rtpend = 0;
67 static int rtpdebug = 0; /* Are we debugging? */
68 static struct sockaddr_in rtpdebugaddr; /* Debug packets to/from this host */
70 static int nochecksums = 0;
73 /* The value of each payload format mapping: */
74 struct rtpPayloadType {
75 int isAstFormat; /* whether the following code is an AST_FORMAT */
79 #define MAX_RTP_PT 256
81 #define FLAG_3389_WARNING (1 << 0)
82 #define FLAG_NAT_ACTIVE (3 << 1)
83 #define FLAG_NAT_INACTIVE (0 << 1)
84 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
90 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
91 /*! Synchronization source, RFC 3550, page 10. */
94 unsigned int lastdigitts;
95 unsigned int lastrxts;
96 unsigned int lastividtimestamp;
97 unsigned int lastovidtimestamp;
98 unsigned int lasteventseqn;
99 unsigned int lasteventendseqn;
103 unsigned int dtmfduration;
106 /*! Socket representation of the local endpoint. */
107 struct sockaddr_in us;
108 /*! Socket representation of the remote endpoint. */
109 struct sockaddr_in them;
110 struct timeval rxcore;
111 struct timeval txcore;
112 struct timeval dtmfmute;
113 struct ast_smoother *smoother;
115 /*! Sequence number, RFC 3550, page 13. */
116 unsigned short seqno;
117 unsigned short rxseqno;
118 struct sched_context *sched;
119 struct io_context *io;
121 ast_rtp_callback callback;
122 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
123 /*! a cache for the result of rtp_lookup_code(): */
124 int rtp_lookup_code_cache_isAstFormat;
125 int rtp_lookup_code_cache_code;
126 int rtp_lookup_code_cache_result;
127 int rtp_offered_from_local;
128 struct ast_rtcp *rtcp;
132 * \brief Structure defining an RTCP session.
134 * The concept "RTCP session" is not defined in RFC 3550, but since
135 * this structure is analogous to ast_rtp, which tracks a RTP session,
136 * it is logical to think of this as a RTCP session.
138 * RTCP packet is defined on page 9 of RFC 3550.
144 /*! Socket representation of the local endpoint. */
145 struct sockaddr_in us;
146 /*! Socket representation of the remote endpoint. */
147 struct sockaddr_in them;
150 static struct ast_rtp_protocol *protos = NULL;
152 int ast_rtp_fd(struct ast_rtp *rtp)
157 int ast_rtcp_fd(struct ast_rtp *rtp)
164 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
169 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
171 rtp->callback = callback;
174 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
179 static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
181 static struct ast_frame null_frame = { AST_FRAME_NULL, };
182 char iabuf[INET_ADDRSTRLEN];
184 if (ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
186 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
188 rtp->dtmfduration = 0;
192 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));
193 if (rtp->resp == 'X') {
194 rtp->f.frametype = AST_FRAME_CONTROL;
195 rtp->f.subclass = AST_CONTROL_FLASH;
197 rtp->f.frametype = AST_FRAME_DTMF;
198 rtp->f.subclass = rtp->resp;
205 rtp->dtmfduration = 0;
210 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
214 if (rtpdebugaddr.sin_addr.s_addr) {
215 if (((ntohs(rtpdebugaddr.sin_port) != 0)
216 && (rtpdebugaddr.sin_port != addr->sin_port))
217 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
223 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
227 struct ast_frame *f = NULL;
228 event = ntohl(*((unsigned int *)(data)));
231 printf("Cisco Digit: %08x (len = %d)\n", event, len);
235 } else if (event < 11) {
237 } else if (event < 12) {
239 } else if (event < 16) {
240 resp = 'A' + (event - 12);
241 } else if (event < 17) {
244 if (rtp->resp && (rtp->resp != resp)) {
248 rtp->dtmfcount = dtmftimeout;
253 * \brief Process RTP DTMF and events according to RFC 2833.
255 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
263 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
266 unsigned int event_end;
267 unsigned int duration;
269 struct ast_frame *f = NULL;
270 event = ntohl(*((unsigned int *)(data)));
272 event_end = ntohl(*((unsigned int *)(data)));
275 duration = ntohl(*((unsigned int *)(data)));
278 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
281 } else if (event < 11) {
283 } else if (event < 12) {
285 } else if (event < 16) {
286 resp = 'A' + (event - 12);
287 } else if (event < 17) { /* Event 16: Hook flash */
290 if (rtp->resp && (rtp->resp != resp)) {
292 } else if(event_end & 0x80) {
294 if(rtp->lasteventendseqn != seqno) {
296 rtp->lasteventendseqn = seqno;
302 } else if(rtp->dtmfduration && (duration < rtp->dtmfduration)) {
305 if (!(event_end & 0x80))
307 rtp->dtmfcount = dtmftimeout;
308 rtp->dtmfduration = duration;
313 * \brief Process Comfort Noise RTP.
315 * This is incomplete at the moment.
318 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
320 struct ast_frame *f = NULL;
321 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
322 totally help us out becuase we don't have an engine to keep it going and we are not
323 guaranteed to have it every 20ms or anything */
325 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
327 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
328 char iabuf[INET_ADDRSTRLEN];
330 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
331 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
332 ast_set_flag(rtp, FLAG_3389_WARNING);
335 /* Must have at least one byte */
339 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
340 rtp->f.datalen = len - 1;
341 rtp->f.offset = AST_FRIENDLY_OFFSET;
342 memcpy(rtp->f.data, data + 1, len - 1);
348 rtp->f.frametype = AST_FRAME_CNG;
349 rtp->f.subclass = data[0] & 0x7f;
350 rtp->f.datalen = len - 1;
352 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
357 static int rtpread(int *id, int fd, short events, void *cbdata)
359 struct ast_rtp *rtp = cbdata;
361 f = ast_rtp_read(rtp);
364 rtp->callback(rtp, f, rtp->data);
369 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
371 static struct ast_frame null_frame = { AST_FRAME_NULL, };
375 struct sockaddr_in sin;
376 unsigned int rtcpdata[1024];
377 char iabuf[INET_ADDRSTRLEN];
379 if (!rtp || !rtp->rtcp)
384 res = recvfrom(rtp->rtcp->s, rtcpdata, sizeof(rtcpdata),
385 0, (struct sockaddr *)&sin, &len);
389 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
396 ast_log(LOG_WARNING, "RTP Read too short\n");
401 /* Send to whoever sent to us */
402 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
403 (rtp->rtcp->them.sin_port != sin.sin_port)) {
404 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
405 if (option_debug || rtpdebug)
406 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));
410 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
414 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
416 struct timeval ts = ast_samp2tv( timestamp, 8000);
417 if (ast_tvzero(rtp->rxcore) || mark) {
418 rtp->rxcore = ast_tvsub(ast_tvnow(), ts);
419 /* Round to 20ms for nice, pretty timestamps */
420 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 20000;
422 *tv = ast_tvadd(rtp->rxcore, ts);
425 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
428 struct sockaddr_in sin;
438 char iabuf[INET_ADDRSTRLEN];
439 unsigned int timestamp;
440 unsigned int *rtpheader;
441 static struct ast_frame *f, null_frame = { AST_FRAME_NULL, };
442 struct rtpPayloadType rtpPT;
446 /* Cache where the header will go */
447 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
448 0, (struct sockaddr *)&sin, &len);
451 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
454 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
460 ast_log(LOG_WARNING, "RTP Read too short\n");
464 /* Ignore if the other side hasn't been given an address
466 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
470 /* Send to whoever sent to us */
471 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
472 (rtp->them.sin_port != sin.sin_port)) {
473 memcpy(&rtp->them, &sin, sizeof(rtp->them));
475 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
476 if (option_debug || rtpdebug)
477 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));
482 seqno = ntohl(rtpheader[0]);
484 /* Check RTP version */
485 version = (seqno & 0xC0000000) >> 30;
489 payloadtype = (seqno & 0x7f0000) >> 16;
490 padding = seqno & (1 << 29);
491 mark = seqno & (1 << 23);
492 ext = seqno & (1 << 28);
494 timestamp = ntohl(rtpheader[1]);
497 /* Remove padding bytes */
498 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
502 /* RTP Extension present */
504 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
508 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
512 if(rtp_debug_test_addr(&sin))
513 ast_verbose("Got RTP packet from %s:%d (type %d, seq %d, ts %d, len %d)\n"
514 , ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
516 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
517 if (!rtpPT.isAstFormat) {
518 /* This is special in-band data that's not one of our codecs */
519 if (rtpPT.code == AST_RTP_DTMF) {
520 /* It's special -- rfc2833 process it */
521 if(rtp_debug_test_addr(&sin)) {
524 unsigned int event_end;
525 unsigned int duration;
526 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
527 event = ntohl(*((unsigned int *)(data)));
529 event_end = ntohl(*((unsigned int *)(data)));
532 duration = ntohl(*((unsigned int *)(data)));
534 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);
536 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
537 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
538 rtp->lasteventseqn = seqno;
545 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
546 /* It's really special -- process it the Cisco way */
547 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
548 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
549 rtp->lasteventseqn = seqno;
556 } else if (rtpPT.code == AST_RTP_CN) {
558 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
564 ast_log(LOG_NOTICE, "Unknown RTP codec %d received\n", payloadtype);
568 rtp->f.subclass = rtpPT.code;
569 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO)
570 rtp->f.frametype = AST_FRAME_VOICE;
572 rtp->f.frametype = AST_FRAME_VIDEO;
573 rtp->lastrxformat = rtp->f.subclass;
576 rtp->lastrxts = timestamp;
579 for (x=rtp->rxseqno + 1; x < seqno; x++) {
580 /* Queue empty frames */
586 rtp->f.src = "RTPMissedFrame";
589 rtp->rxseqno = seqno;
591 if (rtp->dtmfcount) {
593 printf("dtmfcount was %d\n", rtp->dtmfcount);
595 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
596 if (rtp->dtmfcount < 0)
599 if (dtmftimeout != rtp->dtmfcount)
600 printf("dtmfcount is %d\n", rtp->dtmfcount);
603 rtp->lastrxts = timestamp;
605 /* Send any pending DTMF */
606 if (rtp->resp && !rtp->dtmfcount) {
608 ast_log(LOG_DEBUG, "Sending pending DTMF\n");
609 return send_dtmf(rtp);
612 rtp->f.datalen = res - hdrlen;
613 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
614 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
615 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
616 rtp->f.samples = ast_codec_get_samples(&rtp->f);
617 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
618 ast_frame_byteswap_be(&rtp->f);
619 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
621 /* Video -- samples is # of samples vs. 90000 */
622 if (!rtp->lastividtimestamp)
623 rtp->lastividtimestamp = timestamp;
624 rtp->f.samples = timestamp - rtp->lastividtimestamp;
625 rtp->lastividtimestamp = timestamp;
626 rtp->f.delivery.tv_sec = 0;
627 rtp->f.delivery.tv_usec = 0;
629 rtp->f.subclass |= 0x1;
636 /* The following array defines the MIME Media type (and subtype) for each
637 of our codecs, or RTP-specific data type. */
639 struct rtpPayloadType payloadType;
643 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
644 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
645 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
646 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
647 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
648 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
649 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
650 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
651 {{1, AST_FORMAT_G729A}, "audio", "G729"},
652 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
653 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
654 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
655 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
656 {{0, AST_RTP_CN}, "audio", "CN"},
657 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
658 {{1, AST_FORMAT_PNG}, "video", "PNG"},
659 {{1, AST_FORMAT_H261}, "video", "H261"},
660 {{1, AST_FORMAT_H263}, "video", "H263"},
661 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
664 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
665 also, our own choices for dynamic payload types. This is our master
666 table for transmission */
667 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
668 [0] = {1, AST_FORMAT_ULAW},
669 #ifdef USE_DEPRECATED_G726
670 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
672 [3] = {1, AST_FORMAT_GSM},
673 [4] = {1, AST_FORMAT_G723_1},
674 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
675 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
676 [7] = {1, AST_FORMAT_LPC10},
677 [8] = {1, AST_FORMAT_ALAW},
678 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
679 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
680 [13] = {0, AST_RTP_CN},
681 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
682 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
683 [18] = {1, AST_FORMAT_G729A},
684 [19] = {0, AST_RTP_CN}, /* Also used for CN */
685 [26] = {1, AST_FORMAT_JPEG},
686 [31] = {1, AST_FORMAT_H261},
687 [34] = {1, AST_FORMAT_H263},
688 [103] = {1, AST_FORMAT_H263_PLUS},
689 [97] = {1, AST_FORMAT_ILBC},
690 [101] = {0, AST_RTP_DTMF},
691 [110] = {1, AST_FORMAT_SPEEX},
692 [111] = {1, AST_FORMAT_G726},
693 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
696 void ast_rtp_pt_clear(struct ast_rtp* rtp)
702 for (i = 0; i < MAX_RTP_PT; ++i) {
703 rtp->current_RTP_PT[i].isAstFormat = 0;
704 rtp->current_RTP_PT[i].code = 0;
707 rtp->rtp_lookup_code_cache_isAstFormat = 0;
708 rtp->rtp_lookup_code_cache_code = 0;
709 rtp->rtp_lookup_code_cache_result = 0;
712 void ast_rtp_pt_default(struct ast_rtp* rtp)
716 /* Initialize to default payload types */
717 for (i = 0; i < MAX_RTP_PT; ++i) {
718 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
719 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
722 rtp->rtp_lookup_code_cache_isAstFormat = 0;
723 rtp->rtp_lookup_code_cache_code = 0;
724 rtp->rtp_lookup_code_cache_result = 0;
727 /* Make a note of a RTP paymoad type that was seen in a SDP "m=" line. */
728 /* By default, use the well-known value for this type (although it may */
729 /* still be set to a different value by a subsequent "a=rtpmap:" line): */
730 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt) {
731 if (pt < 0 || pt > MAX_RTP_PT)
732 return; /* bogus payload type */
734 if (static_RTP_PT[pt].code != 0) {
735 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
739 /* Make a note of a RTP payload type (with MIME type) that was seen in */
740 /* a SDP "a=rtpmap:" line. */
741 void ast_rtp_set_rtpmap_type(struct ast_rtp* rtp, int pt,
742 char* mimeType, char* mimeSubtype) {
745 if (pt < 0 || pt > MAX_RTP_PT)
746 return; /* bogus payload type */
748 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
749 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
750 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
751 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
757 /* Return the union of all of the codecs that were set by rtp_set...() calls */
758 /* They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
759 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
760 int* astFormats, int* nonAstFormats) {
763 *astFormats = *nonAstFormats = 0;
764 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
765 if (rtp->current_RTP_PT[pt].isAstFormat) {
766 *astFormats |= rtp->current_RTP_PT[pt].code;
768 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
773 void ast_rtp_offered_from_local(struct ast_rtp* rtp, int local) {
775 rtp->rtp_offered_from_local = local;
777 ast_log(LOG_WARNING, "rtp structure is null\n");
780 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
782 struct rtpPayloadType result;
784 result.isAstFormat = result.code = 0;
785 if (pt < 0 || pt > MAX_RTP_PT)
786 return result; /* bogus payload type */
788 /* Start with the negotiated codecs */
789 if (!rtp->rtp_offered_from_local)
790 result = rtp->current_RTP_PT[pt];
792 /* If it doesn't exist, check our static RTP type list, just in case */
794 result = static_RTP_PT[pt];
798 /* Looks up an RTP code out of our *static* outbound list */
799 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
803 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
804 code == rtp->rtp_lookup_code_cache_code) {
806 /* Use our cached mapping, to avoid the overhead of the loop below */
807 return rtp->rtp_lookup_code_cache_result;
810 /* Check the dynamic list first */
811 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
812 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
813 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
814 rtp->rtp_lookup_code_cache_code = code;
815 rtp->rtp_lookup_code_cache_result = pt;
820 /* Then the static list */
821 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
822 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
823 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
824 rtp->rtp_lookup_code_cache_code = code;
825 rtp->rtp_lookup_code_cache_result = pt;
832 char* ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code) {
836 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
837 if (mimeTypes[i].payloadType.code == code && mimeTypes[i].payloadType.isAstFormat == isAstFormat) {
838 return mimeTypes[i].subtype;
844 char *ast_rtp_lookup_mime_multiple(char *buf, int size, const int capability, const int isAstFormat)
854 snprintf(end, size, "0x%x (", capability);
861 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
862 if (capability & format) {
863 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format);
864 snprintf(end, size, "%s|", name);
872 snprintf(start, size, "nothing)");
879 static int rtp_socket(void)
883 s = socket(AF_INET, SOCK_DGRAM, 0);
885 flags = fcntl(s, F_GETFL);
886 fcntl(s, F_SETFL, flags | O_NONBLOCK);
889 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
896 * \brief Initialize a new RTCP session.
898 * \returns The newly initialized RTCP session.
900 static struct ast_rtcp *ast_rtcp_new(void)
902 struct ast_rtcp *rtcp;
903 rtcp = malloc(sizeof(struct ast_rtcp));
906 memset(rtcp, 0, sizeof(struct ast_rtcp));
907 rtcp->s = rtp_socket();
908 rtcp->us.sin_family = AF_INET;
911 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
917 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
923 rtp = malloc(sizeof(struct ast_rtp));
926 memset(rtp, 0, sizeof(struct ast_rtp));
927 rtp->them.sin_family = AF_INET;
928 rtp->us.sin_family = AF_INET;
929 rtp->s = rtp_socket();
931 rtp->seqno = rand() & 0xffff;
934 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
937 if (sched && rtcpenable) {
939 rtp->rtcp = ast_rtcp_new();
942 /* Select a random port number in the range of possible RTP */
943 x = (rand() % (rtpend-rtpstart)) + rtpstart;
945 /* Save it for future references. */
947 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
949 /* Must be an even port number by RTP spec */
950 rtp->us.sin_port = htons(x);
951 rtp->us.sin_addr = addr;
952 /* If there's rtcp, initialize it as well. */
954 rtp->rtcp->us.sin_port = htons(x + 1);
955 /* Try to bind it/them. */
956 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
957 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
960 /* Primary bind succeeded! Gotta recreate it */
962 rtp->s = rtp_socket();
964 if (errno != EADDRINUSE) {
965 /* We got an error that wasn't expected, abort! */
966 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
975 /* The port was used, increment it (by two). */
977 /* Did we go over the limit ? */
979 /* then, start from the begingig. */
980 x = (rtpstart + 1) & ~1;
981 /* Check if we reached the place were we started. */
982 if (x == startplace) {
983 /* If so, there's no ports available. */
984 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
994 if (io && sched && callbackmode) {
995 /* Operate this one in a callback mode */
998 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1000 ast_rtp_pt_default(rtp);
1004 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1008 memset(&ia, 0, sizeof(ia));
1009 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1012 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1016 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1017 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1021 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1023 rtp->them.sin_port = them->sin_port;
1024 rtp->them.sin_addr = them->sin_addr;
1026 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1027 rtp->rtcp->them.sin_addr = them->sin_addr;
1032 void ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1034 them->sin_family = AF_INET;
1035 them->sin_port = rtp->them.sin_port;
1036 them->sin_addr = rtp->them.sin_addr;
1039 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1041 memcpy(us, &rtp->us, sizeof(rtp->us));
1044 void ast_rtp_stop(struct ast_rtp *rtp)
1046 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1047 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1049 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1050 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1054 void ast_rtp_reset(struct ast_rtp *rtp)
1056 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1057 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1058 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1060 rtp->lastdigitts = 0;
1062 rtp->lastividtimestamp = 0;
1063 rtp->lastovidtimestamp = 0;
1064 rtp->lasteventseqn = 0;
1065 rtp->lasteventendseqn = 0;
1066 rtp->lasttxformat = 0;
1067 rtp->lastrxformat = 0;
1069 rtp->dtmfduration = 0;
1074 void ast_rtp_destroy(struct ast_rtp *rtp)
1077 ast_smoother_free(rtp->smoother);
1079 ast_io_remove(rtp->io, rtp->ioid);
1083 close(rtp->rtcp->s);
1089 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1093 if (ast_tvzero(rtp->txcore)) {
1094 rtp->txcore = ast_tvnow();
1095 /* Round to 20ms for nice, pretty timestamps */
1096 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1098 /* Use previous txcore if available */
1099 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
1100 ms = ast_tvdiff_ms(t, rtp->txcore);
1103 /* Use what we just got for next time */
1105 return (unsigned int) ms;
1108 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
1110 unsigned int *rtpheader;
1116 char iabuf[INET_ADDRSTRLEN];
1118 if ((digit <= '9') && (digit >= '0'))
1120 else if (digit == '*')
1122 else if (digit == '#')
1124 else if ((digit >= 'A') && (digit <= 'D'))
1125 digit = digit - 'A' + 12;
1126 else if ((digit >= 'a') && (digit <= 'd'))
1127 digit = digit - 'a' + 12;
1129 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
1132 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
1134 /* If we have no peer, return immediately */
1135 if (!rtp->them.sin_addr.s_addr)
1138 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1140 /* Get a pointer to the header */
1141 rtpheader = (unsigned int *)data;
1142 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
1143 rtpheader[1] = htonl(rtp->lastdigitts);
1144 rtpheader[2] = htonl(rtp->ssrc);
1145 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
1146 for (x = 0; x < 6; x++) {
1147 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1148 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
1150 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
1151 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1152 ntohs(rtp->them.sin_port), strerror(errno));
1153 if (rtp_debug_test_addr(&rtp->them))
1154 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %u, ts %u, len %u)\n",
1155 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1156 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
1158 /* Sequence number of last two end packets does not get incremented */
1161 /* Clear marker bit and set seqno */
1162 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
1163 /* For the last three packets, set the duration and the end bit */
1166 /* No, this is wrong... Do not increment lastdigitts, that's not according
1167 to the RFC, as best we can determine */
1168 rtp->lastdigitts++; /* or else the SPA3000 will click instead of beeping... */
1169 rtpheader[1] = htonl(rtp->lastdigitts);
1171 /* Make duration 800 (100ms) */
1172 rtpheader[3] |= htonl((800));
1173 /* Set the End bit */
1174 rtpheader[3] |= htonl((1 << 23));
1177 /* Increment the digit timestamp by 120ms, to ensure that digits
1178 sent sequentially with no intervening non-digit packets do not
1179 get sent with the same timestamp, and that sequential digits
1180 have some 'dead air' in between them
1182 rtp->lastdigitts += 960;
1183 /* Increment the sequence number to reflect the last packet
1190 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
1192 unsigned int *rtpheader;
1197 char iabuf[INET_ADDRSTRLEN];
1198 level = 127 - (level & 0x7f);
1199 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
1201 /* If we have no peer, return immediately */
1202 if (!rtp->them.sin_addr.s_addr)
1205 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1207 /* Get a pointer to the header */
1208 rtpheader = (unsigned int *)data;
1209 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
1210 rtpheader[1] = htonl(rtp->lastts);
1211 rtpheader[2] = htonl(rtp->ssrc);
1213 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1214 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1216 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));
1217 if(rtp_debug_test_addr(&rtp->them))
1218 ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %d, len %d)\n"
1219 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
1225 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
1227 unsigned char *rtpheader;
1228 char iabuf[INET_ADDRSTRLEN];
1235 ms = calc_txstamp(rtp, &f->delivery);
1236 /* Default prediction */
1237 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
1238 pred = rtp->lastts + f->samples;
1240 /* Re-calculate last TS */
1241 rtp->lastts = rtp->lastts + ms * 8;
1242 if (ast_tvzero(f->delivery)) {
1243 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
1244 and if so, go with our prediction */
1245 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
1248 if (option_debug > 2)
1249 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
1254 mark = f->subclass & 0x1;
1255 pred = rtp->lastovidtimestamp + f->samples;
1256 /* Re-calculate last TS */
1257 rtp->lastts = rtp->lastts + ms * 90;
1258 /* If it's close to our prediction, go for it */
1259 if (ast_tvzero(f->delivery)) {
1260 if (abs(rtp->lastts - pred) < 7200) {
1262 rtp->lastovidtimestamp += f->samples;
1264 if (option_debug > 2)
1265 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);
1266 rtp->lastovidtimestamp = rtp->lastts;
1270 /* If the timestamp for non-digit packets has moved beyond the timestamp
1271 for digits, update the digit timestamp.
1273 if (rtp->lastts > rtp->lastdigitts)
1274 rtp->lastdigitts = rtp->lastts;
1276 /* Get a pointer to the header */
1277 rtpheader = (unsigned char *)(f->data - hdrlen);
1279 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
1280 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
1281 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
1283 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1284 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1286 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1287 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));
1288 } else if ((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) {
1289 /* Only give this error message once if we are not RTP debugging */
1290 if (option_debug || rtpdebug)
1291 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));
1292 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
1296 if(rtp_debug_test_addr(&rtp->them))
1297 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %u, ts %u, len %u)\n"
1298 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
1306 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
1308 struct ast_frame *f;
1314 /* If we have no peer, return immediately */
1315 if (!rtp->them.sin_addr.s_addr)
1318 /* If there is no data length, return immediately */
1322 /* Make sure we have enough space for RTP header */
1323 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
1324 ast_log(LOG_WARNING, "RTP can only send voice\n");
1328 subclass = _f->subclass;
1329 if (_f->frametype == AST_FRAME_VIDEO)
1332 codec = ast_rtp_lookup_code(rtp, 1, subclass);
1334 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
1338 if (rtp->lasttxformat != subclass) {
1339 /* New format, reset the smoother */
1341 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
1342 rtp->lasttxformat = subclass;
1344 ast_smoother_free(rtp->smoother);
1345 rtp->smoother = NULL;
1350 case AST_FORMAT_SLINEAR:
1351 if (!rtp->smoother) {
1352 rtp->smoother = ast_smoother_new(320);
1354 if (!rtp->smoother) {
1355 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1358 ast_smoother_feed_be(rtp->smoother, _f);
1360 while((f = ast_smoother_read(rtp->smoother)))
1361 ast_rtp_raw_write(rtp, f, codec);
1363 case AST_FORMAT_ULAW:
1364 case AST_FORMAT_ALAW:
1365 if (!rtp->smoother) {
1366 rtp->smoother = ast_smoother_new(160);
1368 if (!rtp->smoother) {
1369 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1372 ast_smoother_feed(rtp->smoother, _f);
1374 while((f = ast_smoother_read(rtp->smoother)))
1375 ast_rtp_raw_write(rtp, f, codec);
1377 case AST_FORMAT_ADPCM:
1378 case AST_FORMAT_G726:
1379 if (!rtp->smoother) {
1380 rtp->smoother = ast_smoother_new(80);
1382 if (!rtp->smoother) {
1383 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1386 ast_smoother_feed(rtp->smoother, _f);
1388 while((f = ast_smoother_read(rtp->smoother)))
1389 ast_rtp_raw_write(rtp, f, codec);
1391 case AST_FORMAT_G729A:
1392 if (!rtp->smoother) {
1393 rtp->smoother = ast_smoother_new(20);
1395 ast_smoother_set_flags(rtp->smoother, AST_SMOOTHER_FLAG_G729);
1397 if (!rtp->smoother) {
1398 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
1401 ast_smoother_feed(rtp->smoother, _f);
1403 while((f = ast_smoother_read(rtp->smoother)))
1404 ast_rtp_raw_write(rtp, f, codec);
1406 case AST_FORMAT_GSM:
1407 if (!rtp->smoother) {
1408 rtp->smoother = ast_smoother_new(33);
1410 if (!rtp->smoother) {
1411 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
1414 ast_smoother_feed(rtp->smoother, _f);
1415 while((f = ast_smoother_read(rtp->smoother)))
1416 ast_rtp_raw_write(rtp, f, codec);
1418 case AST_FORMAT_ILBC:
1419 if (!rtp->smoother) {
1420 rtp->smoother = ast_smoother_new(50);
1422 if (!rtp->smoother) {
1423 ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
1426 ast_smoother_feed(rtp->smoother, _f);
1427 while((f = ast_smoother_read(rtp->smoother)))
1428 ast_rtp_raw_write(rtp, f, codec);
1431 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
1432 /* fall through to... */
1433 case AST_FORMAT_H261:
1434 case AST_FORMAT_H263:
1435 case AST_FORMAT_H263_PLUS:
1436 case AST_FORMAT_G723_1:
1437 case AST_FORMAT_LPC10:
1438 case AST_FORMAT_SPEEX:
1439 /* Don't buffer outgoing frames; send them one-per-packet: */
1440 if (_f->offset < hdrlen) {
1445 ast_rtp_raw_write(rtp, f, codec);
1451 /*--- ast_rtp_proto_unregister: Unregister interface to channel driver */
1452 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
1454 struct ast_rtp_protocol *cur, *prev;
1461 prev->next = proto->next;
1463 protos = proto->next;
1471 /*--- ast_rtp_proto_register: Register interface to channel driver */
1472 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
1474 struct ast_rtp_protocol *cur;
1477 if (cur->type == proto->type) {
1478 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1483 proto->next = protos;
1488 /*--- get_proto: Get channel driver interface structure */
1489 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1491 struct ast_rtp_protocol *cur;
1495 if (cur->type == chan->type) {
1503 /* ast_rtp_bridge: Bridge calls. If possible and allowed, initiate
1504 re-invite so the peers exchange media directly outside
1506 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)
1508 struct ast_frame *f;
1509 struct ast_channel *who, *cs[3];
1510 struct ast_rtp *p0, *p1; /* Audio RTP Channels */
1511 struct ast_rtp *vp0, *vp1; /* Video RTP channels */
1512 struct ast_rtp_protocol *pr0, *pr1;
1513 struct sockaddr_in ac0, ac1;
1514 struct sockaddr_in vac0, vac1;
1515 struct sockaddr_in t0, t1;
1516 struct sockaddr_in vt0, vt1;
1517 char iabuf[INET_ADDRSTRLEN];
1520 int codec0,codec1, oldcodec0, oldcodec1;
1522 memset(&vt0, 0, sizeof(vt0));
1523 memset(&vt1, 0, sizeof(vt1));
1524 memset(&vac0, 0, sizeof(vac0));
1525 memset(&vac1, 0, sizeof(vac1));
1527 /* if need DTMF, cant native bridge */
1528 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
1529 return AST_BRIDGE_FAILED_NOWARN;
1532 ast_mutex_lock(&c0->lock);
1533 while(ast_mutex_trylock(&c1->lock)) {
1534 ast_mutex_unlock(&c0->lock);
1536 ast_mutex_lock(&c0->lock);
1539 /* Find channel driver interfaces */
1540 pr0 = get_proto(c0);
1541 pr1 = get_proto(c1);
1543 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
1544 ast_mutex_unlock(&c0->lock);
1545 ast_mutex_unlock(&c1->lock);
1546 return AST_BRIDGE_FAILED;
1549 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1550 ast_mutex_unlock(&c0->lock);
1551 ast_mutex_unlock(&c1->lock);
1552 return AST_BRIDGE_FAILED;
1555 /* Get channel specific interface structures */
1556 pvt0 = c0->tech_pvt;
1557 pvt1 = c1->tech_pvt;
1559 /* Get audio and video interface (if native bridge is possible) */
1560 p0 = pr0->get_rtp_info(c0);
1561 if (pr0->get_vrtp_info)
1562 vp0 = pr0->get_vrtp_info(c0);
1565 p1 = pr1->get_rtp_info(c1);
1566 if (pr1->get_vrtp_info)
1567 vp1 = pr1->get_vrtp_info(c1);
1571 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1573 /* Somebody doesn't want to play... */
1574 ast_mutex_unlock(&c0->lock);
1575 ast_mutex_unlock(&c1->lock);
1576 return AST_BRIDGE_FAILED_NOWARN;
1578 /* Get codecs from both sides */
1580 codec0 = pr0->get_codec(c0);
1584 codec1 = pr1->get_codec(c1);
1587 if (pr0->get_codec && pr1->get_codec) {
1588 /* Hey, we can't do reinvite if both parties speak different codecs */
1589 if (!(codec0 & codec1)) {
1591 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
1592 ast_mutex_unlock(&c0->lock);
1593 ast_mutex_unlock(&c1->lock);
1594 return AST_BRIDGE_FAILED_NOWARN;
1598 /* Ok, we should be able to redirect the media. Start with one channel */
1599 if (pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
1600 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1602 /* Store RTP peer */
1603 ast_rtp_get_peer(p1, &ac1);
1605 ast_rtp_get_peer(vp1, &vac1);
1607 /* Then test the other channel */
1608 if (pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
1609 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1611 /* Store RTP peer */
1612 ast_rtp_get_peer(p0, &ac0);
1614 ast_rtp_get_peer(vp0, &vac0);
1616 ast_mutex_unlock(&c0->lock);
1617 ast_mutex_unlock(&c1->lock);
1618 /* External RTP Bridge up, now loop and see if something happes that force us to take the
1619 media back to Asterisk */
1626 /* Check if something changed... */
1627 if ((c0->tech_pvt != pvt0) ||
1628 (c1->tech_pvt != pvt1) ||
1629 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1630 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
1631 if (c0->tech_pvt == pvt0) {
1632 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
1633 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
1635 if (c1->tech_pvt == pvt1) {
1636 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
1637 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
1639 return AST_BRIDGE_RETRY;
1641 /* Now check if they have changed address */
1642 ast_rtp_get_peer(p1, &t1);
1643 ast_rtp_get_peer(p0, &t0);
1645 codec0 = pr0->get_codec(c0);
1647 codec1 = pr1->get_codec(c1);
1649 ast_rtp_get_peer(vp1, &vt1);
1651 ast_rtp_get_peer(vp0, &vt0);
1652 if (inaddrcmp(&t1, &ac1) || (vp1 && inaddrcmp(&vt1, &vac1)) || (codec1 != oldcodec1)) {
1653 if (option_debug > 1) {
1654 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
1655 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t1.sin_addr), ntohs(t1.sin_port), codec1);
1656 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
1657 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vt1.sin_addr), ntohs(vt1.sin_port), codec1);
1658 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1659 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
1660 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1661 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
1663 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)))
1664 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
1665 memcpy(&ac1, &t1, sizeof(ac1));
1666 memcpy(&vac1, &vt1, sizeof(vac1));
1669 if (inaddrcmp(&t0, &ac0) || (vp0 && inaddrcmp(&vt0, &vac0))) {
1671 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
1672 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t0.sin_addr), ntohs(t0.sin_port), codec0);
1673 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1674 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
1676 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)))
1677 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
1678 memcpy(&ac0, &t0, sizeof(ac0));
1679 memcpy(&vac0, &vt0, sizeof(vac0));
1682 who = ast_waitfor_n(cs, 2, &timeoutms);
1685 return AST_BRIDGE_RETRY;
1687 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
1688 /* check for hangup / whentohangup */
1689 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1694 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
1695 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
1696 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
1700 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
1701 if ((c0->tech_pvt == pvt0) && (!c0->_softhangup)) {
1702 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
1703 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
1705 if ((c1->tech_pvt == pvt1) && (!c1->_softhangup)) {
1706 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
1707 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
1709 return AST_BRIDGE_COMPLETE;
1710 } else if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1711 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
1712 (f->subclass == AST_CONTROL_VIDUPDATE)) {
1713 ast_indicate(who == c0 ? c1 : c0, f->subclass);
1718 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
1719 return AST_BRIDGE_COMPLETE;
1722 if ((f->frametype == AST_FRAME_DTMF) ||
1723 (f->frametype == AST_FRAME_VOICE) ||
1724 (f->frametype == AST_FRAME_VIDEO)) {
1725 /* Forward voice or DTMF frames if they happen upon us */
1728 } else if (who == c1) {
1734 /* Swap priority not that it's a big deal at this point */
1740 return AST_BRIDGE_FAILED;
1743 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
1746 struct ast_hostent ahp;
1747 char iabuf[INET_ADDRSTRLEN];
1752 return RESULT_SHOWUSAGE;
1754 p = strstr(arg, ":");
1760 hp = ast_gethostbyname(arg, &ahp);
1762 return RESULT_SHOWUSAGE;
1763 rtpdebugaddr.sin_family = AF_INET;
1764 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
1765 rtpdebugaddr.sin_port = htons(port);
1767 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr));
1769 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr), port);
1771 return RESULT_SUCCESS;
1774 static int rtp_do_debug(int fd, int argc, char *argv[])
1778 return RESULT_SHOWUSAGE;
1779 return rtp_do_debug_ip(fd, argc, argv);
1782 memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
1783 ast_cli(fd, "RTP Debugging Enabled\n");
1784 return RESULT_SUCCESS;
1787 static int rtp_no_debug(int fd, int argc, char *argv[])
1790 return RESULT_SHOWUSAGE;
1792 ast_cli(fd,"RTP Debugging Disabled\n");
1793 return RESULT_SUCCESS;
1796 static char debug_usage[] =
1797 "Usage: rtp debug [ip host[:port]]\n"
1798 " Enable dumping of all RTP packets to and from host.\n";
1800 static char no_debug_usage[] =
1801 "Usage: rtp no debug\n"
1802 " Disable all RTP debugging\n";
1804 static struct ast_cli_entry cli_debug_ip =
1805 {{ "rtp", "debug", "ip", NULL } , rtp_do_debug, "Enable RTP debugging on IP", debug_usage };
1807 static struct ast_cli_entry cli_debug =
1808 {{ "rtp", "debug", NULL } , rtp_do_debug, "Enable RTP debugging", debug_usage };
1810 static struct ast_cli_entry cli_no_debug =
1811 {{ "rtp", "no", "debug", NULL } , rtp_no_debug, "Disable RTP debugging", no_debug_usage };
1813 void ast_rtp_reload(void)
1815 struct ast_config *cfg;
1820 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
1821 cfg = ast_config_load("rtp.conf");
1823 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
1825 if (rtpstart < 1024)
1827 if (rtpstart > 65535)
1830 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
1837 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
1845 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
1848 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
1849 dtmftimeout = atoi(s);
1850 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
1851 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
1852 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
1853 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
1856 ast_config_destroy(cfg);
1858 if (rtpstart >= rtpend) {
1859 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
1863 if (option_verbose > 1)
1864 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
1868 /*--- ast_rtp_init: Initialize the RTP system in Asterisk */
1869 void ast_rtp_init(void)
1871 ast_cli_register(&cli_debug);
1872 ast_cli_register(&cli_debug_ip);
1873 ast_cli_register(&cli_no_debug);