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.
22 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
24 * \author Mark Spencer <markster@digium.com>
26 * \note RTP is deffined in RFC 3550.
36 #include <netinet/in.h>
38 #include <sys/socket.h>
39 #include <arpa/inet.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
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 struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
73 static int nochecksums = 0;
76 /*! \brief The value of each payload format mapping: */
77 struct rtpPayloadType {
78 int isAstFormat; /*!< whether the following code is an AST_FORMAT */
82 #define MAX_RTP_PT 256
84 #define FLAG_3389_WARNING (1 << 0)
85 #define FLAG_NAT_ACTIVE (3 << 1)
86 #define FLAG_NAT_INACTIVE (0 << 1)
87 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
89 /*! \brief RTP session description */
94 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
95 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
97 unsigned int lastdigitts;
98 unsigned int lastrxts;
99 unsigned int lastividtimestamp;
100 unsigned int lastovidtimestamp;
101 unsigned int lasteventseqn;
102 unsigned int lasteventendseqn;
106 unsigned int dtmfduration;
109 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
110 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
111 struct timeval rxcore;
112 struct timeval txcore;
113 struct timeval dtmfmute;
114 struct ast_smoother *smoother;
116 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
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 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
124 int rtp_lookup_code_cache_code;
125 int rtp_lookup_code_cache_result;
126 struct ast_rtcp *rtcp;
130 * \brief Structure defining an RTCP session.
132 * The concept "RTCP session" is not defined in RFC 3550, but since
133 * this structure is analogous to ast_rtp, which tracks a RTP session,
134 * it is logical to think of this as a RTCP session.
136 * RTCP packet is defined on page 9 of RFC 3550.
140 int s; /*!< Socket */
141 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
142 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
145 /*! \brief List of current sessions */
146 static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
148 int ast_rtp_fd(struct ast_rtp *rtp)
153 int ast_rtcp_fd(struct ast_rtp *rtp)
160 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
165 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
167 rtp->callback = callback;
170 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
175 static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
177 static struct ast_frame null_frame = { AST_FRAME_NULL, };
178 char iabuf[INET_ADDRSTRLEN];
180 if (ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
182 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
184 rtp->dtmfduration = 0;
188 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));
189 if (rtp->resp == 'X') {
190 rtp->f.frametype = AST_FRAME_CONTROL;
191 rtp->f.subclass = AST_CONTROL_FLASH;
193 rtp->f.frametype = AST_FRAME_DTMF;
194 rtp->f.subclass = rtp->resp;
201 rtp->dtmfduration = 0;
206 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
210 if (rtpdebugaddr.sin_addr.s_addr) {
211 if (((ntohs(rtpdebugaddr.sin_port) != 0)
212 && (rtpdebugaddr.sin_port != addr->sin_port))
213 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
219 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
223 struct ast_frame *f = NULL;
224 event = ntohl(*((unsigned int *)(data)));
226 if (option_debug > 2 || rtpdebug)
227 ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
230 } else if (event < 11) {
232 } else if (event < 12) {
234 } else if (event < 16) {
235 resp = 'A' + (event - 12);
236 } else if (event < 17) {
239 if (rtp->resp && (rtp->resp != resp)) {
243 rtp->dtmfcount = dtmftimeout;
248 * \brief Process RTP DTMF and events according to RFC 2833.
250 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
258 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
261 unsigned int event_end;
262 unsigned int duration;
264 struct ast_frame *f = NULL;
266 event = ntohl(*((unsigned int *)(data)));
268 event_end = ntohl(*((unsigned int *)(data)));
271 duration = ntohl(*((unsigned int *)(data)));
273 if (rtpdebug || option_debug > 2)
274 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
277 } else if (event < 11) {
279 } else if (event < 12) {
281 } else if (event < 16) {
282 resp = 'A' + (event - 12);
283 } else if (event < 17) { /* Event 16: Hook flash */
286 if (rtp->resp && (rtp->resp != resp)) {
288 } else if(event_end & 0x80) {
290 if(rtp->lasteventendseqn != seqno) {
292 rtp->lasteventendseqn = seqno;
298 } else if (rtp->resp && rtp->dtmfduration && (duration < rtp->dtmfduration)) {
301 if (!(event_end & 0x80))
303 rtp->dtmfcount = dtmftimeout;
304 rtp->dtmfduration = duration;
309 * \brief Process Comfort Noise RTP.
311 * This is incomplete at the moment.
314 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
316 struct ast_frame *f = NULL;
317 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
318 totally help us out becuase we don't have an engine to keep it going and we are not
319 guaranteed to have it every 20ms or anything */
321 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
323 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
324 char iabuf[INET_ADDRSTRLEN];
326 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
327 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
328 ast_set_flag(rtp, FLAG_3389_WARNING);
331 /* Must have at least one byte */
335 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
336 rtp->f.datalen = len - 1;
337 rtp->f.offset = AST_FRIENDLY_OFFSET;
338 memcpy(rtp->f.data, data + 1, len - 1);
344 rtp->f.frametype = AST_FRAME_CNG;
345 rtp->f.subclass = data[0] & 0x7f;
346 rtp->f.datalen = len - 1;
348 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
353 static int rtpread(int *id, int fd, short events, void *cbdata)
355 struct ast_rtp *rtp = cbdata;
357 f = ast_rtp_read(rtp);
360 rtp->callback(rtp, f, rtp->data);
365 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
367 static struct ast_frame null_frame = { AST_FRAME_NULL, };
371 struct sockaddr_in sin;
372 unsigned int rtcpdata[1024];
373 char iabuf[INET_ADDRSTRLEN];
375 if (!rtp || !rtp->rtcp)
380 res = recvfrom(rtp->rtcp->s, rtcpdata, sizeof(rtcpdata),
381 0, (struct sockaddr *)&sin, &len);
385 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
392 ast_log(LOG_WARNING, "RTP Read too short\n");
397 /* Send to whoever sent to us */
398 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
399 (rtp->rtcp->them.sin_port != sin.sin_port)) {
400 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
401 if (option_debug || rtpdebug)
402 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));
406 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
410 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
412 struct timeval ts = ast_samp2tv( timestamp, 8000);
413 if (ast_tvzero(rtp->rxcore) || mark) {
414 rtp->rxcore = ast_tvsub(ast_tvnow(), ts);
415 /* Round to 20ms for nice, pretty timestamps */
416 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 20000;
418 *tv = ast_tvadd(rtp->rxcore, ts);
421 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
424 struct sockaddr_in sin;
434 char iabuf[INET_ADDRSTRLEN];
435 unsigned int timestamp;
436 unsigned int *rtpheader;
437 static struct ast_frame *f, null_frame = { AST_FRAME_NULL, };
438 struct rtpPayloadType rtpPT;
442 /* Cache where the header will go */
443 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
444 0, (struct sockaddr *)&sin, &len);
447 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
450 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
456 ast_log(LOG_WARNING, "RTP Read too short\n");
460 /* Ignore if the other side hasn't been given an address
462 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
466 /* Send to whoever sent to us */
467 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
468 (rtp->them.sin_port != sin.sin_port)) {
469 memcpy(&rtp->them, &sin, sizeof(rtp->them));
471 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
472 if (option_debug || rtpdebug)
473 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));
478 seqno = ntohl(rtpheader[0]);
480 /* Check RTP version */
481 version = (seqno & 0xC0000000) >> 30;
485 payloadtype = (seqno & 0x7f0000) >> 16;
486 padding = seqno & (1 << 29);
487 mark = seqno & (1 << 23);
488 ext = seqno & (1 << 28);
490 timestamp = ntohl(rtpheader[1]);
493 /* Remove padding bytes */
494 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
498 /* RTP Extension present */
500 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
504 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
508 if(rtp_debug_test_addr(&sin))
509 ast_verbose("Got RTP packet from %s:%d (type %d, seq %d, ts %d, len %d)\n"
510 , ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
512 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
513 if (!rtpPT.isAstFormat) {
514 /* This is special in-band data that's not one of our codecs */
515 if (rtpPT.code == AST_RTP_DTMF) {
516 /* It's special -- rfc2833 process it */
517 if(rtp_debug_test_addr(&sin)) {
520 unsigned int event_end;
521 unsigned int duration;
522 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
523 event = ntohl(*((unsigned int *)(data)));
525 event_end = ntohl(*((unsigned int *)(data)));
528 duration = ntohl(*((unsigned int *)(data)));
530 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);
532 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
533 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
534 rtp->lasteventseqn = seqno;
541 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
542 /* It's really special -- process it the Cisco way */
543 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
544 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
545 rtp->lasteventseqn = seqno;
552 } else if (rtpPT.code == AST_RTP_CN) {
554 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
560 ast_log(LOG_NOTICE, "Unknown RTP codec %d received\n", payloadtype);
564 rtp->f.subclass = rtpPT.code;
565 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO)
566 rtp->f.frametype = AST_FRAME_VOICE;
568 rtp->f.frametype = AST_FRAME_VIDEO;
569 rtp->lastrxformat = rtp->f.subclass;
572 rtp->lastrxts = timestamp;
575 for (x=rtp->rxseqno + 1; x < seqno; x++) {
576 /* Queue empty frames */
582 rtp->f.src = "RTPMissedFrame";
585 rtp->rxseqno = seqno;
587 if (rtp->dtmfcount) {
589 printf("dtmfcount was %d\n", rtp->dtmfcount);
591 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
592 if (rtp->dtmfcount < 0)
595 if (dtmftimeout != rtp->dtmfcount)
596 printf("dtmfcount is %d\n", rtp->dtmfcount);
599 rtp->lastrxts = timestamp;
601 /* Send any pending DTMF */
602 if (rtp->resp && !rtp->dtmfcount) {
604 ast_log(LOG_DEBUG, "Sending pending DTMF\n");
605 return send_dtmf(rtp);
608 rtp->f.datalen = res - hdrlen;
609 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
610 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
611 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
612 rtp->f.samples = ast_codec_get_samples(&rtp->f);
613 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
614 ast_frame_byteswap_be(&rtp->f);
615 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
617 /* Video -- samples is # of samples vs. 90000 */
618 if (!rtp->lastividtimestamp)
619 rtp->lastividtimestamp = timestamp;
620 rtp->f.samples = timestamp - rtp->lastividtimestamp;
621 rtp->lastividtimestamp = timestamp;
622 rtp->f.delivery.tv_sec = 0;
623 rtp->f.delivery.tv_usec = 0;
625 rtp->f.subclass |= 0x1;
632 /* The following array defines the MIME Media type (and subtype) for each
633 of our codecs, or RTP-specific data type. */
635 struct rtpPayloadType payloadType;
639 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
640 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
641 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
642 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
643 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
644 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
645 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
646 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
647 {{1, AST_FORMAT_G729A}, "audio", "G729"},
648 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
649 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
650 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
651 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
652 {{0, AST_RTP_CN}, "audio", "CN"},
653 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
654 {{1, AST_FORMAT_PNG}, "video", "PNG"},
655 {{1, AST_FORMAT_H261}, "video", "H261"},
656 {{1, AST_FORMAT_H263}, "video", "H263"},
657 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
660 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
661 also, our own choices for dynamic payload types. This is our master
662 table for transmission */
663 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
664 [0] = {1, AST_FORMAT_ULAW},
665 #ifdef USE_DEPRECATED_G726
666 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
668 [3] = {1, AST_FORMAT_GSM},
669 [4] = {1, AST_FORMAT_G723_1},
670 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
671 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
672 [7] = {1, AST_FORMAT_LPC10},
673 [8] = {1, AST_FORMAT_ALAW},
674 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
675 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
676 [13] = {0, AST_RTP_CN},
677 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
678 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
679 [18] = {1, AST_FORMAT_G729A},
680 [19] = {0, AST_RTP_CN}, /* Also used for CN */
681 [26] = {1, AST_FORMAT_JPEG},
682 [31] = {1, AST_FORMAT_H261},
683 [34] = {1, AST_FORMAT_H263},
684 [103] = {1, AST_FORMAT_H263_PLUS},
685 [97] = {1, AST_FORMAT_ILBC},
686 [101] = {0, AST_RTP_DTMF},
687 [110] = {1, AST_FORMAT_SPEEX},
688 [111] = {1, AST_FORMAT_G726},
689 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
692 void ast_rtp_pt_clear(struct ast_rtp* rtp)
698 for (i = 0; i < MAX_RTP_PT; ++i) {
699 rtp->current_RTP_PT[i].isAstFormat = 0;
700 rtp->current_RTP_PT[i].code = 0;
703 rtp->rtp_lookup_code_cache_isAstFormat = 0;
704 rtp->rtp_lookup_code_cache_code = 0;
705 rtp->rtp_lookup_code_cache_result = 0;
708 void ast_rtp_pt_default(struct ast_rtp* rtp)
712 /* Initialize to default payload types */
713 for (i = 0; i < MAX_RTP_PT; ++i) {
714 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
715 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
718 rtp->rtp_lookup_code_cache_isAstFormat = 0;
719 rtp->rtp_lookup_code_cache_code = 0;
720 rtp->rtp_lookup_code_cache_result = 0;
723 static void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
726 /* Copy payload types from source to destination */
727 for (i=0; i < MAX_RTP_PT; ++i) {
728 dest->current_RTP_PT[i].isAstFormat =
729 src->current_RTP_PT[i].isAstFormat;
730 dest->current_RTP_PT[i].code =
731 src->current_RTP_PT[i].code;
733 dest->rtp_lookup_code_cache_isAstFormat = 0;
734 dest->rtp_lookup_code_cache_code = 0;
735 dest->rtp_lookup_code_cache_result = 0;
738 /*! \brief Get channel driver interface structure */
739 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
741 struct ast_rtp_protocol *cur;
743 AST_LIST_LOCK(&protos);
744 AST_LIST_TRAVERSE(&protos, cur, list) {
745 if (cur->type == chan->type)
748 AST_LIST_UNLOCK(&protos);
753 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src)
755 struct ast_rtp *destp, *srcp; /* Audio RTP Channels */
756 struct ast_rtp *vdestp, *vsrcp; /* Video RTP channels */
757 struct ast_rtp_protocol *destpr, *srcpr;
759 ast_mutex_lock(&dest->lock);
760 while(ast_mutex_trylock(&src->lock)) {
761 ast_mutex_unlock(&dest->lock);
763 ast_mutex_lock(&dest->lock);
766 /* Find channel driver interfaces */
767 destpr = get_proto(dest);
768 srcpr = get_proto(src);
771 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
772 ast_mutex_unlock(&dest->lock);
773 ast_mutex_unlock(&src->lock);
778 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
779 ast_mutex_unlock(&dest->lock);
780 ast_mutex_unlock(&src->lock);
784 /* Get audio and video interface (if native bridge is possible) */
785 destp = destpr->get_rtp_info(dest);
786 if (destpr->get_vrtp_info)
787 vdestp = destpr->get_vrtp_info(dest);
790 srcp = srcpr->get_rtp_info(src);
791 if (srcpr->get_vrtp_info)
792 vsrcp = srcpr->get_vrtp_info(src);
796 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
797 if (!destp || !srcp) {
798 /* Somebody doesn't want to play... */
799 ast_mutex_unlock(&dest->lock);
800 ast_mutex_unlock(&src->lock);
803 ast_rtp_pt_copy(destp, srcp);
805 ast_rtp_pt_copy(vdestp, vsrcp);
806 ast_mutex_unlock(&dest->lock);
807 ast_mutex_unlock(&src->lock);
809 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
813 /*! \brief Make a note of a RTP paymoad type that was seen in a SDP "m=" line.
814 * By default, use the well-known value for this type (although it may
815 * still be set to a different value by a subsequent "a=rtpmap:" line)
817 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
819 if (pt < 0 || pt > MAX_RTP_PT)
820 return; /* bogus payload type */
822 if (static_RTP_PT[pt].code != 0) {
823 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
827 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
828 a SDP "a=rtpmap:" line. */
829 void ast_rtp_set_rtpmap_type(struct ast_rtp* rtp, int pt,
830 char* mimeType, char* mimeSubtype)
834 if (pt < 0 || pt > MAX_RTP_PT)
835 return; /* bogus payload type */
837 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
838 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
839 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
840 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
846 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
847 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
848 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
849 int* astFormats, int* nonAstFormats) {
852 *astFormats = *nonAstFormats = 0;
853 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
854 if (rtp->current_RTP_PT[pt].isAstFormat) {
855 *astFormats |= rtp->current_RTP_PT[pt].code;
857 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
862 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
864 struct rtpPayloadType result;
866 result.isAstFormat = result.code = 0;
867 if (pt < 0 || pt > MAX_RTP_PT)
868 return result; /* bogus payload type */
870 /* Start with the negotiated codecs */
871 result = rtp->current_RTP_PT[pt];
873 /* If it doesn't exist, check our static RTP type list, just in case */
875 result = static_RTP_PT[pt];
879 /*! \brief Looks up an RTP code out of our *static* outbound list */
880 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
884 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
885 code == rtp->rtp_lookup_code_cache_code) {
887 /* Use our cached mapping, to avoid the overhead of the loop below */
888 return rtp->rtp_lookup_code_cache_result;
891 /* Check the dynamic list first */
892 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
893 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
894 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
895 rtp->rtp_lookup_code_cache_code = code;
896 rtp->rtp_lookup_code_cache_result = pt;
901 /* Then the static list */
902 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
903 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
904 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
905 rtp->rtp_lookup_code_cache_code = code;
906 rtp->rtp_lookup_code_cache_result = pt;
913 char* ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code)
918 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
919 if (mimeTypes[i].payloadType.code == code && mimeTypes[i].payloadType.isAstFormat == isAstFormat) {
920 return mimeTypes[i].subtype;
926 char *ast_rtp_lookup_mime_multiple(char *buf, int size, const int capability, const int isAstFormat)
936 snprintf(end, size, "0x%x (", capability);
943 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
944 if (capability & format) {
945 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format);
946 snprintf(end, size, "%s|", name);
954 snprintf(start, size, "nothing)");
961 static int rtp_socket(void)
965 s = socket(AF_INET, SOCK_DGRAM, 0);
967 flags = fcntl(s, F_GETFL);
968 fcntl(s, F_SETFL, flags | O_NONBLOCK);
971 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
978 * \brief Initialize a new RTCP session.
980 * \returns The newly initialized RTCP session.
982 static struct ast_rtcp *ast_rtcp_new(void)
984 struct ast_rtcp *rtcp;
985 rtcp = malloc(sizeof(struct ast_rtcp));
988 memset(rtcp, 0, sizeof(struct ast_rtcp));
989 rtcp->s = rtp_socket();
990 rtcp->us.sin_family = AF_INET;
993 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
999 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
1001 struct ast_rtp *rtp;
1005 rtp = malloc(sizeof(struct ast_rtp));
1008 memset(rtp, 0, sizeof(struct ast_rtp));
1009 rtp->them.sin_family = AF_INET;
1010 rtp->us.sin_family = AF_INET;
1011 rtp->s = rtp_socket();
1013 rtp->seqno = rand() & 0xffff;
1016 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1019 if (sched && rtcpenable) {
1021 rtp->rtcp = ast_rtcp_new();
1024 /* Select a random port number in the range of possible RTP */
1025 x = (rand() % (rtpend-rtpstart)) + rtpstart;
1027 /* Save it for future references. */
1029 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1031 /* Must be an even port number by RTP spec */
1032 rtp->us.sin_port = htons(x);
1033 rtp->us.sin_addr = addr;
1034 /* If there's rtcp, initialize it as well. */
1036 rtp->rtcp->us.sin_port = htons(x + 1);
1037 /* Try to bind it/them. */
1038 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1039 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1042 /* Primary bind succeeded! Gotta recreate it */
1044 rtp->s = rtp_socket();
1046 if (errno != EADDRINUSE) {
1047 /* We got an error that wasn't expected, abort! */
1048 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1051 close(rtp->rtcp->s);
1057 /* The port was used, increment it (by two). */
1059 /* Did we go over the limit ? */
1061 /* then, start from the begingig. */
1062 x = (rtpstart + 1) & ~1;
1063 /* Check if we reached the place were we started. */
1064 if (x == startplace) {
1065 /* If so, there's no ports available. */
1066 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1069 close(rtp->rtcp->s);
1076 if (io && sched && callbackmode) {
1077 /* Operate this one in a callback mode */
1080 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1082 ast_rtp_pt_default(rtp);
1086 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1090 memset(&ia, 0, sizeof(ia));
1091 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1094 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1098 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1099 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1103 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1105 rtp->them.sin_port = them->sin_port;
1106 rtp->them.sin_addr = them->sin_addr;
1108 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1109 rtp->rtcp->them.sin_addr = them->sin_addr;
1114 void ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1116 them->sin_family = AF_INET;
1117 them->sin_port = rtp->them.sin_port;
1118 them->sin_addr = rtp->them.sin_addr;
1121 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1123 memcpy(us, &rtp->us, sizeof(rtp->us));
1126 void ast_rtp_stop(struct ast_rtp *rtp)
1128 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1129 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1131 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1132 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1136 void ast_rtp_reset(struct ast_rtp *rtp)
1138 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1139 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1140 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1142 rtp->lastdigitts = 0;
1144 rtp->lastividtimestamp = 0;
1145 rtp->lastovidtimestamp = 0;
1146 rtp->lasteventseqn = 0;
1147 rtp->lasteventendseqn = 0;
1148 rtp->lasttxformat = 0;
1149 rtp->lastrxformat = 0;
1151 rtp->dtmfduration = 0;
1156 void ast_rtp_destroy(struct ast_rtp *rtp)
1159 ast_smoother_free(rtp->smoother);
1161 ast_io_remove(rtp->io, rtp->ioid);
1165 close(rtp->rtcp->s);
1171 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1175 if (ast_tvzero(rtp->txcore)) {
1176 rtp->txcore = ast_tvnow();
1177 /* Round to 20ms for nice, pretty timestamps */
1178 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1180 /* Use previous txcore if available */
1181 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
1182 ms = ast_tvdiff_ms(t, rtp->txcore);
1185 /* Use what we just got for next time */
1187 return (unsigned int) ms;
1190 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
1192 unsigned int *rtpheader;
1198 char iabuf[INET_ADDRSTRLEN];
1200 if ((digit <= '9') && (digit >= '0'))
1202 else if (digit == '*')
1204 else if (digit == '#')
1206 else if ((digit >= 'A') && (digit <= 'D'))
1207 digit = digit - 'A' + 12;
1208 else if ((digit >= 'a') && (digit <= 'd'))
1209 digit = digit - 'a' + 12;
1211 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
1214 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
1216 /* If we have no peer, return immediately */
1217 if (!rtp->them.sin_addr.s_addr)
1220 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1222 /* Get a pointer to the header */
1223 rtpheader = (unsigned int *)data;
1224 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
1225 rtpheader[1] = htonl(rtp->lastdigitts);
1226 rtpheader[2] = htonl(rtp->ssrc);
1227 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
1228 for (x = 0; x < 6; x++) {
1229 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1230 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
1232 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
1233 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1234 ntohs(rtp->them.sin_port), strerror(errno));
1235 if (rtp_debug_test_addr(&rtp->them))
1236 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %u, ts %u, len %u)\n",
1237 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1238 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
1240 /* Sequence number of last two end packets does not get incremented */
1243 /* Clear marker bit and set seqno */
1244 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
1245 /* For the last three packets, set the duration and the end bit */
1248 /* No, this is wrong... Do not increment lastdigitts, that's not according
1249 to the RFC, as best we can determine */
1250 rtp->lastdigitts++; /* or else the SPA3000 will click instead of beeping... */
1251 rtpheader[1] = htonl(rtp->lastdigitts);
1253 /* Make duration 800 (100ms) */
1254 rtpheader[3] |= htonl((800));
1255 /* Set the End bit */
1256 rtpheader[3] |= htonl((1 << 23));
1259 /* Increment the digit timestamp by 120ms, to ensure that digits
1260 sent sequentially with no intervening non-digit packets do not
1261 get sent with the same timestamp, and that sequential digits
1262 have some 'dead air' in between them
1264 rtp->lastdigitts += 960;
1265 /* Increment the sequence number to reflect the last packet
1272 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
1274 unsigned int *rtpheader;
1279 char iabuf[INET_ADDRSTRLEN];
1280 level = 127 - (level & 0x7f);
1281 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
1283 /* If we have no peer, return immediately */
1284 if (!rtp->them.sin_addr.s_addr)
1287 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1289 /* Get a pointer to the header */
1290 rtpheader = (unsigned int *)data;
1291 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
1292 rtpheader[1] = htonl(rtp->lastts);
1293 rtpheader[2] = htonl(rtp->ssrc);
1295 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1296 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1298 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));
1299 if(rtp_debug_test_addr(&rtp->them))
1300 ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %d, len %d)\n"
1301 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
1307 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
1309 unsigned char *rtpheader;
1310 char iabuf[INET_ADDRSTRLEN];
1317 ms = calc_txstamp(rtp, &f->delivery);
1318 /* Default prediction */
1319 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
1320 pred = rtp->lastts + f->samples;
1322 /* Re-calculate last TS */
1323 rtp->lastts = rtp->lastts + ms * 8;
1324 if (ast_tvzero(f->delivery)) {
1325 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
1326 and if so, go with our prediction */
1327 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
1330 if (option_debug > 2)
1331 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
1336 mark = f->subclass & 0x1;
1337 pred = rtp->lastovidtimestamp + f->samples;
1338 /* Re-calculate last TS */
1339 rtp->lastts = rtp->lastts + ms * 90;
1340 /* If it's close to our prediction, go for it */
1341 if (ast_tvzero(f->delivery)) {
1342 if (abs(rtp->lastts - pred) < 7200) {
1344 rtp->lastovidtimestamp += f->samples;
1346 if (option_debug > 2)
1347 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);
1348 rtp->lastovidtimestamp = rtp->lastts;
1352 /* If the timestamp for non-digit packets has moved beyond the timestamp
1353 for digits, update the digit timestamp.
1355 if (rtp->lastts > rtp->lastdigitts)
1356 rtp->lastdigitts = rtp->lastts;
1358 /* Get a pointer to the header */
1359 rtpheader = (unsigned char *)(f->data - hdrlen);
1361 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
1362 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
1363 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
1365 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1366 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1368 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1369 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));
1370 } else if ((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) {
1371 /* Only give this error message once if we are not RTP debugging */
1372 if (option_debug || rtpdebug)
1373 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));
1374 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
1378 if(rtp_debug_test_addr(&rtp->them))
1379 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %u, ts %u, len %u)\n"
1380 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
1388 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
1390 struct ast_frame *f;
1396 /* If we have no peer, return immediately */
1397 if (!rtp->them.sin_addr.s_addr)
1400 /* If there is no data length, return immediately */
1404 /* Make sure we have enough space for RTP header */
1405 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
1406 ast_log(LOG_WARNING, "RTP can only send voice\n");
1410 subclass = _f->subclass;
1411 if (_f->frametype == AST_FRAME_VIDEO)
1414 codec = ast_rtp_lookup_code(rtp, 1, subclass);
1416 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
1420 if (rtp->lasttxformat != subclass) {
1421 /* New format, reset the smoother */
1423 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
1424 rtp->lasttxformat = subclass;
1426 ast_smoother_free(rtp->smoother);
1427 rtp->smoother = NULL;
1432 case AST_FORMAT_SLINEAR:
1433 if (!rtp->smoother) {
1434 rtp->smoother = ast_smoother_new(320);
1436 if (!rtp->smoother) {
1437 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1440 ast_smoother_feed_be(rtp->smoother, _f);
1442 while((f = ast_smoother_read(rtp->smoother)))
1443 ast_rtp_raw_write(rtp, f, codec);
1445 case AST_FORMAT_ULAW:
1446 case AST_FORMAT_ALAW:
1447 if (!rtp->smoother) {
1448 rtp->smoother = ast_smoother_new(160);
1450 if (!rtp->smoother) {
1451 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1454 ast_smoother_feed(rtp->smoother, _f);
1456 while((f = ast_smoother_read(rtp->smoother)))
1457 ast_rtp_raw_write(rtp, f, codec);
1459 case AST_FORMAT_ADPCM:
1460 case AST_FORMAT_G726:
1461 if (!rtp->smoother) {
1462 rtp->smoother = ast_smoother_new(80);
1464 if (!rtp->smoother) {
1465 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1468 ast_smoother_feed(rtp->smoother, _f);
1470 while((f = ast_smoother_read(rtp->smoother)))
1471 ast_rtp_raw_write(rtp, f, codec);
1473 case AST_FORMAT_G729A:
1474 if (!rtp->smoother) {
1475 rtp->smoother = ast_smoother_new(20);
1477 ast_smoother_set_flags(rtp->smoother, AST_SMOOTHER_FLAG_G729);
1479 if (!rtp->smoother) {
1480 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
1483 ast_smoother_feed(rtp->smoother, _f);
1485 while((f = ast_smoother_read(rtp->smoother)))
1486 ast_rtp_raw_write(rtp, f, codec);
1488 case AST_FORMAT_GSM:
1489 if (!rtp->smoother) {
1490 rtp->smoother = ast_smoother_new(33);
1492 if (!rtp->smoother) {
1493 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
1496 ast_smoother_feed(rtp->smoother, _f);
1497 while((f = ast_smoother_read(rtp->smoother)))
1498 ast_rtp_raw_write(rtp, f, codec);
1500 case AST_FORMAT_ILBC:
1501 if (!rtp->smoother) {
1502 rtp->smoother = ast_smoother_new(50);
1504 if (!rtp->smoother) {
1505 ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
1508 ast_smoother_feed(rtp->smoother, _f);
1509 while((f = ast_smoother_read(rtp->smoother)))
1510 ast_rtp_raw_write(rtp, f, codec);
1513 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
1514 /* fall through to... */
1515 case AST_FORMAT_H261:
1516 case AST_FORMAT_H263:
1517 case AST_FORMAT_H263_PLUS:
1518 case AST_FORMAT_G723_1:
1519 case AST_FORMAT_LPC10:
1520 case AST_FORMAT_SPEEX:
1521 /* Don't buffer outgoing frames; send them one-per-packet: */
1522 if (_f->offset < hdrlen) {
1527 ast_rtp_raw_write(rtp, f, codec);
1533 /*! \brief Unregister interface to channel driver */
1534 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
1536 struct ast_rtp_protocol *cur;
1538 AST_LIST_LOCK(&protos);
1539 AST_LIST_TRAVERSE_SAFE_BEGIN(&protos, cur, list) {
1541 AST_LIST_REMOVE_CURRENT(&protos, list);
1545 AST_LIST_TRAVERSE_SAFE_END
1546 AST_LIST_UNLOCK(&protos);
1549 /*! \brief Register interface to channel driver */
1550 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
1552 struct ast_rtp_protocol *cur;
1554 AST_LIST_LOCK(&protos);
1555 AST_LIST_TRAVERSE(&protos, cur, list) {
1556 if (cur->type == proto->type) {
1557 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1558 AST_LIST_UNLOCK(&protos);
1562 AST_LIST_INSERT_HEAD(&protos, proto, list);
1563 AST_LIST_UNLOCK(&protos);
1568 /*! \brief Bridge calls. If possible and allowed, initiate
1569 re-invite so the peers exchange media directly outside
1571 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)
1573 struct ast_frame *f;
1574 struct ast_channel *who, *cs[3];
1575 struct ast_rtp *p0, *p1; /* Audio RTP Channels */
1576 struct ast_rtp *vp0, *vp1; /* Video RTP channels */
1577 struct ast_rtp_protocol *pr0, *pr1;
1578 struct sockaddr_in ac0, ac1;
1579 struct sockaddr_in vac0, vac1;
1580 struct sockaddr_in t0, t1;
1581 struct sockaddr_in vt0, vt1;
1582 char iabuf[INET_ADDRSTRLEN];
1585 int codec0,codec1, oldcodec0, oldcodec1;
1587 memset(&vt0, 0, sizeof(vt0));
1588 memset(&vt1, 0, sizeof(vt1));
1589 memset(&vac0, 0, sizeof(vac0));
1590 memset(&vac1, 0, sizeof(vac1));
1592 /* if need DTMF, cant native bridge */
1593 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
1594 return AST_BRIDGE_FAILED_NOWARN;
1597 ast_mutex_lock(&c0->lock);
1598 while(ast_mutex_trylock(&c1->lock)) {
1599 ast_mutex_unlock(&c0->lock);
1601 ast_mutex_lock(&c0->lock);
1604 /* Find channel driver interfaces */
1605 pr0 = get_proto(c0);
1606 pr1 = get_proto(c1);
1608 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
1609 ast_mutex_unlock(&c0->lock);
1610 ast_mutex_unlock(&c1->lock);
1611 return AST_BRIDGE_FAILED;
1614 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1615 ast_mutex_unlock(&c0->lock);
1616 ast_mutex_unlock(&c1->lock);
1617 return AST_BRIDGE_FAILED;
1620 /* Get channel specific interface structures */
1621 pvt0 = c0->tech_pvt;
1622 pvt1 = c1->tech_pvt;
1624 /* Get audio and video interface (if native bridge is possible) */
1625 p0 = pr0->get_rtp_info(c0);
1626 if (pr0->get_vrtp_info)
1627 vp0 = pr0->get_vrtp_info(c0);
1630 p1 = pr1->get_rtp_info(c1);
1631 if (pr1->get_vrtp_info)
1632 vp1 = pr1->get_vrtp_info(c1);
1636 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1638 /* Somebody doesn't want to play... */
1639 ast_mutex_unlock(&c0->lock);
1640 ast_mutex_unlock(&c1->lock);
1641 return AST_BRIDGE_FAILED_NOWARN;
1643 /* Get codecs from both sides */
1645 codec0 = pr0->get_codec(c0);
1649 codec1 = pr1->get_codec(c1);
1652 if (pr0->get_codec && pr1->get_codec) {
1653 /* Hey, we can't do reinvite if both parties speak different codecs */
1654 if (!(codec0 & codec1)) {
1656 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
1657 ast_mutex_unlock(&c0->lock);
1658 ast_mutex_unlock(&c1->lock);
1659 return AST_BRIDGE_FAILED_NOWARN;
1663 /* Ok, we should be able to redirect the media. Start with one channel */
1664 if (pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
1665 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1667 /* Store RTP peer */
1668 ast_rtp_get_peer(p1, &ac1);
1670 ast_rtp_get_peer(vp1, &vac1);
1672 /* Then test the other channel */
1673 if (pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
1674 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1676 /* Store RTP peer */
1677 ast_rtp_get_peer(p0, &ac0);
1679 ast_rtp_get_peer(vp0, &vac0);
1681 ast_mutex_unlock(&c0->lock);
1682 ast_mutex_unlock(&c1->lock);
1683 /* External RTP Bridge up, now loop and see if something happes that force us to take the
1684 media back to Asterisk */
1691 /* Check if something changed... */
1692 if ((c0->tech_pvt != pvt0) ||
1693 (c1->tech_pvt != pvt1) ||
1694 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1695 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
1696 if (c0->tech_pvt == pvt0) {
1697 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
1698 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
1700 if (c1->tech_pvt == pvt1) {
1701 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
1702 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
1704 return AST_BRIDGE_RETRY;
1706 /* Now check if they have changed address */
1707 ast_rtp_get_peer(p1, &t1);
1708 ast_rtp_get_peer(p0, &t0);
1710 codec0 = pr0->get_codec(c0);
1712 codec1 = pr1->get_codec(c1);
1714 ast_rtp_get_peer(vp1, &vt1);
1716 ast_rtp_get_peer(vp0, &vt0);
1717 if (inaddrcmp(&t1, &ac1) || (vp1 && inaddrcmp(&vt1, &vac1)) || (codec1 != oldcodec1)) {
1718 if (option_debug > 1) {
1719 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
1720 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t1.sin_addr), ntohs(t1.sin_port), codec1);
1721 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
1722 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vt1.sin_addr), ntohs(vt1.sin_port), codec1);
1723 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1724 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
1725 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1726 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
1728 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)))
1729 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
1730 memcpy(&ac1, &t1, sizeof(ac1));
1731 memcpy(&vac1, &vt1, sizeof(vac1));
1734 if (inaddrcmp(&t0, &ac0) || (vp0 && inaddrcmp(&vt0, &vac0))) {
1736 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
1737 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t0.sin_addr), ntohs(t0.sin_port), codec0);
1738 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1739 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
1741 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)))
1742 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
1743 memcpy(&ac0, &t0, sizeof(ac0));
1744 memcpy(&vac0, &vt0, sizeof(vac0));
1747 who = ast_waitfor_n(cs, 2, &timeoutms);
1750 return AST_BRIDGE_RETRY;
1752 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
1753 /* check for hangup / whentohangup */
1754 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1759 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
1760 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
1761 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
1765 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
1766 if ((c0->tech_pvt == pvt0)) {
1767 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
1768 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
1770 if ((c1->tech_pvt == pvt1)) {
1771 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
1772 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
1774 return AST_BRIDGE_COMPLETE;
1775 } else if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1776 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
1777 (f->subclass == AST_CONTROL_VIDUPDATE)) {
1778 ast_indicate(who == c0 ? c1 : c0, f->subclass);
1783 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
1784 return AST_BRIDGE_COMPLETE;
1787 if ((f->frametype == AST_FRAME_DTMF) ||
1788 (f->frametype == AST_FRAME_VOICE) ||
1789 (f->frametype == AST_FRAME_VIDEO)) {
1790 /* Forward voice or DTMF frames if they happen upon us */
1793 } else if (who == c1) {
1799 /* Swap priority not that it's a big deal at this point */
1805 return AST_BRIDGE_FAILED;
1808 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
1811 struct ast_hostent ahp;
1812 char iabuf[INET_ADDRSTRLEN];
1817 return RESULT_SHOWUSAGE;
1819 p = strstr(arg, ":");
1825 hp = ast_gethostbyname(arg, &ahp);
1827 return RESULT_SHOWUSAGE;
1828 rtpdebugaddr.sin_family = AF_INET;
1829 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
1830 rtpdebugaddr.sin_port = htons(port);
1832 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr));
1834 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr), port);
1836 return RESULT_SUCCESS;
1839 static int rtp_do_debug(int fd, int argc, char *argv[])
1843 return RESULT_SHOWUSAGE;
1844 return rtp_do_debug_ip(fd, argc, argv);
1847 memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
1848 ast_cli(fd, "RTP Debugging Enabled\n");
1849 return RESULT_SUCCESS;
1852 static int rtp_no_debug(int fd, int argc, char *argv[])
1855 return RESULT_SHOWUSAGE;
1857 ast_cli(fd,"RTP Debugging Disabled\n");
1858 return RESULT_SUCCESS;
1861 static char debug_usage[] =
1862 "Usage: rtp debug [ip host[:port]]\n"
1863 " Enable dumping of all RTP packets to and from host.\n";
1865 static char no_debug_usage[] =
1866 "Usage: rtp no debug\n"
1867 " Disable all RTP debugging\n";
1869 static struct ast_cli_entry cli_debug_ip =
1870 {{ "rtp", "debug", "ip", NULL } , rtp_do_debug, "Enable RTP debugging on IP", debug_usage };
1872 static struct ast_cli_entry cli_debug =
1873 {{ "rtp", "debug", NULL } , rtp_do_debug, "Enable RTP debugging", debug_usage };
1875 static struct ast_cli_entry cli_no_debug =
1876 {{ "rtp", "no", "debug", NULL } , rtp_no_debug, "Disable RTP debugging", no_debug_usage };
1878 void ast_rtp_reload(void)
1880 struct ast_config *cfg;
1885 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
1886 cfg = ast_config_load("rtp.conf");
1888 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
1890 if (rtpstart < 1024)
1892 if (rtpstart > 65535)
1895 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
1902 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
1910 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
1913 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
1914 dtmftimeout = atoi(s);
1915 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
1916 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
1917 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
1918 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
1921 ast_config_destroy(cfg);
1923 if (rtpstart >= rtpend) {
1924 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
1928 if (option_verbose > 1)
1929 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
1933 /*! \brief Initialize the RTP system in Asterisk */
1934 void ast_rtp_init(void)
1936 ast_cli_register(&cli_debug);
1937 ast_cli_register(&cli_debug_ip);
1938 ast_cli_register(&cli_no_debug);