Skip to content
Snippets Groups Projects
rtp.c 55.4 KiB
Newer Older
Mark Spencer's avatar
Mark Spencer committed
/*
 * Asterisk -- An open source telephony toolkit.
Mark Spencer's avatar
Mark Spencer committed
 *
 * Copyright (C) 1999 - 2006, Digium, Inc.
Mark Spencer's avatar
Mark Spencer committed
 *
 * Mark Spencer <markster@digium.com>
Mark Spencer's avatar
Mark Spencer committed
 *
 * See http://www.asterisk.org for more information about
 * the Asterisk project. Please do not directly contact
 * any of the maintainers of this project for assistance;
 * the project provides a web site, mailing lists and IRC
 * channels for your use.
 *
Mark Spencer's avatar
Mark Spencer committed
 * This program is free software, distributed under the terms of
 * the GNU General Public License Version 2. See the LICENSE file
 * at the top of the source tree.
 */

 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
 *
 * \author Mark Spencer <markster@digium.com>
 * \note RTP is deffined in RFC 3550.
Mark Spencer's avatar
Mark Spencer committed
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>

#include "asterisk.h"

Kevin P. Fleming's avatar
Kevin P. Fleming committed
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
#include "asterisk/rtp.h"
#include "asterisk/frame.h"
#include "asterisk/logger.h"
#include "asterisk/options.h"
#include "asterisk/channel.h"
#include "asterisk/acl.h"
#include "asterisk/channel.h"
#include "asterisk/config.h"
#include "asterisk/lock.h"
#include "asterisk/utils.h"
#include "asterisk/cli.h"
#include "asterisk/unaligned.h"
#define MAX_TIMESTAMP_SKEW	640

#define DEFAULT_DTMF_TIMEOUT 3000	/*!< samples */

static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
static int rtpstart = 0;		/*!< First port for RTP sessions (set in rtp.conf) */
static int rtpend = 0;			/*!< Last port for RTP sessions (set in rtp.conf) */
static int rtpdebug = 0;		/*!< Are we debugging? */
static struct sockaddr_in rtpdebugaddr;	/*!< Debug packets to/from this host */
static int nochecksums = 0;
/*! \brief The value of each payload format mapping: */
struct rtpPayloadType {
	int isAstFormat; 	/*!< whether the following code is an AST_FORMAT */
	int code;
#define FLAG_3389_WARNING		(1 << 0)
#define FLAG_NAT_ACTIVE			(3 << 1)
#define FLAG_NAT_INACTIVE		(0 << 1)
#define FLAG_NAT_INACTIVE_NOWARN	(1 << 1)
Mark Spencer's avatar
Mark Spencer committed
struct ast_rtp {
	int s;
	char resp;
	struct ast_frame f;
	unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
	unsigned int ssrc;		/*!< Synchronization source, RFC 3550, page 10. */
Mark Spencer's avatar
Mark Spencer committed
	unsigned int lastts;
Mark Spencer's avatar
Mark Spencer committed
	unsigned int lastrxts;
	unsigned int lastividtimestamp;
	unsigned int lastovidtimestamp;
	unsigned int lasteventseqn;
	unsigned int lasteventendseqn;
Mark Spencer's avatar
Mark Spencer committed
	int lasttxformat;
	int lastrxformat;
Mark Spencer's avatar
Mark Spencer committed
	int dtmfcount;
Mark Spencer's avatar
Mark Spencer committed
	unsigned int dtmfduration;
	int nat;
	struct sockaddr_in us;		/*!< Socket representation of the local endpoint. */
	struct sockaddr_in them;	/*!< Socket representation of the remote endpoint. */
Mark Spencer's avatar
Mark Spencer committed
	struct timeval rxcore;
	struct timeval txcore;
Mark Spencer's avatar
Mark Spencer committed
	struct timeval dtmfmute;
Mark Spencer's avatar
Mark Spencer committed
	struct ast_smoother *smoother;
Mark Spencer's avatar
Mark Spencer committed
	int *ioid;
	unsigned short seqno;		/*!< Sequence number, RFC 3550, page 13. */
Mark Spencer's avatar
Mark Spencer committed
	struct sched_context *sched;
	struct io_context *io;
	void *data;
	ast_rtp_callback callback;
	struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
	int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
	int rtp_lookup_code_cache_code;
	int rtp_lookup_code_cache_result;
/*!
 * \brief Structure defining an RTCP session.
 * 
 * The concept "RTCP session" is not defined in RFC 3550, but since 
 * this structure is analogous to ast_rtp, which tracks a RTP session, 
 * it is logical to think of this as a RTCP session.
 *
 * RTCP packet is defined on page 9 of RFC 3550.
 * 
 */
	int s;				/*!< Socket */
	struct sockaddr_in us;		/*!< Socket representation of the local endpoint. */
	struct sockaddr_in them;	/*!< Socket representation of the remote endpoint. */
/*! \brief List of current sessions */
static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
int ast_rtp_fd(struct ast_rtp *rtp)
{
	return rtp->s;
}
int ast_rtcp_fd(struct ast_rtp *rtp)
{
	if (rtp->rtcp)
		return rtp->rtcp->s;
	return -1;
}

Mark Spencer's avatar
Mark Spencer committed
void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
{
	rtp->data = data;
}

void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
{
	rtp->callback = callback;
}

void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
{
	rtp->nat = nat;
}

static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
Mark Spencer's avatar
Mark Spencer committed
{
	char iabuf[INET_ADDRSTRLEN];

	if (ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
Mark Spencer's avatar
Mark Spencer committed
		rtp->resp = 0;
		rtp->dtmfduration = 0;
Mark Spencer's avatar
Mark Spencer committed
	}
	if (option_debug)
		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));
	if (rtp->resp == 'X') {
		rtp->f.frametype = AST_FRAME_CONTROL;
		rtp->f.subclass = AST_CONTROL_FLASH;
	} else {
		rtp->f.frametype = AST_FRAME_DTMF;
		rtp->f.subclass = rtp->resp;
	}
Mark Spencer's avatar
Mark Spencer committed
	rtp->f.datalen = 0;
Mark Spencer's avatar
Mark Spencer committed
	rtp->f.samples = 0;
Mark Spencer's avatar
Mark Spencer committed
	rtp->f.mallocd = 0;
	rtp->f.src = "RTP";
	rtp->resp = 0;
Mark Spencer's avatar
Mark Spencer committed
	rtp->dtmfduration = 0;
	return &rtp->f;
static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
{
	if (rtpdebug == 0)
		return 0;
	if (rtpdebugaddr.sin_addr.s_addr) {
		if (((ntohs(rtpdebugaddr.sin_port) != 0)
			&& (rtpdebugaddr.sin_port != addr->sin_port))
			|| (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
		return 0;
	}
	return 1;
}

Mark Spencer's avatar
Mark Spencer committed
static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
{
	unsigned int event;
	char resp = 0;
	struct ast_frame *f = NULL;
	event = ntohl(*((unsigned int *)(data)));
	event &= 0x001F;
	if (option_debug > 2 || rtpdebug)
		ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
Mark Spencer's avatar
Mark Spencer committed
	if (event < 10) {
		resp = '0' + event;
	} else if (event < 11) {
		resp = '*';
	} else if (event < 12) {
		resp = '#';
	} else if (event < 16) {
		resp = 'A' + (event - 12);
	} else if (event < 17) {
		resp = 'X';
Mark Spencer's avatar
Mark Spencer committed
	}
	if (rtp->resp && (rtp->resp != resp)) {
		f = send_dtmf(rtp);
	}
	rtp->resp = resp;
	rtp->dtmfcount = dtmftimeout;
	return f;
}

/*! 
 * \brief Process RTP DTMF and events according to RFC 2833.
 * 
 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
 * 
 * \param rtp
 * \param data
 * \param len
 * \param seqno
 * \returns
 */
static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
Mark Spencer's avatar
Mark Spencer committed
{
	unsigned int event;
Mark Spencer's avatar
Mark Spencer committed
	unsigned int event_end;
	unsigned int duration;
Mark Spencer's avatar
Mark Spencer committed
	char resp = 0;
	struct ast_frame *f = NULL;
Mark Spencer's avatar
Mark Spencer committed
	event = ntohl(*((unsigned int *)(data)));
	event >>= 24;
Mark Spencer's avatar
Mark Spencer committed
	event_end = ntohl(*((unsigned int *)(data)));
	event_end <<= 8;
	event_end >>= 24;
	duration = ntohl(*((unsigned int *)(data)));
	duration &= 0xFFFF;
		ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
Mark Spencer's avatar
Mark Spencer committed
	if (event < 10) {
		resp = '0' + event;
	} else if (event < 11) {
		resp = '*';
	} else if (event < 12) {
		resp = '#';
	} else if (event < 16) {
		resp = 'A' + (event - 12);
	} else if (event < 17) {	/* Event 16: Hook flash */
		resp = 'X';	
Mark Spencer's avatar
Mark Spencer committed
	}
	if (rtp->resp && (rtp->resp != resp)) {
		f = send_dtmf(rtp);
Mark Spencer's avatar
Mark Spencer committed
		if (rtp->resp) {
			if(rtp->lasteventendseqn != seqno) {
				f = send_dtmf(rtp);
				rtp->lasteventendseqn = seqno;
			}
Mark Spencer's avatar
Mark Spencer committed
			rtp->resp = 0;
		}
Mark Spencer's avatar
Mark Spencer committed
		resp = 0;
		duration = 0;
	} else if (rtp->resp && rtp->dtmfduration && (duration < rtp->dtmfduration)) {
Mark Spencer's avatar
Mark Spencer committed
		f = send_dtmf(rtp);
	}
Mark Spencer's avatar
Mark Spencer committed
	if (!(event_end & 0x80))
		rtp->resp = resp;
Mark Spencer's avatar
Mark Spencer committed
	rtp->dtmfcount = dtmftimeout;
Mark Spencer's avatar
Mark Spencer committed
	rtp->dtmfduration = duration;
	return f;
/*!
 * \brief Process Comfort Noise RTP.
 * 
 * This is incomplete at the moment.
 * 
static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
{
	struct ast_frame *f = NULL;
	/* Convert comfort noise into audio with various codecs.  Unfortunately this doesn't
	   totally help us out becuase we don't have an engine to keep it going and we are not
	   guaranteed to have it every 20ms or anything */
Jeremy McNamara's avatar
Jeremy McNamara committed
		ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);

	if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {

		ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
			ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
		ast_set_flag(rtp, FLAG_3389_WARNING);
	/* Must have at least one byte */
	if (!len)
		return NULL;
	if (len < 24) {
		rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
		memcpy(rtp->f.data, data + 1, len - 1);
	} else {
	rtp->f.frametype = AST_FRAME_CNG;
	rtp->f.subclass = data[0] & 0x7f;
	rtp->f.datalen = len - 1;
	rtp->f.samples = 0;
	rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
	f = &rtp->f;
Mark Spencer's avatar
Mark Spencer committed
static int rtpread(int *id, int fd, short events, void *cbdata)
{
	struct ast_rtp *rtp = cbdata;
	struct ast_frame *f;
	f = ast_rtp_read(rtp);
	if (f) {
		if (rtp->callback)
			rtp->callback(rtp, f, rtp->data);
	}
	return 1;
}

struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
{
	int hdrlen = 8;
	int res;
	struct sockaddr_in sin;
	unsigned int rtcpdata[1024];
	char iabuf[INET_ADDRSTRLEN];
	if (!rtp || !rtp->rtcp)

	len = sizeof(sin);
	
	res = recvfrom(rtp->rtcp->s, rtcpdata, sizeof(rtcpdata),
					0, (struct sockaddr *)&sin, &len);
	
	if (res < 0) {
		if (errno != EAGAIN)
			ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
	}

	if (res < hdrlen) {
		ast_log(LOG_WARNING, "RTP Read too short\n");
	}

	if (rtp->nat) {
		/* Send to whoever sent to us */
		if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
		    (rtp->rtcp->them.sin_port != sin.sin_port)) {
			memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
			if (option_debug || rtpdebug)
				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));
Mark Spencer's avatar
Mark Spencer committed
	if (option_debug)
		ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
	struct timeval ts = ast_samp2tv( timestamp, 8000);
	if (ast_tvzero(rtp->rxcore) || mark) {
		rtp->rxcore = ast_tvsub(ast_tvnow(), ts);
		/* Round to 20ms for nice, pretty timestamps */
		rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 20000;
struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
{
Mark Spencer's avatar
Mark Spencer committed
	int res;
	struct sockaddr_in sin;
Mark Spencer's avatar
Mark Spencer committed
	unsigned int seqno;
	int version;
Mark Spencer's avatar
Mark Spencer committed
	int payloadtype;
	int hdrlen = 12;
	char iabuf[INET_ADDRSTRLEN];
Mark Spencer's avatar
Mark Spencer committed
	unsigned int timestamp;
	unsigned int *rtpheader;
	struct rtpPayloadType rtpPT;
Mark Spencer's avatar
Mark Spencer committed
	
	len = sizeof(sin);
	
	/* Cache where the header will go */
	res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
Mark Spencer's avatar
Mark Spencer committed
					0, (struct sockaddr *)&sin, &len);

	rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
Mark Spencer's avatar
Mark Spencer committed
	if (res < 0) {
		if (errno != EAGAIN)
			ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
Mark Spencer's avatar
Mark Spencer committed
		if (errno == EBADF)
			CRASH;
Mark Spencer's avatar
Mark Spencer committed
	}
	if (res < hdrlen) {
		ast_log(LOG_WARNING, "RTP Read too short\n");
Mark Spencer's avatar
Mark Spencer committed
	}

	/* Ignore if the other side hasn't been given an address
	   yet.  */
	if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
	if (rtp->nat) {
		/* Send to whoever sent to us */
		if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
		    (rtp->them.sin_port != sin.sin_port)) {
			memcpy(&rtp->them, &sin, sizeof(rtp->them));
			ast_set_flag(rtp, FLAG_NAT_ACTIVE);
			if (option_debug || rtpdebug)
				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));
Mark Spencer's avatar
Mark Spencer committed
	/* Get fields */
	seqno = ntohl(rtpheader[0]);

	/* Check RTP version */
	version = (seqno & 0xC0000000) >> 30;
	if (version != 2)
Mark Spencer's avatar
Mark Spencer committed
	payloadtype = (seqno & 0x7f0000) >> 16;
	padding = seqno & (1 << 29);
	ext = seqno & (1 << 28);
Mark Spencer's avatar
Mark Spencer committed
	seqno &= 0xffff;
	timestamp = ntohl(rtpheader[1]);
	
	if (padding) {
		/* Remove padding bytes */
		res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
	}
	
	if (ext) {
		/* RTP Extension present */
		hdrlen += 4;
		hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
	if (res < hdrlen) {
		ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
	if(rtp_debug_test_addr(&sin))
		ast_verbose("Got RTP packet from %s:%d (type %d, seq %d, ts %d, len %d)\n"
			, ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);

   	rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
	if (!rtpPT.isAstFormat) {
		/* This is special in-band data that's not one of our codecs */
		if (rtpPT.code == AST_RTP_DTMF) {
			/* It's special -- rfc2833 process it */
			if(rtp_debug_test_addr(&sin)) {
				unsigned char *data;
				unsigned int event;
				unsigned int event_end;
				unsigned int duration;
				data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
				event = ntohl(*((unsigned int *)(data)));
				event >>= 24;
				event_end = ntohl(*((unsigned int *)(data)));
				event_end <<= 8;
				event_end >>= 24;
				duration = ntohl(*((unsigned int *)(data)));
				duration &= 0xFFFF;
				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);
			}
			if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
				f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
				rtp->lasteventseqn = seqno;
			} else
		} else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
			/* It's really special -- process it the Cisco way */
			if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
				f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
				rtp->lasteventseqn = seqno;
			} else 
		} else if (rtpPT.code == AST_RTP_CN) {
			/* Comfort Noise */
			f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
			if (f) 
			ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
	}
	rtp->f.subclass = rtpPT.code;
	if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO)
		rtp->f.frametype = AST_FRAME_VOICE;
	else
		rtp->f.frametype = AST_FRAME_VIDEO;
	rtp->lastrxformat = rtp->f.subclass;
Mark Spencer's avatar
Mark Spencer committed

	if (!rtp->lastrxts)
		rtp->lastrxts = timestamp;

	if (rtp->rxseqno) {
		for (x=rtp->rxseqno + 1; x < seqno; x++) {
			/* Queue empty frames */
			rtp->f.mallocd = 0;
			rtp->f.datalen = 0;
			rtp->f.data = NULL;
			rtp->f.offset = 0;
			rtp->f.samples = 0;
			rtp->f.src = "RTPMissedFrame";
		}
	}
	rtp->rxseqno = seqno;

Mark Spencer's avatar
Mark Spencer committed
	if (rtp->dtmfcount) {
#if 0
		printf("dtmfcount was %d\n", rtp->dtmfcount);
#endif		
		rtp->dtmfcount -= (timestamp - rtp->lastrxts);
		if (rtp->dtmfcount < 0)
			rtp->dtmfcount = 0;
#if 0
		if (dtmftimeout != rtp->dtmfcount)
			printf("dtmfcount is %d\n", rtp->dtmfcount);
#endif
	}
	rtp->lastrxts = timestamp;

	/* Send any pending DTMF */
	if (rtp->resp && !rtp->dtmfcount) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Sending pending DTMF\n");
		return send_dtmf(rtp);
Mark Spencer's avatar
Mark Spencer committed
	}
	rtp->f.mallocd = 0;
	rtp->f.datalen = res - hdrlen;
Mark Spencer's avatar
Mark Spencer committed
	rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
	rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
	if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
		rtp->f.samples = ast_codec_get_samples(&rtp->f);
		if (rtp->f.subclass == AST_FORMAT_SLINEAR) 
		calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
	} else {
		/* Video -- samples is # of samples vs. 90000 */
Mark Spencer's avatar
Mark Spencer committed
		if (!rtp->lastividtimestamp)
			rtp->lastividtimestamp = timestamp;
		rtp->f.samples = timestamp - rtp->lastividtimestamp;
		rtp->lastividtimestamp = timestamp;
		rtp->f.delivery.tv_sec = 0;
		rtp->f.delivery.tv_usec = 0;
		if (mark)
			rtp->f.subclass |= 0x1;
		
Mark Spencer's avatar
Mark Spencer committed
	}
	rtp->f.src = "RTP";
	return &rtp->f;
/* The following array defines the MIME Media type (and subtype) for each
   of our codecs, or RTP-specific data type. */
Mark Spencer's avatar
Mark Spencer committed
static struct {
	struct rtpPayloadType payloadType;
	char* type;
	char* subtype;
} mimeTypes[] = {
	{{1, AST_FORMAT_G723_1}, "audio", "G723"},
	{{1, AST_FORMAT_GSM}, "audio", "GSM"},
	{{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
	{{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
	{{1, AST_FORMAT_G726}, "audio", "G726-32"},
	{{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
	{{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
	{{1, AST_FORMAT_LPC10}, "audio", "LPC"},
	{{1, AST_FORMAT_G729A}, "audio", "G729"},
	{{1, AST_FORMAT_SPEEX}, "audio", "speex"},
	{{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
	{{0, AST_RTP_DTMF}, "audio", "telephone-event"},
	{{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
	{{0, AST_RTP_CN}, "audio", "CN"},
	{{1, AST_FORMAT_JPEG}, "video", "JPEG"},
	{{1, AST_FORMAT_PNG}, "video", "PNG"},
	{{1, AST_FORMAT_H261}, "video", "H261"},
	{{1, AST_FORMAT_H263}, "video", "H263"},
	{{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
	{{1, AST_FORMAT_H264}, "video", "H264"},
/* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
   also, our own choices for dynamic payload types.  This is our master
   table for transmission */
static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
#ifdef USE_DEPRECATED_G726
	[2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
	[3] = {1, AST_FORMAT_GSM},
	[4] = {1, AST_FORMAT_G723_1},
	[5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
	[6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
	[7] = {1, AST_FORMAT_LPC10},
	[8] = {1, AST_FORMAT_ALAW},
	[10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
	[11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
	[13] = {0, AST_RTP_CN},
	[16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
	[17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
	[18] = {1, AST_FORMAT_G729A},
	[19] = {0, AST_RTP_CN},		/* Also used for CN */
	[26] = {1, AST_FORMAT_JPEG},
	[31] = {1, AST_FORMAT_H261},
	[34] = {1, AST_FORMAT_H263},
	[103] = {1, AST_FORMAT_H263_PLUS},
	[97] = {1, AST_FORMAT_ILBC},
	[99] = {1, AST_FORMAT_H264},
	[101] = {0, AST_RTP_DTMF},
	[110] = {1, AST_FORMAT_SPEEX},
	[111] = {1, AST_FORMAT_G726},
	[121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
void ast_rtp_pt_clear(struct ast_rtp* rtp) 
{
	for (i = 0; i < MAX_RTP_PT; ++i) {
		rtp->current_RTP_PT[i].isAstFormat = 0;
		rtp->current_RTP_PT[i].code = 0;
	}
	rtp->rtp_lookup_code_cache_isAstFormat = 0;
	rtp->rtp_lookup_code_cache_code = 0;
	rtp->rtp_lookup_code_cache_result = 0;
void ast_rtp_pt_default(struct ast_rtp* rtp) 
{
	int i;

	/* Initialize to default payload types */
	for (i = 0; i < MAX_RTP_PT; ++i) {
		rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
		rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
	}

	rtp->rtp_lookup_code_cache_isAstFormat = 0;
	rtp->rtp_lookup_code_cache_code = 0;
	rtp->rtp_lookup_code_cache_result = 0;
static void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
{
	int i;
	/* Copy payload types from source to destination */
	for (i=0; i < MAX_RTP_PT; ++i) {
		dest->current_RTP_PT[i].isAstFormat = 
			src->current_RTP_PT[i].isAstFormat;
		dest->current_RTP_PT[i].code = 
			src->current_RTP_PT[i].code; 
	}
	dest->rtp_lookup_code_cache_isAstFormat = 0;
	dest->rtp_lookup_code_cache_code = 0;
	dest->rtp_lookup_code_cache_result = 0;
}

/*! \brief Get channel driver interface structure */
static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
{
	struct ast_rtp_protocol *cur = NULL;
	AST_LIST_LOCK(&protos);
	AST_LIST_TRAVERSE(&protos, cur, list) {
		if (cur->type == chan->tech->type)
}

int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src)
{
	struct ast_rtp *destp, *srcp;		/* Audio RTP Channels */
	struct ast_rtp *vdestp, *vsrcp;		/* Video RTP channels */
	struct ast_rtp_protocol *destpr, *srcpr;
	/* Lock channels */
	ast_mutex_lock(&dest->lock);
	while(ast_mutex_trylock(&src->lock)) {
		ast_mutex_unlock(&dest->lock);
		usleep(1);
		ast_mutex_lock(&dest->lock);
	}

	/* Find channel driver interfaces */
	destpr = get_proto(dest);
	srcpr = get_proto(src);
	if (!destpr) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
		ast_mutex_unlock(&dest->lock);
		ast_mutex_unlock(&src->lock);
		return 0;
	}
	if (!srcpr) {
		if (option_debug)
			ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
		ast_mutex_unlock(&dest->lock);
		ast_mutex_unlock(&src->lock);
		return 0;
	}

	/* Get audio and video interface (if native bridge is possible) */
	destp = destpr->get_rtp_info(dest);
	if (destpr->get_vrtp_info)
		vdestp = destpr->get_vrtp_info(dest);
	else
		vdestp = NULL;
	srcp = srcpr->get_rtp_info(src);
	if (srcpr->get_vrtp_info)
		vsrcp = srcpr->get_vrtp_info(src);
	else
		vsrcp = NULL;

	/* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
	if (!destp || !srcp) {
		/* Somebody doesn't want to play... */
		ast_mutex_unlock(&dest->lock);
		ast_mutex_unlock(&src->lock);
		return 0;
	}
	ast_rtp_pt_copy(destp, srcp);
	if (vdestp && vsrcp)
		ast_rtp_pt_copy(vdestp, vsrcp);
	ast_mutex_unlock(&dest->lock);
	ast_mutex_unlock(&src->lock);
	if (option_debug)
		ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
/*! \brief  Make a note of a RTP paymoad type that was seen in a SDP "m=" line.
 * By default, use the well-known value for this type (although it may 
 * still be set to a different value by a subsequent "a=rtpmap:" line)
 */
void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt) 
{
	if (pt < 0 || pt > MAX_RTP_PT) 
		return; /* bogus payload type */
	if (static_RTP_PT[pt].code != 0) {
		rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
	}
/*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
 	a SDP "a=rtpmap:" line. */
void ast_rtp_set_rtpmap_type(struct ast_rtp* rtp, int pt,
	if (pt < 0 || pt > MAX_RTP_PT) 
			return; /* bogus payload type */
	for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
		if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
		     strcasecmp(mimeType, mimeTypes[i].type) == 0) {
			rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
		return;
		}
	}
/*! \brief Return the union of all of the codecs that were set by rtp_set...() calls 
 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
void ast_rtp_get_current_formats(struct ast_rtp* rtp,
			     int* astFormats, int* nonAstFormats) {
	int pt;

	*astFormats = *nonAstFormats = 0;
	for (pt = 0; pt < MAX_RTP_PT; ++pt) {
		if (rtp->current_RTP_PT[pt].isAstFormat) {
			*astFormats |= rtp->current_RTP_PT[pt].code;
		} else {
			*nonAstFormats |= rtp->current_RTP_PT[pt].code;
		}
	}
struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt) 
{
	struct rtpPayloadType result;

	result.isAstFormat = result.code = 0;
	if (pt < 0 || pt > MAX_RTP_PT) 
		return result; /* bogus payload type */

	/* Start with the negotiated codecs */

	/* If it doesn't exist, check our static RTP type list, just in case */
	if (!result.code) 
		result = static_RTP_PT[pt];
	return result;
/*! \brief Looks up an RTP code out of our *static* outbound list */
int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
	if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
		code == rtp->rtp_lookup_code_cache_code) {

		/* Use our cached mapping, to avoid the overhead of the loop below */
		return rtp->rtp_lookup_code_cache_result;
	}
	/* Check the dynamic list first */
	for (pt = 0; pt < MAX_RTP_PT; ++pt) {
  		if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
			rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
			rtp->rtp_lookup_code_cache_code = code;
			rtp->rtp_lookup_code_cache_result = pt;
			return pt;
		}
	}

	/* Then the static list */
	for (pt = 0; pt < MAX_RTP_PT; ++pt) {
		if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
			rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
  			rtp->rtp_lookup_code_cache_code = code;
			rtp->rtp_lookup_code_cache_result = pt;
			return pt;
		}
	}
	return -1;
Mark Spencer's avatar
Mark Spencer committed
}
char* ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code) 
{

	int i;

	for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
	if (mimeTypes[i].payloadType.code == code && mimeTypes[i].payloadType.isAstFormat == isAstFormat) {
      		return mimeTypes[i].subtype;
		}
	}
	return "";
char *ast_rtp_lookup_mime_multiple(char *buf, int size, const int capability, const int isAstFormat)
{
	int format;
	unsigned len;
	char *end = buf;
	char *start = buf;
	snprintf(end, size, "0x%x (", capability);

	len = strlen(end);
	end += len;
	size -= len;
	start = end;

	for (format = 1; format < AST_RTP_MAX; format <<= 1) {
		if (capability & format) {
			const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format);
			snprintf(end, size, "%s|", name);
			len = strlen(end);
			end += len;
			size -= len;
	if (start == end)
		snprintf(start, size, "nothing)"); 
	else if (size > 1)
		*(end -1) = ')';
	
Mark Spencer's avatar
Mark Spencer committed
static int rtp_socket(void)
{
	int s;
	long flags;
	s = socket(AF_INET, SOCK_DGRAM, 0);
	if (s > -1) {
		flags = fcntl(s, F_GETFL);
		fcntl(s, F_SETFL, flags | O_NONBLOCK);
		if (nochecksums)
			setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
/*!
 * \brief Initialize a new RTCP session.
 * 
 * \returns The newly initialized RTCP session.
 */
static struct ast_rtcp *ast_rtcp_new(void)
{
	struct ast_rtcp *rtcp;

	if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
Mark Spencer's avatar
Mark Spencer committed
	rtcp->s = rtp_socket();
	rtcp->us.sin_family = AF_INET;
	if (rtcp->s < 0) {
		free(rtcp);
		ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
		return NULL;
	}
struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)