2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
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 char iabuf[INET_ADDRSTRLEN];
179 if (ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
181 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
183 rtp->dtmfduration = 0;
184 return &ast_null_frame;
187 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));
188 if (rtp->resp == 'X') {
189 rtp->f.frametype = AST_FRAME_CONTROL;
190 rtp->f.subclass = AST_CONTROL_FLASH;
192 rtp->f.frametype = AST_FRAME_DTMF;
193 rtp->f.subclass = rtp->resp;
200 rtp->dtmfduration = 0;
205 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
209 if (rtpdebugaddr.sin_addr.s_addr) {
210 if (((ntohs(rtpdebugaddr.sin_port) != 0)
211 && (rtpdebugaddr.sin_port != addr->sin_port))
212 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
218 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
222 struct ast_frame *f = NULL;
223 event = ntohl(*((unsigned int *)(data)));
225 if (option_debug > 2 || rtpdebug)
226 ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
229 } else if (event < 11) {
231 } else if (event < 12) {
233 } else if (event < 16) {
234 resp = 'A' + (event - 12);
235 } else if (event < 17) {
238 if (rtp->resp && (rtp->resp != resp)) {
242 rtp->dtmfcount = dtmftimeout;
247 * \brief Process RTP DTMF and events according to RFC 2833.
249 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
257 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
260 unsigned int event_end;
261 unsigned int duration;
263 struct ast_frame *f = NULL;
265 event = ntohl(*((unsigned int *)(data)));
267 event_end = ntohl(*((unsigned int *)(data)));
270 duration = ntohl(*((unsigned int *)(data)));
272 if (rtpdebug || option_debug > 2)
273 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
276 } else if (event < 11) {
278 } else if (event < 12) {
280 } else if (event < 16) {
281 resp = 'A' + (event - 12);
282 } else if (event < 17) { /* Event 16: Hook flash */
285 if (rtp->resp && (rtp->resp != resp)) {
287 } else if(event_end & 0x80) {
289 if(rtp->lasteventendseqn != seqno) {
291 rtp->lasteventendseqn = seqno;
297 } else if (rtp->resp && rtp->dtmfduration && (duration < rtp->dtmfduration)) {
300 if (!(event_end & 0x80))
302 rtp->dtmfcount = dtmftimeout;
303 rtp->dtmfduration = duration;
308 * \brief Process Comfort Noise RTP.
310 * This is incomplete at the moment.
313 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
315 struct ast_frame *f = NULL;
316 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
317 totally help us out becuase we don't have an engine to keep it going and we are not
318 guaranteed to have it every 20ms or anything */
320 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
322 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
323 char iabuf[INET_ADDRSTRLEN];
325 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
326 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
327 ast_set_flag(rtp, FLAG_3389_WARNING);
330 /* Must have at least one byte */
334 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
335 rtp->f.datalen = len - 1;
336 rtp->f.offset = AST_FRIENDLY_OFFSET;
337 memcpy(rtp->f.data, data + 1, len - 1);
343 rtp->f.frametype = AST_FRAME_CNG;
344 rtp->f.subclass = data[0] & 0x7f;
345 rtp->f.datalen = len - 1;
347 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
352 static int rtpread(int *id, int fd, short events, void *cbdata)
354 struct ast_rtp *rtp = cbdata;
356 f = ast_rtp_read(rtp);
359 rtp->callback(rtp, f, rtp->data);
364 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
369 struct sockaddr_in sin;
370 unsigned int rtcpdata[1024];
371 char iabuf[INET_ADDRSTRLEN];
373 if (!rtp || !rtp->rtcp)
374 return &ast_null_frame;
378 res = recvfrom(rtp->rtcp->s, rtcpdata, sizeof(rtcpdata),
379 0, (struct sockaddr *)&sin, &len);
383 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
386 return &ast_null_frame;
390 ast_log(LOG_WARNING, "RTP Read too short\n");
391 return &ast_null_frame;
395 /* Send to whoever sent to us */
396 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
397 (rtp->rtcp->them.sin_port != sin.sin_port)) {
398 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
399 if (option_debug || rtpdebug)
400 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));
404 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
405 return &ast_null_frame;
408 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
410 struct timeval ts = ast_samp2tv( timestamp, 8000);
411 if (ast_tvzero(rtp->rxcore) || mark) {
412 rtp->rxcore = ast_tvsub(ast_tvnow(), ts);
413 /* Round to 20ms for nice, pretty timestamps */
414 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 20000;
416 *tv = ast_tvadd(rtp->rxcore, ts);
419 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
422 struct sockaddr_in sin;
432 char iabuf[INET_ADDRSTRLEN];
433 unsigned int timestamp;
434 unsigned int *rtpheader;
435 static struct ast_frame *f;
436 struct rtpPayloadType rtpPT;
440 /* Cache where the header will go */
441 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
442 0, (struct sockaddr *)&sin, &len);
445 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
448 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
451 return &ast_null_frame;
454 ast_log(LOG_WARNING, "RTP Read too short\n");
455 return &ast_null_frame;
458 /* Ignore if the other side hasn't been given an address
460 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
461 return &ast_null_frame;
464 /* Send to whoever sent to us */
465 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
466 (rtp->them.sin_port != sin.sin_port)) {
467 memcpy(&rtp->them, &sin, sizeof(rtp->them));
469 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
470 if (option_debug || rtpdebug)
471 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));
476 seqno = ntohl(rtpheader[0]);
478 /* Check RTP version */
479 version = (seqno & 0xC0000000) >> 30;
481 return &ast_null_frame;
483 payloadtype = (seqno & 0x7f0000) >> 16;
484 padding = seqno & (1 << 29);
485 mark = seqno & (1 << 23);
486 ext = seqno & (1 << 28);
488 timestamp = ntohl(rtpheader[1]);
491 /* Remove padding bytes */
492 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
496 /* RTP Extension present */
498 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
502 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
503 return &ast_null_frame;
506 if(rtp_debug_test_addr(&sin))
507 ast_verbose("Got RTP packet from %s:%d (type %d, seq %d, ts %d, len %d)\n"
508 , ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
510 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
511 if (!rtpPT.isAstFormat) {
512 /* This is special in-band data that's not one of our codecs */
513 if (rtpPT.code == AST_RTP_DTMF) {
514 /* It's special -- rfc2833 process it */
515 if(rtp_debug_test_addr(&sin)) {
518 unsigned int event_end;
519 unsigned int duration;
520 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
521 event = ntohl(*((unsigned int *)(data)));
523 event_end = ntohl(*((unsigned int *)(data)));
526 duration = ntohl(*((unsigned int *)(data)));
528 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);
530 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
531 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
532 rtp->lasteventseqn = seqno;
538 return &ast_null_frame;
539 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
540 /* It's really special -- process it the Cisco way */
541 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
542 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
543 rtp->lasteventseqn = seqno;
549 return &ast_null_frame;
550 } else if (rtpPT.code == AST_RTP_CN) {
552 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
556 return &ast_null_frame;
558 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
559 return &ast_null_frame;
562 rtp->f.subclass = rtpPT.code;
563 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO)
564 rtp->f.frametype = AST_FRAME_VOICE;
566 rtp->f.frametype = AST_FRAME_VIDEO;
567 rtp->lastrxformat = rtp->f.subclass;
570 rtp->lastrxts = timestamp;
573 for (x=rtp->rxseqno + 1; x < seqno; x++) {
574 /* Queue empty frames */
580 rtp->f.src = "RTPMissedFrame";
583 rtp->rxseqno = seqno;
585 if (rtp->dtmfcount) {
587 printf("dtmfcount was %d\n", rtp->dtmfcount);
589 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
590 if (rtp->dtmfcount < 0)
593 if (dtmftimeout != rtp->dtmfcount)
594 printf("dtmfcount is %d\n", rtp->dtmfcount);
597 rtp->lastrxts = timestamp;
599 /* Send any pending DTMF */
600 if (rtp->resp && !rtp->dtmfcount) {
602 ast_log(LOG_DEBUG, "Sending pending DTMF\n");
603 return send_dtmf(rtp);
606 rtp->f.datalen = res - hdrlen;
607 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
608 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
609 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
610 rtp->f.samples = ast_codec_get_samples(&rtp->f);
611 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
612 ast_frame_byteswap_be(&rtp->f);
613 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
615 /* Video -- samples is # of samples vs. 90000 */
616 if (!rtp->lastividtimestamp)
617 rtp->lastividtimestamp = timestamp;
618 rtp->f.samples = timestamp - rtp->lastividtimestamp;
619 rtp->lastividtimestamp = timestamp;
620 rtp->f.delivery.tv_sec = 0;
621 rtp->f.delivery.tv_usec = 0;
623 rtp->f.subclass |= 0x1;
630 /* The following array defines the MIME Media type (and subtype) for each
631 of our codecs, or RTP-specific data type. */
633 struct rtpPayloadType payloadType;
637 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
638 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
639 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
640 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
641 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
642 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
643 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
644 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
645 {{1, AST_FORMAT_G729A}, "audio", "G729"},
646 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
647 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
648 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
649 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
650 {{0, AST_RTP_CN}, "audio", "CN"},
651 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
652 {{1, AST_FORMAT_PNG}, "video", "PNG"},
653 {{1, AST_FORMAT_H261}, "video", "H261"},
654 {{1, AST_FORMAT_H263}, "video", "H263"},
655 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
656 {{1, AST_FORMAT_H264}, "video", "H264"},
659 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
660 also, our own choices for dynamic payload types. This is our master
661 table for transmission */
662 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
663 [0] = {1, AST_FORMAT_ULAW},
664 #ifdef USE_DEPRECATED_G726
665 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
667 [3] = {1, AST_FORMAT_GSM},
668 [4] = {1, AST_FORMAT_G723_1},
669 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
670 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
671 [7] = {1, AST_FORMAT_LPC10},
672 [8] = {1, AST_FORMAT_ALAW},
673 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
674 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
675 [13] = {0, AST_RTP_CN},
676 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
677 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
678 [18] = {1, AST_FORMAT_G729A},
679 [19] = {0, AST_RTP_CN}, /* Also used for CN */
680 [26] = {1, AST_FORMAT_JPEG},
681 [31] = {1, AST_FORMAT_H261},
682 [34] = {1, AST_FORMAT_H263},
683 [103] = {1, AST_FORMAT_H263_PLUS},
684 [97] = {1, AST_FORMAT_ILBC},
685 [99] = {1, AST_FORMAT_H264},
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 = NULL;
743 AST_LIST_LOCK(&protos);
744 AST_LIST_TRAVERSE(&protos, cur, list) {
745 if (cur->type == chan->tech->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 vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
787 srcp = srcpr->get_rtp_info(src);
788 vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
790 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
791 if (!destp || !srcp) {
792 /* Somebody doesn't want to play... */
793 ast_mutex_unlock(&dest->lock);
794 ast_mutex_unlock(&src->lock);
797 ast_rtp_pt_copy(destp, srcp);
799 ast_rtp_pt_copy(vdestp, vsrcp);
800 ast_mutex_unlock(&dest->lock);
801 ast_mutex_unlock(&src->lock);
803 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
807 /*! \brief Make a note of a RTP paymoad type that was seen in a SDP "m=" line.
808 * By default, use the well-known value for this type (although it may
809 * still be set to a different value by a subsequent "a=rtpmap:" line)
811 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
813 if (pt < 0 || pt > MAX_RTP_PT)
814 return; /* bogus payload type */
816 if (static_RTP_PT[pt].code != 0) {
817 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
821 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
822 a SDP "a=rtpmap:" line. */
823 void ast_rtp_set_rtpmap_type(struct ast_rtp* rtp, int pt,
824 char* mimeType, char* mimeSubtype)
828 if (pt < 0 || pt > MAX_RTP_PT)
829 return; /* bogus payload type */
831 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
832 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
833 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
834 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
840 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
841 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
842 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
843 int* astFormats, int* nonAstFormats) {
846 *astFormats = *nonAstFormats = 0;
847 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
848 if (rtp->current_RTP_PT[pt].isAstFormat) {
849 *astFormats |= rtp->current_RTP_PT[pt].code;
851 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
856 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
858 struct rtpPayloadType result;
860 result.isAstFormat = result.code = 0;
861 if (pt < 0 || pt > MAX_RTP_PT)
862 return result; /* bogus payload type */
864 /* Start with the negotiated codecs */
865 result = rtp->current_RTP_PT[pt];
867 /* If it doesn't exist, check our static RTP type list, just in case */
869 result = static_RTP_PT[pt];
873 /*! \brief Looks up an RTP code out of our *static* outbound list */
874 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
878 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
879 code == rtp->rtp_lookup_code_cache_code) {
881 /* Use our cached mapping, to avoid the overhead of the loop below */
882 return rtp->rtp_lookup_code_cache_result;
885 /* Check the dynamic list first */
886 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
887 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
888 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
889 rtp->rtp_lookup_code_cache_code = code;
890 rtp->rtp_lookup_code_cache_result = pt;
895 /* Then the static list */
896 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
897 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
898 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
899 rtp->rtp_lookup_code_cache_code = code;
900 rtp->rtp_lookup_code_cache_result = pt;
907 char* ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code)
912 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
913 if (mimeTypes[i].payloadType.code == code && mimeTypes[i].payloadType.isAstFormat == isAstFormat)
914 return mimeTypes[i].subtype;
919 char *ast_rtp_lookup_mime_multiple(char *buf, int size, const int capability, const int isAstFormat)
929 snprintf(end, size, "0x%x (", capability);
936 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
937 if (capability & format) {
938 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format);
939 snprintf(end, size, "%s|", name);
947 snprintf(start, size, "nothing)");
954 static int rtp_socket(void)
958 s = socket(AF_INET, SOCK_DGRAM, 0);
960 flags = fcntl(s, F_GETFL);
961 fcntl(s, F_SETFL, flags | O_NONBLOCK);
964 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
971 * \brief Initialize a new RTCP session.
973 * \returns The newly initialized RTCP session.
975 static struct ast_rtcp *ast_rtcp_new(void)
977 struct ast_rtcp *rtcp;
979 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
981 rtcp->s = rtp_socket();
982 rtcp->us.sin_family = AF_INET;
985 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
992 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
999 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
1001 rtp->them.sin_family = AF_INET;
1002 rtp->us.sin_family = AF_INET;
1003 rtp->s = rtp_socket();
1004 rtp->ssrc = ast_random();
1005 rtp->seqno = ast_random() & 0xffff;
1008 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1011 if (sched && rtcpenable) {
1013 rtp->rtcp = ast_rtcp_new();
1016 /* Select a random port number in the range of possible RTP */
1017 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
1019 /* Save it for future references. */
1021 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1023 /* Must be an even port number by RTP spec */
1024 rtp->us.sin_port = htons(x);
1025 rtp->us.sin_addr = addr;
1026 /* If there's rtcp, initialize it as well. */
1028 rtp->rtcp->us.sin_port = htons(x + 1);
1029 /* Try to bind it/them. */
1030 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1031 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1034 /* Primary bind succeeded! Gotta recreate it */
1036 rtp->s = rtp_socket();
1038 if (errno != EADDRINUSE) {
1039 /* We got an error that wasn't expected, abort! */
1040 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1043 close(rtp->rtcp->s);
1049 /* The port was used, increment it (by two). */
1051 /* Did we go over the limit ? */
1053 /* then, start from the begingig. */
1054 x = (rtpstart + 1) & ~1;
1055 /* Check if we reached the place were we started. */
1056 if (x == startplace) {
1057 /* If so, there's no ports available. */
1058 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1061 close(rtp->rtcp->s);
1068 if (io && sched && callbackmode) {
1069 /* Operate this one in a callback mode */
1072 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1074 ast_rtp_pt_default(rtp);
1078 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1082 memset(&ia, 0, sizeof(ia));
1083 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1086 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1090 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1091 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1095 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1097 rtp->them.sin_port = them->sin_port;
1098 rtp->them.sin_addr = them->sin_addr;
1100 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1101 rtp->rtcp->them.sin_addr = them->sin_addr;
1106 void ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1108 them->sin_family = AF_INET;
1109 them->sin_port = rtp->them.sin_port;
1110 them->sin_addr = rtp->them.sin_addr;
1113 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1118 void ast_rtp_stop(struct ast_rtp *rtp)
1120 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1121 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1123 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1124 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1128 void ast_rtp_reset(struct ast_rtp *rtp)
1130 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1131 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1132 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1134 rtp->lastdigitts = 0;
1136 rtp->lastividtimestamp = 0;
1137 rtp->lastovidtimestamp = 0;
1138 rtp->lasteventseqn = 0;
1139 rtp->lasteventendseqn = 0;
1140 rtp->lasttxformat = 0;
1141 rtp->lastrxformat = 0;
1143 rtp->dtmfduration = 0;
1148 void ast_rtp_destroy(struct ast_rtp *rtp)
1151 ast_smoother_free(rtp->smoother);
1153 ast_io_remove(rtp->io, rtp->ioid);
1157 close(rtp->rtcp->s);
1163 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1167 if (ast_tvzero(rtp->txcore)) {
1168 rtp->txcore = ast_tvnow();
1169 /* Round to 20ms for nice, pretty timestamps */
1170 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1172 /* Use previous txcore if available */
1173 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
1174 ms = ast_tvdiff_ms(t, rtp->txcore);
1177 /* Use what we just got for next time */
1179 return (unsigned int) ms;
1182 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
1184 unsigned int *rtpheader;
1190 char iabuf[INET_ADDRSTRLEN];
1192 if ((digit <= '9') && (digit >= '0'))
1194 else if (digit == '*')
1196 else if (digit == '#')
1198 else if ((digit >= 'A') && (digit <= 'D'))
1199 digit = digit - 'A' + 12;
1200 else if ((digit >= 'a') && (digit <= 'd'))
1201 digit = digit - 'a' + 12;
1203 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
1206 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
1208 /* If we have no peer, return immediately */
1209 if (!rtp->them.sin_addr.s_addr)
1212 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1214 /* Get a pointer to the header */
1215 rtpheader = (unsigned int *)data;
1216 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
1217 rtpheader[1] = htonl(rtp->lastdigitts);
1218 rtpheader[2] = htonl(rtp->ssrc);
1219 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
1220 for (x = 0; x < 6; x++) {
1221 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1222 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
1224 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
1225 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1226 ntohs(rtp->them.sin_port), strerror(errno));
1227 if (rtp_debug_test_addr(&rtp->them))
1228 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %u, ts %u, len %u)\n",
1229 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1230 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
1232 /* Sequence number of last two end packets does not get incremented */
1235 /* Clear marker bit and set seqno */
1236 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
1237 /* For the last three packets, set the duration and the end bit */
1240 /* No, this is wrong... Do not increment lastdigitts, that's not according
1241 to the RFC, as best we can determine */
1242 rtp->lastdigitts++; /* or else the SPA3000 will click instead of beeping... */
1243 rtpheader[1] = htonl(rtp->lastdigitts);
1245 /* Make duration 800 (100ms) */
1246 rtpheader[3] |= htonl((800));
1247 /* Set the End bit */
1248 rtpheader[3] |= htonl((1 << 23));
1251 /* Increment the digit timestamp by 120ms, to ensure that digits
1252 sent sequentially with no intervening non-digit packets do not
1253 get sent with the same timestamp, and that sequential digits
1254 have some 'dead air' in between them
1256 rtp->lastdigitts += 960;
1257 /* Increment the sequence number to reflect the last packet
1264 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
1266 unsigned int *rtpheader;
1271 char iabuf[INET_ADDRSTRLEN];
1272 level = 127 - (level & 0x7f);
1273 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
1275 /* If we have no peer, return immediately */
1276 if (!rtp->them.sin_addr.s_addr)
1279 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1281 /* Get a pointer to the header */
1282 rtpheader = (unsigned int *)data;
1283 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
1284 rtpheader[1] = htonl(rtp->lastts);
1285 rtpheader[2] = htonl(rtp->ssrc);
1287 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1288 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1290 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));
1291 if(rtp_debug_test_addr(&rtp->them))
1292 ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %d, len %d)\n"
1293 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
1299 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
1301 unsigned char *rtpheader;
1302 char iabuf[INET_ADDRSTRLEN];
1309 ms = calc_txstamp(rtp, &f->delivery);
1310 /* Default prediction */
1311 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
1312 pred = rtp->lastts + f->samples;
1314 /* Re-calculate last TS */
1315 rtp->lastts = rtp->lastts + ms * 8;
1316 if (ast_tvzero(f->delivery)) {
1317 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
1318 and if so, go with our prediction */
1319 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
1322 if (option_debug > 2)
1323 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
1328 mark = f->subclass & 0x1;
1329 pred = rtp->lastovidtimestamp + f->samples;
1330 /* Re-calculate last TS */
1331 rtp->lastts = rtp->lastts + ms * 90;
1332 /* If it's close to our prediction, go for it */
1333 if (ast_tvzero(f->delivery)) {
1334 if (abs(rtp->lastts - pred) < 7200) {
1336 rtp->lastovidtimestamp += f->samples;
1338 if (option_debug > 2)
1339 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);
1340 rtp->lastovidtimestamp = rtp->lastts;
1344 /* If the timestamp for non-digit packets has moved beyond the timestamp
1345 for digits, update the digit timestamp.
1347 if (rtp->lastts > rtp->lastdigitts)
1348 rtp->lastdigitts = rtp->lastts;
1350 /* Get a pointer to the header */
1351 rtpheader = (unsigned char *)(f->data - hdrlen);
1353 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
1354 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
1355 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
1357 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1358 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1360 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1361 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));
1362 } else if ((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) {
1363 /* Only give this error message once if we are not RTP debugging */
1364 if (option_debug || rtpdebug)
1365 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));
1366 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
1370 if(rtp_debug_test_addr(&rtp->them))
1371 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %u, ts %u, len %u)\n"
1372 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
1380 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
1382 struct ast_frame *f;
1388 /* If we have no peer, return immediately */
1389 if (!rtp->them.sin_addr.s_addr)
1392 /* If there is no data length, return immediately */
1396 /* Make sure we have enough space for RTP header */
1397 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
1398 ast_log(LOG_WARNING, "RTP can only send voice\n");
1402 subclass = _f->subclass;
1403 if (_f->frametype == AST_FRAME_VIDEO)
1406 codec = ast_rtp_lookup_code(rtp, 1, subclass);
1408 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
1412 if (rtp->lasttxformat != subclass) {
1413 /* New format, reset the smoother */
1415 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
1416 rtp->lasttxformat = subclass;
1418 ast_smoother_free(rtp->smoother);
1419 rtp->smoother = NULL;
1424 case AST_FORMAT_SLINEAR:
1425 if (!rtp->smoother) {
1426 rtp->smoother = ast_smoother_new(320);
1428 if (!rtp->smoother) {
1429 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1432 ast_smoother_feed_be(rtp->smoother, _f);
1434 while((f = ast_smoother_read(rtp->smoother)))
1435 ast_rtp_raw_write(rtp, f, codec);
1437 case AST_FORMAT_ULAW:
1438 case AST_FORMAT_ALAW:
1439 if (!rtp->smoother) {
1440 rtp->smoother = ast_smoother_new(160);
1442 if (!rtp->smoother) {
1443 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1446 ast_smoother_feed(rtp->smoother, _f);
1448 while((f = ast_smoother_read(rtp->smoother)))
1449 ast_rtp_raw_write(rtp, f, codec);
1451 case AST_FORMAT_ADPCM:
1452 case AST_FORMAT_G726:
1453 if (!rtp->smoother) {
1454 rtp->smoother = ast_smoother_new(80);
1456 if (!rtp->smoother) {
1457 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1460 ast_smoother_feed(rtp->smoother, _f);
1462 while((f = ast_smoother_read(rtp->smoother)))
1463 ast_rtp_raw_write(rtp, f, codec);
1465 case AST_FORMAT_G729A:
1466 if (!rtp->smoother) {
1467 rtp->smoother = ast_smoother_new(20);
1469 ast_smoother_set_flags(rtp->smoother, AST_SMOOTHER_FLAG_G729);
1471 if (!rtp->smoother) {
1472 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
1475 ast_smoother_feed(rtp->smoother, _f);
1477 while((f = ast_smoother_read(rtp->smoother)))
1478 ast_rtp_raw_write(rtp, f, codec);
1480 case AST_FORMAT_GSM:
1481 if (!rtp->smoother) {
1482 rtp->smoother = ast_smoother_new(33);
1484 if (!rtp->smoother) {
1485 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
1488 ast_smoother_feed(rtp->smoother, _f);
1489 while((f = ast_smoother_read(rtp->smoother)))
1490 ast_rtp_raw_write(rtp, f, codec);
1492 case AST_FORMAT_ILBC:
1493 if (!rtp->smoother) {
1494 rtp->smoother = ast_smoother_new(50);
1496 if (!rtp->smoother) {
1497 ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
1500 ast_smoother_feed(rtp->smoother, _f);
1501 while((f = ast_smoother_read(rtp->smoother)))
1502 ast_rtp_raw_write(rtp, f, codec);
1505 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
1506 /* fall through to... */
1507 case AST_FORMAT_H261:
1508 case AST_FORMAT_H263:
1509 case AST_FORMAT_H263_PLUS:
1510 case AST_FORMAT_H264:
1511 case AST_FORMAT_G723_1:
1512 case AST_FORMAT_LPC10:
1513 case AST_FORMAT_SPEEX:
1514 /* Don't buffer outgoing frames; send them one-per-packet: */
1515 if (_f->offset < hdrlen) {
1520 ast_rtp_raw_write(rtp, f, codec);
1526 /*! \brief Unregister interface to channel driver */
1527 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
1529 AST_LIST_LOCK(&protos);
1530 AST_LIST_REMOVE(&protos, proto, list);
1531 AST_LIST_UNLOCK(&protos);
1534 /*! \brief Register interface to channel driver */
1535 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
1537 struct ast_rtp_protocol *cur;
1539 AST_LIST_LOCK(&protos);
1540 AST_LIST_TRAVERSE(&protos, cur, list) {
1541 if (!strcmp(cur->type, proto->type)) {
1542 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1543 AST_LIST_UNLOCK(&protos);
1547 AST_LIST_INSERT_HEAD(&protos, proto, list);
1548 AST_LIST_UNLOCK(&protos);
1553 /*! \brief Bridge calls. If possible and allowed, initiate
1554 re-invite so the peers exchange media directly outside
1556 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)
1558 struct ast_frame *f;
1559 struct ast_channel *who, *other, *cs[3];
1560 struct ast_rtp *p0, *p1; /* Audio RTP Channels */
1561 struct ast_rtp *vp0, *vp1; /* Video RTP channels */
1562 struct ast_rtp_protocol *pr0, *pr1;
1563 struct sockaddr_in ac0, ac1;
1564 struct sockaddr_in vac0, vac1;
1565 struct sockaddr_in t0, t1;
1566 struct sockaddr_in vt0, vt1;
1567 char iabuf[INET_ADDRSTRLEN];
1570 int codec0,codec1, oldcodec0, oldcodec1;
1572 memset(&vt0, 0, sizeof(vt0));
1573 memset(&vt1, 0, sizeof(vt1));
1574 memset(&vac0, 0, sizeof(vac0));
1575 memset(&vac1, 0, sizeof(vac1));
1577 /* if need DTMF, cant native bridge */
1578 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
1579 return AST_BRIDGE_FAILED_NOWARN;
1582 ast_mutex_lock(&c0->lock);
1583 while(ast_mutex_trylock(&c1->lock)) {
1584 ast_mutex_unlock(&c0->lock);
1586 ast_mutex_lock(&c0->lock);
1589 /* Find channel driver interfaces */
1590 pr0 = get_proto(c0);
1591 pr1 = get_proto(c1);
1593 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
1594 ast_mutex_unlock(&c0->lock);
1595 ast_mutex_unlock(&c1->lock);
1596 return AST_BRIDGE_FAILED;
1599 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1600 ast_mutex_unlock(&c0->lock);
1601 ast_mutex_unlock(&c1->lock);
1602 return AST_BRIDGE_FAILED;
1605 /* Get channel specific interface structures */
1606 pvt0 = c0->tech_pvt;
1607 pvt1 = c1->tech_pvt;
1609 /* Get audio and video interface (if native bridge is possible) */
1610 p0 = pr0->get_rtp_info(c0);
1611 vp0 = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0) : NULL;
1612 p1 = pr1->get_rtp_info(c1);
1613 vp1 = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1) : NULL;
1615 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1617 /* Somebody doesn't want to play... */
1618 ast_mutex_unlock(&c0->lock);
1619 ast_mutex_unlock(&c1->lock);
1620 return AST_BRIDGE_FAILED_NOWARN;
1622 /* Get codecs from both sides */
1623 codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
1624 codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
1625 if (pr0->get_codec && pr1->get_codec) {
1626 /* Hey, we can't do reinvite if both parties speak different codecs */
1627 if (!(codec0 & codec1)) {
1629 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
1630 ast_mutex_unlock(&c0->lock);
1631 ast_mutex_unlock(&c1->lock);
1632 return AST_BRIDGE_FAILED_NOWARN;
1636 if (option_verbose > 2)
1637 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
1639 /* Ok, we should be able to redirect the media. Start with one channel */
1640 if (pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
1641 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1643 /* Store RTP peer */
1644 ast_rtp_get_peer(p1, &ac1);
1646 ast_rtp_get_peer(vp1, &vac1);
1648 /* Then test the other channel */
1649 if (pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
1650 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1652 /* Store RTP peer */
1653 ast_rtp_get_peer(p0, &ac0);
1655 ast_rtp_get_peer(vp0, &vac0);
1657 ast_mutex_unlock(&c0->lock);
1658 ast_mutex_unlock(&c1->lock);
1659 /* External RTP Bridge up, now loop and see if something happes that force us to take the
1660 media back to Asterisk */
1667 /* Check if something changed... */
1668 if ((c0->tech_pvt != pvt0) ||
1669 (c1->tech_pvt != pvt1) ||
1670 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1671 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
1672 if (c0->tech_pvt == pvt0) {
1673 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
1674 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
1676 if (c1->tech_pvt == pvt1) {
1677 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
1678 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
1680 return AST_BRIDGE_RETRY;
1682 /* Now check if they have changed address */
1683 ast_rtp_get_peer(p1, &t1);
1684 ast_rtp_get_peer(p0, &t0);
1686 codec0 = pr0->get_codec(c0);
1688 codec1 = pr1->get_codec(c1);
1690 ast_rtp_get_peer(vp1, &vt1);
1692 ast_rtp_get_peer(vp0, &vt0);
1693 if (inaddrcmp(&t1, &ac1) || (vp1 && inaddrcmp(&vt1, &vac1)) || (codec1 != oldcodec1)) {
1694 if (option_debug > 1) {
1695 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
1696 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t1.sin_addr), ntohs(t1.sin_port), codec1);
1697 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
1698 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vt1.sin_addr), ntohs(vt1.sin_port), codec1);
1699 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1700 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
1701 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1702 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
1704 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)))
1705 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
1706 memcpy(&ac1, &t1, sizeof(ac1));
1707 memcpy(&vac1, &vt1, sizeof(vac1));
1710 if (inaddrcmp(&t0, &ac0) || (vp0 && inaddrcmp(&vt0, &vac0))) {
1712 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
1713 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t0.sin_addr), ntohs(t0.sin_port), codec0);
1714 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1715 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
1717 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)))
1718 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
1719 memcpy(&ac0, &t0, sizeof(ac0));
1720 memcpy(&vac0, &vt0, sizeof(vac0));
1723 who = ast_waitfor_n(cs, 2, &timeoutms);
1726 return AST_BRIDGE_RETRY;
1728 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
1729 /* check for hangup / whentohangup */
1730 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1735 other = (who == c0) ? c1 : c0; /* the other channel */
1736 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
1737 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
1738 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
1739 /* breaking out of the bridge. */
1743 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
1744 if ((c0->tech_pvt == pvt0)) {
1745 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
1746 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
1748 if ((c1->tech_pvt == pvt1)) {
1749 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
1750 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
1752 return AST_BRIDGE_COMPLETE;
1753 } else if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1754 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
1755 (f->subclass == AST_CONTROL_VIDUPDATE)) {
1756 ast_indicate(other, f->subclass);
1761 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
1762 return AST_BRIDGE_COMPLETE;
1765 if ((f->frametype == AST_FRAME_DTMF) ||
1766 (f->frametype == AST_FRAME_VOICE) ||
1767 (f->frametype == AST_FRAME_VIDEO)) {
1768 /* Forward voice or DTMF frames if they happen upon us */
1769 ast_write(other, f);
1773 /* Swap priority not that it's a big deal at this point */
1779 return AST_BRIDGE_FAILED;
1782 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
1785 struct ast_hostent ahp;
1786 char iabuf[INET_ADDRSTRLEN];
1791 return RESULT_SHOWUSAGE;
1793 p = strstr(arg, ":");
1799 hp = ast_gethostbyname(arg, &ahp);
1801 return RESULT_SHOWUSAGE;
1802 rtpdebugaddr.sin_family = AF_INET;
1803 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
1804 rtpdebugaddr.sin_port = htons(port);
1806 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr));
1808 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr), port);
1810 return RESULT_SUCCESS;
1813 static int rtp_do_debug(int fd, int argc, char *argv[])
1817 return RESULT_SHOWUSAGE;
1818 return rtp_do_debug_ip(fd, argc, argv);
1821 memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
1822 ast_cli(fd, "RTP Debugging Enabled\n");
1823 return RESULT_SUCCESS;
1826 static int rtp_no_debug(int fd, int argc, char *argv[])
1829 return RESULT_SHOWUSAGE;
1831 ast_cli(fd,"RTP Debugging Disabled\n");
1832 return RESULT_SUCCESS;
1835 static char debug_usage[] =
1836 "Usage: rtp debug [ip host[:port]]\n"
1837 " Enable dumping of all RTP packets to and from host.\n";
1839 static char no_debug_usage[] =
1840 "Usage: rtp no debug\n"
1841 " Disable all RTP debugging\n";
1843 static struct ast_cli_entry cli_debug_ip =
1844 {{ "rtp", "debug", "ip", NULL } , rtp_do_debug, "Enable RTP debugging on IP", debug_usage };
1846 static struct ast_cli_entry cli_debug =
1847 {{ "rtp", "debug", NULL } , rtp_do_debug, "Enable RTP debugging", debug_usage };
1849 static struct ast_cli_entry cli_no_debug =
1850 {{ "rtp", "no", "debug", NULL } , rtp_no_debug, "Disable RTP debugging", no_debug_usage };
1852 int ast_rtp_reload(void)
1854 struct ast_config *cfg;
1859 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
1860 cfg = ast_config_load("rtp.conf");
1862 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
1864 if (rtpstart < 1024)
1866 if (rtpstart > 65535)
1869 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
1876 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
1884 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
1887 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
1888 dtmftimeout = atoi(s);
1889 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
1890 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
1891 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
1892 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
1895 ast_config_destroy(cfg);
1897 if (rtpstart >= rtpend) {
1898 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
1902 if (option_verbose > 1)
1903 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
1907 /*! \brief Initialize the RTP system in Asterisk */
1908 void ast_rtp_init(void)
1910 ast_cli_register(&cli_debug);
1911 ast_cli_register(&cli_debug_ip);
1912 ast_cli_register(&cli_no_debug);