Newer
Older
* Asterisk -- An open source telephony toolkit.
* Copyright (C) 1999 - 2006, Digium, Inc.
* 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.
*
* 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>
*
*/
#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>
Kevin P. Fleming
committed
#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"
Kevin P. Fleming
committed
#include "asterisk/utils.h"
#define MAX_TIMESTAMP_SKEW 640
#define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
#define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
#define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
#define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
#define RTCP_PT_FUR 192
#define RTCP_PT_SR 200
#define RTCP_PT_RR 201
#define RTCP_PT_SDES 202
#define RTCP_PT_BYE 203
#define RTCP_PT_APP 204
#define RTP_MTU 1200
Olle Johansson
committed
#define DEFAULT_DTMF_TIMEOUT 3000 /*!< samples */
static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
Olle Johansson
committed
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 int rtcpdebug = 0; /*!< Are we debugging RTCP? */
static int rtcpstats = 0; /*!< Are we debugging RTCP? */
static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
static int stundebug = 0; /*!< Are we debugging stun? */
Olle Johansson
committed
static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
static struct sockaddr_in rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
#ifdef SO_NO_CHECK
static int nochecksums = 0;
#endif
/* Forward declarations */
static int ast_rtcp_write(void *data);
static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
static int ast_rtcp_write_sr(void *data);
static int ast_rtcp_write_rr(void *data);
static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
Kevin P. Fleming
committed
#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)
#define FLAG_HAS_DTMF (1 << 3)
/*!
* \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.
*
*/
struct ast_rtcp {
Olle Johansson
committed
int s; /*!< Socket */
struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
unsigned int soc; /*!< What they told us */
unsigned int spc; /*!< What they told us */
unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
struct timeval rxlsr; /*!< Time when we got their last SR */
struct timeval txlsr; /*!< Time when we sent or last SR*/
unsigned int expected_prior; /*!< no. packets in previous interval */
unsigned int received_prior; /*!< no. packets received in previous interval */
int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
unsigned int sr_count; /*!< number of SRs we've sent */
unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
double accumulated_transit; /*!< accumulated a-dlsr-lsr */
double rtt; /*!< Last reported rtt */
unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
unsigned int reported_lost; /*!< Reported lost packets in their RR */
char quality[AST_MAX_USER_FIELD];
double maxrxjitter;
double minrxjitter;
double maxrtt;
double minrtt;
int sendfur;
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
/* XXX Maybe stun belongs in another file if it ever has use outside of RTP */
struct stun_header {
unsigned short msgtype;
unsigned short msglen;
stun_trans_id id;
unsigned char ies[0];
} __attribute__((packed));
struct stun_attr {
unsigned short attr;
unsigned short len;
unsigned char value[0];
} __attribute__((packed));
struct stun_addr {
unsigned char unused;
unsigned char family;
unsigned short port;
unsigned int addr;
} __attribute__((packed));
#define STUN_IGNORE (0)
#define STUN_ACCEPT (1)
#define STUN_BINDREQ 0x0001
#define STUN_BINDRESP 0x0101
#define STUN_BINDERR 0x0111
#define STUN_SECRESP 0x0102
#define STUN_RESPONSE_ADDRESS 0x0002
#define STUN_CHANGE_REQUEST 0x0003
#define STUN_SOURCE_ADDRESS 0x0004
#define STUN_CHANGED_ADDRESS 0x0005
#define STUN_USERNAME 0x0006
#define STUN_PASSWORD 0x0007
#define STUN_MESSAGE_INTEGRITY 0x0008
#define STUN_UNKNOWN_ATTRIBUTES 0x000a
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
static const char *stun_msg2str(int msg)
{
switch(msg) {
case STUN_BINDREQ:
return "Binding Request";
case STUN_BINDRESP:
return "Binding Response";
case STUN_BINDERR:
return "Binding Error Response";
case STUN_SECREQ:
return "Shared Secret Request";
case STUN_SECRESP:
return "Shared Secret Response";
case STUN_SECERR:
return "Shared Secret Error Response";
}
return "Non-RFC3489 Message";
}
static const char *stun_attr2str(int msg)
{
switch(msg) {
case STUN_MAPPED_ADDRESS:
return "Mapped Address";
case STUN_RESPONSE_ADDRESS:
return "Response Address";
case STUN_CHANGE_REQUEST:
return "Change Request";
case STUN_SOURCE_ADDRESS:
return "Source Address";
case STUN_CHANGED_ADDRESS:
return "Changed Address";
case STUN_USERNAME:
return "Username";
case STUN_PASSWORD:
return "Password";
case STUN_MESSAGE_INTEGRITY:
return "Message Integrity";
case STUN_ERROR_CODE:
return "Error Code";
case STUN_UNKNOWN_ATTRIBUTES:
return "Unknown Attributes";
case STUN_REFLECTED_FROM:
return "Reflected From";
}
return "Non-RFC3489 Attribute";
}
struct stun_state {
unsigned char *username;
unsigned char *password;
};
static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
{
if (stundebug)
ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
switch(ntohs(attr->attr)) {
case STUN_USERNAME:
state->username = (unsigned char *)(attr->value);
break;
case STUN_PASSWORD:
state->password = (unsigned char *)(attr->value);
break;
default:
if (stundebug)
ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
}
return 0;
}
static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
{
int size = sizeof(**attr) + strlen(s);
if (*left > size) {
(*attr)->attr = htons(attrval);
(*attr)->len = htons(strlen(s));
memcpy((*attr)->value, s, strlen(s));
(*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
*len += size;
*left -= size;
}
}
static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
{
int size = sizeof(**attr) + 8;
struct stun_addr *addr;
if (*left > size) {
(*attr)->attr = htons(attrval);
(*attr)->len = htons(8);
addr = (struct stun_addr *)((*attr)->value);
addr->unused = 0;
addr->family = 0x01;
addr->port = sin->sin_port;
addr->addr = sin->sin_addr.s_addr;
(*attr) = (struct stun_attr *)((*attr)->value + 8);
*len += size;
*left -= size;
}
}
static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
{
return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
(struct sockaddr *)dst, sizeof(*dst));
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
}
static void stun_req_id(struct stun_header *req)
{
int x;
for (x=0;x<4;x++)
req->id.id[x] = ast_random();
}
void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
{
struct stun_header *req;
unsigned char reqdata[1024];
int reqlen, reqleft;
struct stun_attr *attr;
req = (struct stun_header *)reqdata;
stun_req_id(req);
reqlen = 0;
reqleft = sizeof(reqdata) - sizeof(struct stun_header);
req->msgtype = 0;
req->msglen = 0;
attr = (struct stun_attr *)req->ies;
if (username)
append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
req->msglen = htons(reqlen);
req->msgtype = htons(STUN_BINDREQ);
stun_send(rtp->s, suggestion, req);
}
Kevin P. Fleming
committed
static int stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len)
{
struct stun_header *resp, *hdr = (struct stun_header *)data;
struct stun_attr *attr;
struct stun_state st;
int ret = STUN_IGNORE;
unsigned char respdata[1024];
int resplen, respleft;
if (len < sizeof(struct stun_header)) {
Kevin P. Fleming
committed
ast_log(LOG_DEBUG, "Runt STUN packet (only %zd, wanting at least %zd)\n", len, sizeof(struct stun_header));
return -1;
}
if (stundebug)
ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), ntohs(hdr->msglen));
if (ntohs(hdr->msglen) > len - sizeof(struct stun_header)) {
Kevin P. Fleming
committed
ast_log(LOG_DEBUG, "Scrambled STUN packet length (got %d, expecting %zd)\n", ntohs(hdr->msglen), len - sizeof(struct stun_header));
} else
len = ntohs(hdr->msglen);
data += sizeof(struct stun_header);
memset(&st, 0, sizeof(st));
while(len) {
if (len < sizeof(struct stun_attr)) {
Kevin P. Fleming
committed
ast_log(LOG_DEBUG, "Runt Attribute (got %zd, expecting %zd)\n", len, sizeof(struct stun_attr));
break;
}
attr = (struct stun_attr *)data;
if (ntohs(attr->len) > len) {
Kevin P. Fleming
committed
ast_log(LOG_DEBUG, "Inconsistant Attribute (length %d exceeds remaining msg len %zd)\n", ntohs(attr->len), len);
break;
}
if (stun_process_attr(&st, attr)) {
if (option_debug)
ast_log(LOG_DEBUG, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
break;
}
/* Clear attribute in case previous entry was a string */
attr->attr = 0;
data += ntohs(attr->len) + sizeof(struct stun_attr);
len -= ntohs(attr->len) + sizeof(struct stun_attr);
}
/* Null terminate any string */
*data = '\0';
resp = (struct stun_header *)respdata;
resplen = 0;
respleft = sizeof(respdata) - sizeof(struct stun_header);
resp->id = hdr->id;
resp->msgtype = 0;
resp->msglen = 0;
attr = (struct stun_attr *)resp->ies;
if (!len) {
switch(ntohs(hdr->msgtype)) {
case STUN_BINDREQ:
if (stundebug)
ast_verbose("STUN Bind Request, username: %s\n",
st.username ? (const char *)st.username : "<none>");
if (st.username)
append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
resp->msglen = htons(resplen);
resp->msgtype = htons(STUN_BINDRESP);
stun_send(s, src, resp);
ret = STUN_ACCEPT;
break;
default:
if (stundebug)
ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
}
}
return ret;
}
Olle Johansson
committed
/*! \brief List of current sessions */
static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
{
unsigned int sec, usec, frac;
sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
usec = tv.tv_usec;
frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
*msw = sec;
*lsw = frac;
}
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;
}
unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
{
unsigned int interval;
/*! \todo XXX Do a more reasonable calculation on this one
* Look in RFC 3550 Section A.7 for an example*/
interval = rtcpinterval;
return interval;
}
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;
}
void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
{
ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
}
static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
char iabuf[INET_ADDRSTRLEN];
Kevin P. Fleming
committed
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));
return &ast_null_frame;
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;
}
rtp->f.mallocd = 0;
rtp->f.src = "RTP";
rtp->resp = 0;
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;
}
static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
{
if (rtcpdebug == 0)
return 0;
if (rtcpdebugaddr.sin_addr.s_addr) {
if (((ntohs(rtcpdebugaddr.sin_port) != 0)
&& (rtcpdebugaddr.sin_port != addr->sin_port))
|| (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
return 0;
}
return 1;
}
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;
Olle Johansson
committed
if (option_debug > 2 || rtpdebug)
ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
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';
}
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)
unsigned int event_end;
unsigned int duration;
Olle Johansson
committed
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;
Olle Johansson
committed
if (rtpdebug || option_debug > 2)
ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
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';
if (rtp->lasteventendseqn != seqno) {
f = send_dtmf(rtp);
rtp->lasteventendseqn = seqno;
}
} else if (rtp->resp && rtp->dtmfduration && (duration < rtp->dtmfduration)) {
if (!(event_end & 0x80))
rtp->resp = resp;
/*!
* \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 */
if (rtpdebug)
ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
Kevin P. Fleming
committed
if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
char iabuf[INET_ADDRSTRLEN];
Kevin P. Fleming
committed
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);
Kevin P. Fleming
committed
/* Must have at least one byte */
if (!len)
return NULL;
if (len < 24) {
Mark Spencer
committed
rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
rtp->f.datalen = len - 1;
Mark Spencer
committed
rtp->f.offset = AST_FRIENDLY_OFFSET;
memcpy(rtp->f.data, data + 1, len - 1);
} else {
Mark Spencer
committed
rtp->f.data = NULL;
rtp->f.offset = 0;
rtp->f.datalen = 0;
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;
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)
{
socklen_t len;
int position, i, packetwords;
int res;
struct sockaddr_in sin;
unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
char iabuf[INET_ADDRSTRLEN];
unsigned int *rtcpheader;
int pt;
struct timeval now;
unsigned int length;
int rc;
double rtt = 0;
double a;
double dlsr;
double lsr;
unsigned int msw;
unsigned int lsw;
unsigned int comp;
struct ast_frame *f = &ast_null_frame;
if (!rtp || !rtp->rtcp)
return &ast_null_frame;
len = sizeof(sin);
res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
0, (struct sockaddr *)&sin, &len);
rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
if (res < 0) {
ast_log(LOG_WARNING, "RTCP Read error: %s\n", strerror(errno));
if (errno == EBADF)
CRASH;
return &ast_null_frame;
packetwords = res / 4;
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));
Kevin P. Fleming
committed
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));
if (option_debug)
ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
/* Process a compound packet */
position = 0;
while (position < packetwords) {
i = position;
length = ntohl(rtcpheader[i]);
pt = (length & 0xff0000) >> 16;
rc = (length & 0x1f000000) >> 24;
length &= 0xffff;
if ((i + length) > packetwords) {
ast_log(LOG_WARNING, "RTCP Read too short\n");
return &ast_null_frame;
}
if (rtcp_debug_test_addr(&sin)) {
ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
ast_verbose("Reception reports: %d\n", rc);
ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
}
i += 2; /* Advance past header and ssrc */
switch (pt) {
case RTCP_PT_SR:
gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff) >> 16); /* Going to LSR in RR*/
if (rtcp_debug_test_addr(&sin)) {
ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
}
i += 5;
if (rc < 1)
break;
/* Intentional fall through */
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
case RTCP_PT_RR:
/* This is the place to calculate RTT */
/* Don't handle multiple reception reports (rc > 1) yet */
gettimeofday(&now, NULL);
timeval2ntp(now, &msw, &lsw);
/* Use the one we sent them in our SR instead, rtcp->txlsr could have been rewritten if the dlsr is large */
if (ntohl(rtcpheader[i + 4])) { /* We must have the LSR */
comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
a = (double)((comp & 0xffff0000) >> 16) + (double)((double)(comp & 0xffff)/1000000.);
lsr = (double)((ntohl(rtcpheader[i + 4]) & 0xffff0000) >> 16) + (double)((double)(ntohl(rtcpheader[i + 4]) & 0xffff) / 1000000.);
dlsr = (double)(ntohl(rtcpheader[i + 5])/65536.);
rtt = a - dlsr - lsr;
rtp->rtcp->accumulated_transit += rtt;
rtp->rtcp->rtt = rtt;
if (rtp->rtcp->maxrtt<rtt)
rtp->rtcp->maxrtt = rtt;
if (rtp->rtcp->minrtt>rtt)
rtp->rtcp->minrtt = rtt;
}
rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
if (rtcp_debug_test_addr(&sin)) {
ast_verbose("Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
ast_verbose("Packets lost so far: %d\n", rtp->rtcp->reported_lost);
ast_verbose("Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
ast_verbose("Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
ast_verbose("Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
ast_verbose("Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
ast_verbose("DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
if (rtt)
ast_verbose("RTT: %f(sec)\n", rtt);
}
break;
case RTCP_PT_FUR:
if (rtcp_debug_test_addr(&sin))
ast_verbose("Received an RTCP Fast Update Request\n");
rtp->f.frametype = AST_FRAME_CONTROL;
rtp->f.subclass = AST_CONTROL_VIDUPDATE;
rtp->f.datalen = 0;
rtp->f.samples = 0;
rtp->f.mallocd = 0;
rtp->f.src = "RTP";
f = &rtp->f;
break;
case RTCP_PT_SDES:
if (rtcp_debug_test_addr(&sin))
ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
break;
case RTCP_PT_BYE:
if (rtcp_debug_test_addr(&sin))
ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
break;
default:
ast_log(LOG_NOTICE, "Unknown RTCP packet (pt=%d) received from %s:%d\n", pt, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
break;
}
position += (length + 1);
}
return f;
static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
struct timeval now;
double transit;
double current_time;
double d;
double dtv;
double prog;
if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
gettimeofday(&rtp->rxcore, NULL);
rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
/* map timestamp to a real time */
rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
rtp->rxcore.tv_sec -= timestamp / 8000;
rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
/* Round to 0.1ms for nice, pretty timestamps */
rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
if (rtp->rxcore.tv_usec < 0) {
/* Adjust appropriately if necessary */
rtp->rxcore.tv_usec += 1000000;
rtp->rxcore.tv_sec -= 1;
}
gettimeofday(&now,NULL);
/* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
if (tv->tv_usec >= 1000000) {
tv->tv_usec -= 1000000;
tv->tv_sec += 1;
}
prog = (double)((timestamp-rtp->seedrxts)/8000.);
dtv = (double)rtp->drxcore + (double)(prog);
current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
transit = current_time - dtv;
d = transit - rtp->rxtransit;
rtp->rxtransit = transit;
d=-d;
rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
rtp->rtcp->maxrxjitter = rtp->rxjitter;
if (rtp->rxjitter < rtp->rtcp->minrxjitter)
rtp->rtcp->minrxjitter = rtp->rxjitter;
struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
{
socklen_t len;
int tseqno;
int mark;
char iabuf[INET_ADDRSTRLEN];
unsigned int timestamp;
unsigned int *rtpheader;
/* Cache where the header will go */
res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
return &ast_null_frame;
if (res < hdrlen) {
ast_log(LOG_WARNING, "RTP Read too short\n");
return &ast_null_frame;
/* Get fields */
seqno = ntohl(rtpheader[0]);
/* Check RTP version */
version = (seqno & 0xC0000000) >> 30;
if (!version) {
if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res) == STUN_ACCEPT) &&
(!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
memcpy(&rtp->them, &sin, sizeof(rtp->them));
}
return &ast_null_frame;
}
if (version != 2)
return &ast_null_frame;
/* Ignore if the other side hasn't been given an address
yet. */
if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
return &ast_null_frame;
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->rtcp->them, &sin, sizeof(rtp->rtcp->them));
rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
}
Mark Spencer
committed
rtp->rxseqno = 0;
Kevin P. Fleming
committed
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));
padding = seqno & (1 << 29);
mark = seqno & (1 << 23);
seqno &= 0xffff;
timestamp = ntohl(rtpheader[1]);
ssrc = ntohl(rtpheader[2]);
if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
if (option_verbose > 1)
ast_verbose(VERBOSE_PREFIX_2 "Forcing Marker bit, because SSRC has changed\n");
mark = 1;
}
rtp->rxssrc = ssrc;
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);
return &ast_null_frame;
rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
tseqno = rtp->lastrxseqno +1;
/* This is the first RTP packet successfully received from source */
rtp->seedrxseqno = seqno;
}
/* Schedule transmission of Receiver Report */
rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
}
if (tseqno > RTP_SEQ_MOD) { /* if tseqno is greater than RTP_SEQ_MOD it would indicate that the sender cycled */
rtp->cycles += RTP_SEQ_MOD;
ast_verbose("SEQNO cycled: %u\t%d\n", rtp->cycles, seqno);
}
rtp->lastrxseqno = seqno;
rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
ast_verbose("Got RTP packet from %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\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);