remove rule for running bootstrap, it's only safe to run it manually now
[asterisk-bristuff.git] / rtp.c
blobb80fb306968a7e7a73e1115930eee33cfbdede02
1 /*
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.
19 /*!
20 * \file
22 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
24 * \author Mark Spencer <markster@digium.com>
26 * \note RTP is defined in RFC 3550.
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/time.h>
33 #include <signal.h>
34 #include <errno.h>
35 #include <unistd.h>
36 #include <netinet/in.h>
37 #include <sys/time.h>
38 #include <sys/socket.h>
39 #include <arpa/inet.h>
40 #include <fcntl.h>
42 #include "asterisk.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
62 #define RTP_MTU 1200
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 */
72 #ifdef SO_NO_CHECK
73 static int nochecksums = 0;
74 #endif
76 /*! \brief The value of each payload format mapping: */
77 struct rtpPayloadType {
78 int isAstFormat; /*!< whether the following code is an AST_FORMAT */
79 int code;
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 */
90 struct ast_rtp {
91 int s;
92 char resp;
93 struct ast_frame f;
94 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
95 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
96 unsigned int lastts;
97 unsigned int lastdigitts;
98 unsigned int lastrxts;
99 unsigned int lastividtimestamp;
100 unsigned int lastovidtimestamp;
101 unsigned int lasteventseqn;
102 unsigned int lasteventendseqn;
103 int lasttxformat;
104 int lastrxformat;
105 int dtmfcount;
106 unsigned int dtmfduration;
107 int nat;
108 unsigned int flags;
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;
115 int *ioid;
116 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
117 unsigned short rxseqno;
118 struct sched_context *sched;
119 struct io_context *io;
120 void *data;
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.
139 struct ast_rtcp {
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)
150 return rtp->s;
153 int ast_rtcp_fd(struct ast_rtp *rtp)
155 if (rtp->rtcp)
156 return rtp->rtcp->s;
157 return -1;
160 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
162 rtp->data = 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)
172 rtp->nat = 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) {
180 if (option_debug)
181 ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
182 rtp->resp = 0;
183 rtp->dtmfduration = 0;
184 return &ast_null_frame;
186 if (option_debug)
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;
191 } else {
192 rtp->f.frametype = AST_FRAME_DTMF;
193 rtp->f.subclass = rtp->resp;
195 rtp->f.datalen = 0;
196 rtp->f.samples = 0;
197 rtp->f.mallocd = 0;
198 rtp->f.src = "RTP";
199 rtp->resp = 0;
200 rtp->dtmfduration = 0;
201 return &rtp->f;
205 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
207 if (rtpdebug == 0)
208 return 0;
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))
213 return 0;
215 return 1;
218 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
220 unsigned int event;
221 char resp = 0;
222 struct ast_frame *f = NULL;
223 event = ntohl(*((unsigned int *)(data)));
224 event &= 0x001F;
225 if (option_debug > 2 || rtpdebug)
226 ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
227 if (event < 10) {
228 resp = '0' + event;
229 } else if (event < 11) {
230 resp = '*';
231 } else if (event < 12) {
232 resp = '#';
233 } else if (event < 16) {
234 resp = 'A' + (event - 12);
235 } else if (event < 17) {
236 resp = 'X';
238 if (rtp->resp && (rtp->resp != resp)) {
239 f = send_dtmf(rtp);
241 rtp->resp = resp;
242 rtp->dtmfcount = dtmftimeout;
243 return f;
246 /*!
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".
251 * \param rtp
252 * \param data
253 * \param len
254 * \param seqno
255 * \returns
257 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
259 unsigned int event;
260 unsigned int event_end;
261 unsigned int duration;
262 char resp = 0;
263 struct ast_frame *f = NULL;
265 event = ntohl(*((unsigned int *)(data)));
266 event >>= 24;
267 event_end = ntohl(*((unsigned int *)(data)));
268 event_end <<= 8;
269 event_end >>= 24;
270 duration = ntohl(*((unsigned int *)(data)));
271 duration &= 0xFFFF;
272 if (rtpdebug || option_debug > 2)
273 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
274 if (event < 10) {
275 resp = '0' + event;
276 } else if (event < 11) {
277 resp = '*';
278 } else if (event < 12) {
279 resp = '#';
280 } else if (event < 16) {
281 resp = 'A' + (event - 12);
282 } else if (event < 17) { /* Event 16: Hook flash */
283 resp = 'X';
285 if (rtp->resp && (rtp->resp != resp)) {
286 f = send_dtmf(rtp);
287 } else if(event_end & 0x80) {
288 if (rtp->resp) {
289 if(rtp->lasteventendseqn != seqno) {
290 f = send_dtmf(rtp);
291 rtp->lasteventendseqn = seqno;
293 rtp->resp = 0;
295 resp = 0;
296 duration = 0;
297 } else if (rtp->resp && rtp->dtmfduration && (duration < rtp->dtmfduration)) {
298 f = send_dtmf(rtp);
300 if (!(event_end & 0x80))
301 rtp->resp = resp;
302 rtp->dtmfcount = dtmftimeout;
303 rtp->dtmfduration = duration;
304 return f;
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 */
319 if (rtpdebug)
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 */
331 if (!len)
332 return NULL;
333 if (len < 24) {
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);
338 } else {
339 rtp->f.data = NULL;
340 rtp->f.offset = 0;
341 rtp->f.datalen = 0;
343 rtp->f.frametype = AST_FRAME_CNG;
344 rtp->f.subclass = data[0] & 0x7f;
345 rtp->f.datalen = len - 1;
346 rtp->f.samples = 0;
347 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
348 f = &rtp->f;
349 return f;
352 static int rtpread(int *id, int fd, short events, void *cbdata)
354 struct ast_rtp *rtp = cbdata;
355 struct ast_frame *f;
356 f = ast_rtp_read(rtp);
357 if (f) {
358 if (rtp->callback)
359 rtp->callback(rtp, f, rtp->data);
361 return 1;
364 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
366 socklen_t len;
367 int hdrlen = 8;
368 int res;
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;
376 len = sizeof(sin);
378 res = recvfrom(rtp->rtcp->s, rtcpdata, sizeof(rtcpdata),
379 0, (struct sockaddr *)&sin, &len);
381 if (res < 0) {
382 if (errno != EAGAIN)
383 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
384 if (errno == EBADF)
385 CRASH;
386 return &ast_null_frame;
389 if (res < hdrlen) {
390 ast_log(LOG_WARNING, "RTP Read too short\n");
391 return &ast_null_frame;
394 if (rtp->nat) {
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));
403 if (option_debug)
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)
421 int res;
422 struct sockaddr_in sin;
423 socklen_t len;
424 unsigned int seqno;
425 int version;
426 int payloadtype;
427 int hdrlen = 12;
428 int padding;
429 int mark;
430 int ext;
431 int x;
432 char iabuf[INET_ADDRSTRLEN];
433 unsigned int timestamp;
434 unsigned int *rtpheader;
435 struct rtpPayloadType rtpPT;
437 len = sizeof(sin);
439 /* Cache where the header will go */
440 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
441 0, (struct sockaddr *)&sin, &len);
444 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
445 if (res < 0) {
446 if (errno != EAGAIN)
447 ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
448 if (errno == EBADF)
449 CRASH;
450 return &ast_null_frame;
452 if (res < hdrlen) {
453 ast_log(LOG_WARNING, "RTP Read too short\n");
454 return &ast_null_frame;
457 /* Ignore if the other side hasn't been given an address
458 yet. */
459 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
460 return &ast_null_frame;
462 if (rtp->nat) {
463 /* Send to whoever sent to us */
464 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
465 (rtp->them.sin_port != sin.sin_port)) {
466 rtp->them = sin;
467 rtp->rxseqno = 0;
468 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
469 if (option_debug || rtpdebug)
470 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));
474 /* Get fields */
475 seqno = ntohl(rtpheader[0]);
477 /* Check RTP version */
478 version = (seqno & 0xC0000000) >> 30;
479 if (version != 2)
480 return &ast_null_frame;
482 payloadtype = (seqno & 0x7f0000) >> 16;
483 padding = seqno & (1 << 29);
484 mark = seqno & (1 << 23);
485 ext = seqno & (1 << 28);
486 seqno &= 0xffff;
487 timestamp = ntohl(rtpheader[1]);
489 if (padding) {
490 /* Remove padding bytes */
491 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
494 if (ext) {
495 /* RTP Extension present */
496 hdrlen += 4;
497 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
500 if (res < hdrlen) {
501 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
502 return &ast_null_frame;
505 if(rtp_debug_test_addr(&sin))
506 ast_verbose("Got RTP packet from %s:%d (type %d, seq %d, ts %d, len %d)\n"
507 , ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
509 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
510 if (!rtpPT.isAstFormat) {
511 struct ast_frame *f = NULL;
513 /* This is special in-band data that's not one of our codecs */
514 if (rtpPT.code == AST_RTP_DTMF) {
515 /* It's special -- rfc2833 process it */
516 if(rtp_debug_test_addr(&sin)) {
517 unsigned char *data;
518 unsigned int event;
519 unsigned int event_end;
520 unsigned int duration;
521 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
522 event = ntohl(*((unsigned int *)(data)));
523 event >>= 24;
524 event_end = ntohl(*((unsigned int *)(data)));
525 event_end <<= 8;
526 event_end >>= 24;
527 duration = ntohl(*((unsigned int *)(data)));
528 duration &= 0xFFFF;
529 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);
531 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
532 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
533 rtp->lasteventseqn = seqno;
535 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
536 /* It's really special -- process it the Cisco way */
537 if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
538 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
539 rtp->lasteventseqn = seqno;
541 } else if (rtpPT.code == AST_RTP_CN) {
542 /* Comfort Noise */
543 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
544 } else {
545 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
547 return f ? f : &ast_null_frame;
549 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
550 rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : AST_FRAME_VIDEO;
552 if (!rtp->lastrxts)
553 rtp->lastrxts = timestamp;
555 if (rtp->rxseqno) {
556 for (x=rtp->rxseqno + 1; x < seqno; x++) {
557 /* Queue empty frames */
558 rtp->f.mallocd = 0;
559 rtp->f.datalen = 0;
560 rtp->f.data = NULL;
561 rtp->f.offset = 0;
562 rtp->f.samples = 0;
563 rtp->f.src = "RTPMissedFrame";
566 rtp->rxseqno = seqno;
568 if (rtp->dtmfcount) {
569 #if 0
570 printf("dtmfcount was %d\n", rtp->dtmfcount);
571 #endif
572 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
573 if (rtp->dtmfcount < 0)
574 rtp->dtmfcount = 0;
575 #if 0
576 if (dtmftimeout != rtp->dtmfcount)
577 printf("dtmfcount is %d\n", rtp->dtmfcount);
578 #endif
580 rtp->lastrxts = timestamp;
582 /* Send any pending DTMF */
583 if (rtp->resp && !rtp->dtmfcount) {
584 if (option_debug)
585 ast_log(LOG_DEBUG, "Sending pending DTMF\n");
586 return send_dtmf(rtp);
588 rtp->f.mallocd = 0;
589 rtp->f.datalen = res - hdrlen;
590 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
591 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
592 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
593 rtp->f.samples = ast_codec_get_samples(&rtp->f);
594 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
595 ast_frame_byteswap_be(&rtp->f);
596 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
597 } else {
598 /* Video -- samples is # of samples vs. 90000 */
599 if (!rtp->lastividtimestamp)
600 rtp->lastividtimestamp = timestamp;
601 rtp->f.samples = timestamp - rtp->lastividtimestamp;
602 rtp->lastividtimestamp = timestamp;
603 rtp->f.delivery.tv_sec = 0;
604 rtp->f.delivery.tv_usec = 0;
605 if (mark)
606 rtp->f.subclass |= 0x1;
609 rtp->f.src = "RTP";
610 return &rtp->f;
613 /* The following array defines the MIME Media type (and subtype) for each
614 of our codecs, or RTP-specific data type. */
615 static struct {
616 struct rtpPayloadType payloadType;
617 char* type;
618 char* subtype;
619 } mimeTypes[] = {
620 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
621 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
622 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
623 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
624 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
625 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
626 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
627 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
628 {{1, AST_FORMAT_G729A}, "audio", "G729"},
629 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
630 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
631 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
632 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
633 {{0, AST_RTP_CN}, "audio", "CN"},
634 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
635 {{1, AST_FORMAT_PNG}, "video", "PNG"},
636 {{1, AST_FORMAT_H261}, "video", "H261"},
637 {{1, AST_FORMAT_H263}, "video", "H263"},
638 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
639 {{1, AST_FORMAT_H264}, "video", "H264"},
642 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
643 also, our own choices for dynamic payload types. This is our master
644 table for transmission */
645 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
646 [0] = {1, AST_FORMAT_ULAW},
647 #ifdef USE_DEPRECATED_G726
648 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
649 #endif
650 [3] = {1, AST_FORMAT_GSM},
651 [4] = {1, AST_FORMAT_G723_1},
652 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
653 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
654 [7] = {1, AST_FORMAT_LPC10},
655 [8] = {1, AST_FORMAT_ALAW},
656 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
657 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
658 [13] = {0, AST_RTP_CN},
659 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
660 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
661 [18] = {1, AST_FORMAT_G729A},
662 [19] = {0, AST_RTP_CN}, /* Also used for CN */
663 [26] = {1, AST_FORMAT_JPEG},
664 [31] = {1, AST_FORMAT_H261},
665 [34] = {1, AST_FORMAT_H263},
666 [103] = {1, AST_FORMAT_H263_PLUS},
667 [97] = {1, AST_FORMAT_ILBC},
668 [99] = {1, AST_FORMAT_H264},
669 [101] = {0, AST_RTP_DTMF},
670 [110] = {1, AST_FORMAT_SPEEX},
671 [111] = {1, AST_FORMAT_G726},
672 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
675 void ast_rtp_pt_clear(struct ast_rtp* rtp)
677 int i;
678 if (!rtp)
679 return;
681 for (i = 0; i < MAX_RTP_PT; ++i) {
682 rtp->current_RTP_PT[i].isAstFormat = 0;
683 rtp->current_RTP_PT[i].code = 0;
686 rtp->rtp_lookup_code_cache_isAstFormat = 0;
687 rtp->rtp_lookup_code_cache_code = 0;
688 rtp->rtp_lookup_code_cache_result = 0;
691 void ast_rtp_pt_default(struct ast_rtp* rtp)
693 int i;
695 /* Initialize to default payload types */
696 for (i = 0; i < MAX_RTP_PT; ++i) {
697 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
698 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
701 rtp->rtp_lookup_code_cache_isAstFormat = 0;
702 rtp->rtp_lookup_code_cache_code = 0;
703 rtp->rtp_lookup_code_cache_result = 0;
706 static void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
708 int i;
709 /* Copy payload types from source to destination */
710 for (i=0; i < MAX_RTP_PT; ++i) {
711 dest->current_RTP_PT[i].isAstFormat =
712 src->current_RTP_PT[i].isAstFormat;
713 dest->current_RTP_PT[i].code =
714 src->current_RTP_PT[i].code;
716 dest->rtp_lookup_code_cache_isAstFormat = 0;
717 dest->rtp_lookup_code_cache_code = 0;
718 dest->rtp_lookup_code_cache_result = 0;
721 /*! \brief Get channel driver interface structure */
722 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
724 struct ast_rtp_protocol *cur = NULL;
726 AST_LIST_LOCK(&protos);
727 AST_LIST_TRAVERSE(&protos, cur, list) {
728 if (cur->type == chan->tech->type)
729 break;
731 AST_LIST_UNLOCK(&protos);
733 return cur;
736 int ast_rtp_early_media(struct ast_channel *dest, struct ast_channel *src)
738 struct ast_rtp *destp, *srcp=NULL; /* Audio RTP Channels */
739 struct ast_rtp *vdestp, *vsrcp=NULL; /* Video RTP channels */
740 struct ast_rtp_protocol *destpr, *srcpr=NULL;
741 int srccodec;
742 /* Lock channels */
743 ast_channel_lock(dest);
744 if (src) {
745 while(ast_channel_trylock(src)) {
746 ast_channel_unlock(dest);
747 usleep(1);
748 ast_channel_lock(dest);
752 /* Find channel driver interfaces */
753 destpr = get_proto(dest);
754 if (src)
755 srcpr = get_proto(src);
756 if (!destpr) {
757 if (option_debug)
758 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
759 ast_channel_unlock(dest);
760 if (src)
761 ast_channel_unlock(src);
762 return 0;
764 if (!srcpr) {
765 if (option_debug)
766 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
767 ast_channel_unlock(dest);
768 if (src)
769 ast_channel_unlock(src);
770 return 0;
773 /* Get audio and video interface (if native bridge is possible) */
774 destp = destpr->get_rtp_info(dest);
775 vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
776 if (srcpr) {
777 srcp = srcpr->get_rtp_info(src);
778 vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
781 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
782 if (!destp) {
783 /* Somebody doesn't want to play... */
784 ast_channel_unlock(dest);
785 if (src)
786 ast_channel_unlock(src);
787 return 0;
789 if (srcpr && srcpr->get_codec)
790 srccodec = srcpr->get_codec(src);
791 else
792 srccodec = 0;
793 /* Consider empty media as non-existant */
794 if (srcp && !srcp->them.sin_addr.s_addr)
795 srcp = NULL;
796 /* Bridge early media */
797 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, srcp ? ast_test_flag(srcp, FLAG_NAT_ACTIVE) : 0))
798 ast_log(LOG_WARNING, "Channel '%s' failed to send early media to '%s'\n", dest->name, src ? src->name : "<unspecified>");
799 ast_channel_unlock(dest);
800 if (src)
801 ast_channel_unlock(src);
802 if (option_debug)
803 ast_log(LOG_DEBUG, "Setting early media SDP of '%s' with that of '%s'\n", dest->name, src ? src->name : "<unspecified>");
804 return 1;
807 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
809 struct ast_rtp *destp, *srcp; /* Audio RTP Channels */
810 struct ast_rtp *vdestp, *vsrcp; /* Video RTP channels */
811 struct ast_rtp_protocol *destpr, *srcpr;
812 int srccodec;
813 /* Lock channels */
814 ast_channel_lock(dest);
815 while(ast_channel_trylock(src)) {
816 ast_channel_unlock(dest);
817 usleep(1);
818 ast_channel_lock(dest);
821 /* Find channel driver interfaces */
822 destpr = get_proto(dest);
823 srcpr = get_proto(src);
824 if (!destpr) {
825 if (option_debug)
826 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
827 ast_channel_unlock(dest);
828 ast_channel_unlock(src);
829 return 0;
831 if (!srcpr) {
832 if (option_debug)
833 ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
834 ast_channel_unlock(dest);
835 ast_channel_unlock(src);
836 return 0;
839 /* Get audio and video interface (if native bridge is possible) */
840 destp = destpr->get_rtp_info(dest);
841 vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
842 srcp = srcpr->get_rtp_info(src);
843 vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
845 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
846 if (!destp || !srcp) {
847 /* Somebody doesn't want to play... */
848 ast_channel_unlock(dest);
849 ast_channel_unlock(src);
850 return 0;
852 ast_rtp_pt_copy(destp, srcp);
853 if (vdestp && vsrcp)
854 ast_rtp_pt_copy(vdestp, vsrcp);
855 if (srcpr->get_codec)
856 srccodec = srcpr->get_codec(src);
857 else
858 srccodec = 0;
859 if (media) {
860 /* Bridge early media */
861 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
862 ast_log(LOG_WARNING, "Channel '%s' failed to send early media to '%s'\n", dest->name, src->name);
864 ast_channel_unlock(dest);
865 ast_channel_unlock(src);
866 if (option_debug)
867 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
868 return 1;
871 /*! \brief Make a note of a RTP paymoad type that was seen in a SDP "m=" line.
872 * By default, use the well-known value for this type (although it may
873 * still be set to a different value by a subsequent "a=rtpmap:" line)
875 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
877 if (pt < 0 || pt > MAX_RTP_PT)
878 return; /* bogus payload type */
880 if (static_RTP_PT[pt].code != 0) {
881 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
885 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
886 a SDP "a=rtpmap:" line. */
887 void ast_rtp_set_rtpmap_type(struct ast_rtp* rtp, int pt,
888 char* mimeType, char* mimeSubtype)
890 int i;
892 if (pt < 0 || pt > MAX_RTP_PT)
893 return; /* bogus payload type */
895 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
896 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
897 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
898 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
899 return;
904 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
905 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
906 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
907 int* astFormats, int* nonAstFormats) {
908 int pt;
910 *astFormats = *nonAstFormats = 0;
911 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
912 if (rtp->current_RTP_PT[pt].isAstFormat) {
913 *astFormats |= rtp->current_RTP_PT[pt].code;
914 } else {
915 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
920 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
922 struct rtpPayloadType result;
924 result.isAstFormat = result.code = 0;
925 if (pt < 0 || pt > MAX_RTP_PT)
926 return result; /* bogus payload type */
928 /* Start with the negotiated codecs */
929 result = rtp->current_RTP_PT[pt];
931 /* If it doesn't exist, check our static RTP type list, just in case */
932 if (!result.code)
933 result = static_RTP_PT[pt];
934 return result;
937 /*! \brief Looks up an RTP code out of our *static* outbound list */
938 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
940 int pt;
942 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
943 code == rtp->rtp_lookup_code_cache_code) {
945 /* Use our cached mapping, to avoid the overhead of the loop below */
946 return rtp->rtp_lookup_code_cache_result;
949 /* Check the dynamic list first */
950 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
951 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
952 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
953 rtp->rtp_lookup_code_cache_code = code;
954 rtp->rtp_lookup_code_cache_result = pt;
955 return pt;
959 /* Then the static list */
960 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
961 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
962 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
963 rtp->rtp_lookup_code_cache_code = code;
964 rtp->rtp_lookup_code_cache_result = pt;
965 return pt;
968 return -1;
971 char* ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code)
974 int i;
976 for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
977 if (mimeTypes[i].payloadType.code == code && mimeTypes[i].payloadType.isAstFormat == isAstFormat)
978 return mimeTypes[i].subtype;
980 return "";
983 char *ast_rtp_lookup_mime_multiple(char *buf, int size, const int capability, const int isAstFormat)
985 int format;
986 unsigned len;
987 char *end = buf;
988 char *start = buf;
990 if (!buf || !size)
991 return NULL;
993 snprintf(end, size, "0x%x (", capability);
995 len = strlen(end);
996 end += len;
997 size -= len;
998 start = end;
1000 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
1001 if (capability & format) {
1002 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format);
1003 snprintf(end, size, "%s|", name);
1004 len = strlen(end);
1005 end += len;
1006 size -= len;
1010 if (start == end)
1011 snprintf(start, size, "nothing)");
1012 else if (size > 1)
1013 *(end -1) = ')';
1015 return buf;
1018 static int rtp_socket(void)
1020 int s;
1021 long flags;
1022 s = socket(AF_INET, SOCK_DGRAM, 0);
1023 if (s > -1) {
1024 flags = fcntl(s, F_GETFL);
1025 fcntl(s, F_SETFL, flags | O_NONBLOCK);
1026 #ifdef SO_NO_CHECK
1027 if (nochecksums)
1028 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
1029 #endif
1031 return s;
1035 * \brief Initialize a new RTCP session.
1037 * \returns The newly initialized RTCP session.
1039 static struct ast_rtcp *ast_rtcp_new(void)
1041 struct ast_rtcp *rtcp;
1043 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
1044 return NULL;
1045 rtcp->s = rtp_socket();
1046 rtcp->us.sin_family = AF_INET;
1047 if (rtcp->s < 0) {
1048 free(rtcp);
1049 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
1050 return NULL;
1053 return rtcp;
1056 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
1058 struct ast_rtp *rtp;
1059 int x;
1060 int first;
1061 int startplace;
1063 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
1064 return NULL;
1065 rtp->them.sin_family = AF_INET;
1066 rtp->us.sin_family = AF_INET;
1067 rtp->s = rtp_socket();
1068 rtp->ssrc = ast_random();
1069 rtp->seqno = ast_random() & 0xffff;
1070 if (rtp->s < 0) {
1071 free(rtp);
1072 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1073 return NULL;
1075 if (sched && rtcpenable) {
1076 rtp->sched = sched;
1077 rtp->rtcp = ast_rtcp_new();
1080 /* Select a random port number in the range of possible RTP */
1081 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
1082 x = x & ~1;
1083 /* Save it for future references. */
1084 startplace = x;
1085 /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1086 for (;;) {
1087 /* Must be an even port number by RTP spec */
1088 rtp->us.sin_port = htons(x);
1089 rtp->us.sin_addr = addr;
1090 /* If there's rtcp, initialize it as well. */
1091 if (rtp->rtcp)
1092 rtp->rtcp->us.sin_port = htons(x + 1);
1093 /* Try to bind it/them. */
1094 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1095 (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1096 break;
1097 if (!first) {
1098 /* Primary bind succeeded! Gotta recreate it */
1099 close(rtp->s);
1100 rtp->s = rtp_socket();
1102 if (errno != EADDRINUSE) {
1103 /* We got an error that wasn't expected, abort! */
1104 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1105 close(rtp->s);
1106 if (rtp->rtcp) {
1107 close(rtp->rtcp->s);
1108 free(rtp->rtcp);
1110 free(rtp);
1111 return NULL;
1113 /* The port was used, increment it (by two). */
1114 x += 2;
1115 /* Did we go over the limit ? */
1116 if (x > rtpend)
1117 /* then, start from the begingig. */
1118 x = (rtpstart + 1) & ~1;
1119 /* Check if we reached the place were we started. */
1120 if (x == startplace) {
1121 /* If so, there's no ports available. */
1122 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1123 close(rtp->s);
1124 if (rtp->rtcp) {
1125 close(rtp->rtcp->s);
1126 free(rtp->rtcp);
1128 free(rtp);
1129 return NULL;
1132 if (io && sched && callbackmode) {
1133 /* Operate this one in a callback mode */
1134 rtp->sched = sched;
1135 rtp->io = io;
1136 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1138 ast_rtp_pt_default(rtp);
1139 return rtp;
1142 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1144 struct in_addr ia;
1146 memset(&ia, 0, sizeof(ia));
1147 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1150 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1152 int res;
1154 if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos))))
1155 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1156 return res;
1159 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1161 rtp->them.sin_port = them->sin_port;
1162 rtp->them.sin_addr = them->sin_addr;
1163 if (rtp->rtcp) {
1164 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1165 rtp->rtcp->them.sin_addr = them->sin_addr;
1167 rtp->rxseqno = 0;
1170 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1172 if ((them->sin_family != AF_INET) ||
1173 (them->sin_port != rtp->them.sin_port) ||
1174 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
1175 them->sin_family = AF_INET;
1176 them->sin_port = rtp->them.sin_port;
1177 them->sin_addr = rtp->them.sin_addr;
1178 return 1;
1180 return 0;
1183 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1185 *us = rtp->us;
1188 void ast_rtp_stop(struct ast_rtp *rtp)
1190 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1191 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1192 if (rtp->rtcp) {
1193 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1194 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1198 void ast_rtp_reset(struct ast_rtp *rtp)
1200 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1201 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1202 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1203 rtp->lastts = 0;
1204 rtp->lastdigitts = 0;
1205 rtp->lastrxts = 0;
1206 rtp->lastividtimestamp = 0;
1207 rtp->lastovidtimestamp = 0;
1208 rtp->lasteventseqn = 0;
1209 rtp->lasteventendseqn = 0;
1210 rtp->lasttxformat = 0;
1211 rtp->lastrxformat = 0;
1212 rtp->dtmfcount = 0;
1213 rtp->dtmfduration = 0;
1214 rtp->seqno = 0;
1215 rtp->rxseqno = 0;
1218 void ast_rtp_destroy(struct ast_rtp *rtp)
1220 if (rtp->smoother)
1221 ast_smoother_free(rtp->smoother);
1222 if (rtp->ioid)
1223 ast_io_remove(rtp->io, rtp->ioid);
1224 if (rtp->s > -1)
1225 close(rtp->s);
1226 if (rtp->rtcp) {
1227 close(rtp->rtcp->s);
1228 free(rtp->rtcp);
1230 free(rtp);
1233 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1235 struct timeval t;
1236 long ms;
1237 if (ast_tvzero(rtp->txcore)) {
1238 rtp->txcore = ast_tvnow();
1239 /* Round to 20ms for nice, pretty timestamps */
1240 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1242 /* Use previous txcore if available */
1243 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
1244 ms = ast_tvdiff_ms(t, rtp->txcore);
1245 if (ms < 0)
1246 ms = 0;
1247 /* Use what we just got for next time */
1248 rtp->txcore = t;
1249 return (unsigned int) ms;
1252 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
1254 unsigned int *rtpheader;
1255 int hdrlen = 12;
1256 int res;
1257 int x;
1258 int payload;
1259 char data[256];
1260 char iabuf[INET_ADDRSTRLEN];
1262 if ((digit <= '9') && (digit >= '0'))
1263 digit -= '0';
1264 else if (digit == '*')
1265 digit = 10;
1266 else if (digit == '#')
1267 digit = 11;
1268 else if ((digit >= 'A') && (digit <= 'D'))
1269 digit = digit - 'A' + 12;
1270 else if ((digit >= 'a') && (digit <= 'd'))
1271 digit = digit - 'a' + 12;
1272 else {
1273 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
1274 return -1;
1276 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
1278 /* If we have no peer, return immediately */
1279 if (!rtp->them.sin_addr.s_addr)
1280 return 0;
1282 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1284 /* Get a pointer to the header */
1285 rtpheader = (unsigned int *)data;
1286 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
1287 rtpheader[1] = htonl(rtp->lastdigitts);
1288 rtpheader[2] = htonl(rtp->ssrc);
1289 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
1290 for (x = 0; x < 6; x++) {
1291 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1292 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
1293 if (res < 0)
1294 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
1295 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1296 ntohs(rtp->them.sin_port), strerror(errno));
1297 if (rtp_debug_test_addr(&rtp->them))
1298 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %u, ts %u, len %u)\n",
1299 ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1300 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
1302 /* Sequence number of last two end packets does not get incremented */
1303 if (x < 3)
1304 rtp->seqno++;
1305 /* Clear marker bit and set seqno */
1306 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
1307 /* For the last three packets, set the duration and the end bit */
1308 if (x == 2) {
1309 #if 0
1310 /* No, this is wrong... Do not increment lastdigitts, that's not according
1311 to the RFC, as best we can determine */
1312 rtp->lastdigitts++; /* or else the SPA3000 will click instead of beeping... */
1313 rtpheader[1] = htonl(rtp->lastdigitts);
1314 #endif
1315 /* Make duration 800 (100ms) */
1316 rtpheader[3] |= htonl((800));
1317 /* Set the End bit */
1318 rtpheader[3] |= htonl((1 << 23));
1321 /* Increment the digit timestamp by 120ms, to ensure that digits
1322 sent sequentially with no intervening non-digit packets do not
1323 get sent with the same timestamp, and that sequential digits
1324 have some 'dead air' in between them
1326 rtp->lastdigitts += 960;
1327 /* Increment the sequence number to reflect the last packet
1328 that was sent
1330 rtp->seqno++;
1331 return 0;
1334 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
1336 unsigned int *rtpheader;
1337 int hdrlen = 12;
1338 int res;
1339 int payload;
1340 char data[256];
1341 char iabuf[INET_ADDRSTRLEN];
1342 level = 127 - (level & 0x7f);
1343 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
1345 /* If we have no peer, return immediately */
1346 if (!rtp->them.sin_addr.s_addr)
1347 return 0;
1349 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1351 /* Get a pointer to the header */
1352 rtpheader = (unsigned int *)data;
1353 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
1354 rtpheader[1] = htonl(rtp->lastts);
1355 rtpheader[2] = htonl(rtp->ssrc);
1356 data[12] = level;
1357 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1358 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1359 if (res <0)
1360 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));
1361 if(rtp_debug_test_addr(&rtp->them))
1362 ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %d, len %d)\n"
1363 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
1366 return 0;
1369 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
1371 unsigned char *rtpheader;
1372 char iabuf[INET_ADDRSTRLEN];
1373 int hdrlen = 12;
1374 int res;
1375 unsigned int ms;
1376 int pred;
1377 int mark = 0;
1379 ms = calc_txstamp(rtp, &f->delivery);
1380 /* Default prediction */
1381 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
1382 pred = rtp->lastts + f->samples;
1384 /* Re-calculate last TS */
1385 rtp->lastts = rtp->lastts + ms * 8;
1386 if (ast_tvzero(f->delivery)) {
1387 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
1388 and if so, go with our prediction */
1389 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
1390 rtp->lastts = pred;
1391 else {
1392 if (option_debug > 2)
1393 ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
1394 mark = 1;
1397 } else {
1398 mark = f->subclass & 0x1;
1399 pred = rtp->lastovidtimestamp + f->samples;
1400 /* Re-calculate last TS */
1401 rtp->lastts = rtp->lastts + ms * 90;
1402 /* If it's close to our prediction, go for it */
1403 if (ast_tvzero(f->delivery)) {
1404 if (abs(rtp->lastts - pred) < 7200) {
1405 rtp->lastts = pred;
1406 rtp->lastovidtimestamp += f->samples;
1407 } else {
1408 if (option_debug > 2)
1409 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);
1410 rtp->lastovidtimestamp = rtp->lastts;
1414 /* If the timestamp for non-digit packets has moved beyond the timestamp
1415 for digits, update the digit timestamp.
1417 if (rtp->lastts > rtp->lastdigitts)
1418 rtp->lastdigitts = rtp->lastts;
1420 /* Get a pointer to the header */
1421 rtpheader = (unsigned char *)(f->data - hdrlen);
1423 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
1424 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
1425 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
1427 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1428 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1429 if (res <0) {
1430 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1431 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));
1432 } else if ((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) {
1433 /* Only give this error message once if we are not RTP debugging */
1434 if (option_debug || rtpdebug)
1435 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));
1436 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
1440 if(rtp_debug_test_addr(&rtp->them))
1441 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %u, ts %u, len %u)\n"
1442 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
1445 rtp->seqno++;
1447 return 0;
1450 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
1452 struct ast_frame *f;
1453 int codec;
1454 int hdrlen = 12;
1455 int subclass;
1458 /* If we have no peer, return immediately */
1459 if (!rtp->them.sin_addr.s_addr)
1460 return 0;
1462 /* If there is no data length, return immediately */
1463 if (!_f->datalen)
1464 return 0;
1466 /* Make sure we have enough space for RTP header */
1467 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
1468 ast_log(LOG_WARNING, "RTP can only send voice\n");
1469 return -1;
1472 subclass = _f->subclass;
1473 if (_f->frametype == AST_FRAME_VIDEO)
1474 subclass &= ~0x1;
1476 codec = ast_rtp_lookup_code(rtp, 1, subclass);
1477 if (codec < 0) {
1478 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
1479 return -1;
1482 if (rtp->lasttxformat != subclass) {
1483 /* New format, reset the smoother */
1484 if (option_debug)
1485 ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
1486 rtp->lasttxformat = subclass;
1487 if (rtp->smoother)
1488 ast_smoother_free(rtp->smoother);
1489 rtp->smoother = NULL;
1493 switch(subclass) {
1494 case AST_FORMAT_SLINEAR:
1495 if (!rtp->smoother) {
1496 rtp->smoother = ast_smoother_new(320);
1498 if (!rtp->smoother) {
1499 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1500 return -1;
1502 ast_smoother_feed_be(rtp->smoother, _f);
1504 while((f = ast_smoother_read(rtp->smoother)))
1505 ast_rtp_raw_write(rtp, f, codec);
1506 break;
1507 case AST_FORMAT_ULAW:
1508 case AST_FORMAT_ALAW:
1509 if (!rtp->smoother) {
1510 rtp->smoother = ast_smoother_new(160);
1512 if (!rtp->smoother) {
1513 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1514 return -1;
1516 ast_smoother_feed(rtp->smoother, _f);
1518 while((f = ast_smoother_read(rtp->smoother)))
1519 ast_rtp_raw_write(rtp, f, codec);
1520 break;
1521 case AST_FORMAT_ADPCM:
1522 case AST_FORMAT_G726:
1523 if (!rtp->smoother) {
1524 rtp->smoother = ast_smoother_new(80);
1526 if (!rtp->smoother) {
1527 ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1528 return -1;
1530 ast_smoother_feed(rtp->smoother, _f);
1532 while((f = ast_smoother_read(rtp->smoother)))
1533 ast_rtp_raw_write(rtp, f, codec);
1534 break;
1535 case AST_FORMAT_G729A:
1536 if (!rtp->smoother) {
1537 rtp->smoother = ast_smoother_new(20);
1538 if (rtp->smoother)
1539 ast_smoother_set_flags(rtp->smoother, AST_SMOOTHER_FLAG_G729);
1541 if (!rtp->smoother) {
1542 ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
1543 return -1;
1545 ast_smoother_feed(rtp->smoother, _f);
1547 while((f = ast_smoother_read(rtp->smoother)))
1548 ast_rtp_raw_write(rtp, f, codec);
1549 break;
1550 case AST_FORMAT_GSM:
1551 if (!rtp->smoother) {
1552 rtp->smoother = ast_smoother_new(33);
1554 if (!rtp->smoother) {
1555 ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
1556 return -1;
1558 ast_smoother_feed(rtp->smoother, _f);
1559 while((f = ast_smoother_read(rtp->smoother)))
1560 ast_rtp_raw_write(rtp, f, codec);
1561 break;
1562 case AST_FORMAT_ILBC:
1563 if (!rtp->smoother) {
1564 rtp->smoother = ast_smoother_new(50);
1566 if (!rtp->smoother) {
1567 ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
1568 return -1;
1570 ast_smoother_feed(rtp->smoother, _f);
1571 while((f = ast_smoother_read(rtp->smoother)))
1572 ast_rtp_raw_write(rtp, f, codec);
1573 break;
1574 default:
1575 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
1576 /* fall through to... */
1577 case AST_FORMAT_H261:
1578 case AST_FORMAT_H263:
1579 case AST_FORMAT_H263_PLUS:
1580 case AST_FORMAT_H264:
1581 case AST_FORMAT_G723_1:
1582 case AST_FORMAT_LPC10:
1583 case AST_FORMAT_SPEEX:
1584 /* Don't buffer outgoing frames; send them one-per-packet: */
1585 if (_f->offset < hdrlen) {
1586 f = ast_frdup(_f);
1587 } else {
1588 f = _f;
1590 ast_rtp_raw_write(rtp, f, codec);
1593 return 0;
1596 /*! \brief Unregister interface to channel driver */
1597 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
1599 AST_LIST_LOCK(&protos);
1600 AST_LIST_REMOVE(&protos, proto, list);
1601 AST_LIST_UNLOCK(&protos);
1604 /*! \brief Register interface to channel driver */
1605 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
1607 struct ast_rtp_protocol *cur;
1609 AST_LIST_LOCK(&protos);
1610 AST_LIST_TRAVERSE(&protos, cur, list) {
1611 if (!strcmp(cur->type, proto->type)) {
1612 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1613 AST_LIST_UNLOCK(&protos);
1614 return -1;
1617 AST_LIST_INSERT_HEAD(&protos, proto, list);
1618 AST_LIST_UNLOCK(&protos);
1620 return 0;
1623 /*! \brief Bridge calls. If possible and allowed, initiate
1624 re-invite so the peers exchange media directly outside
1625 of Asterisk. */
1626 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)
1628 struct ast_frame *f;
1629 struct ast_channel *who, *other, *cs[3];
1630 struct ast_rtp *p0, *p1; /* Audio RTP Channels */
1631 struct ast_rtp *vp0, *vp1; /* Video RTP channels */
1632 struct ast_rtp_protocol *pr0, *pr1;
1633 struct sockaddr_in ac0, ac1;
1634 struct sockaddr_in vac0, vac1;
1635 struct sockaddr_in t0, t1;
1636 struct sockaddr_in vt0, vt1;
1637 char iabuf[INET_ADDRSTRLEN];
1639 void *pvt0, *pvt1;
1640 int codec0,codec1, oldcodec0, oldcodec1;
1642 memset(&vt0, 0, sizeof(vt0));
1643 memset(&vt1, 0, sizeof(vt1));
1644 memset(&vac0, 0, sizeof(vac0));
1645 memset(&vac1, 0, sizeof(vac1));
1647 /* if need DTMF, cant native bridge */
1648 if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
1649 return AST_BRIDGE_FAILED_NOWARN;
1651 /* Lock channels */
1652 ast_channel_lock(c0);
1653 while(ast_channel_trylock(c1)) {
1654 ast_channel_unlock(c0);
1655 usleep(1);
1656 ast_channel_lock(c0);
1659 /* Find channel driver interfaces */
1660 pr0 = get_proto(c0);
1661 pr1 = get_proto(c1);
1662 if (!pr0) {
1663 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
1664 ast_channel_unlock(c0);
1665 ast_channel_unlock(c1);
1666 return AST_BRIDGE_FAILED;
1668 if (!pr1) {
1669 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1670 ast_channel_unlock(c0);
1671 ast_channel_unlock(c1);
1672 return AST_BRIDGE_FAILED;
1675 /* Get channel specific interface structures */
1676 pvt0 = c0->tech_pvt;
1677 pvt1 = c1->tech_pvt;
1679 /* Get audio and video interface (if native bridge is possible) */
1680 p0 = pr0->get_rtp_info(c0);
1681 vp0 = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0) : NULL;
1682 p1 = pr1->get_rtp_info(c1);
1683 vp1 = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1) : NULL;
1685 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1686 if (!p0 || !p1) {
1687 /* Somebody doesn't want to play... */
1688 ast_channel_unlock(c0);
1689 ast_channel_unlock(c1);
1690 return AST_BRIDGE_FAILED_NOWARN;
1692 /* Get codecs from both sides */
1693 codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
1694 codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
1695 if (pr0->get_codec && pr1->get_codec) {
1696 /* Hey, we can't do reinvite if both parties speak different codecs */
1697 if (!(codec0 & codec1)) {
1698 if (option_debug)
1699 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
1700 ast_channel_unlock(c0);
1701 ast_channel_unlock(c1);
1702 return AST_BRIDGE_FAILED_NOWARN;
1706 if (option_verbose > 2)
1707 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
1709 /* Ok, we should be able to redirect the media. Start with one channel */
1710 if (pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
1711 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1712 else {
1713 /* Store RTP peer */
1714 ast_rtp_get_peer(p1, &ac1);
1715 if (vp1)
1716 ast_rtp_get_peer(vp1, &vac1);
1718 /* Then test the other channel */
1719 if (pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
1720 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1721 else {
1722 /* Store RTP peer */
1723 ast_rtp_get_peer(p0, &ac0);
1724 if (vp0)
1725 ast_rtp_get_peer(vp0, &vac0);
1727 ast_channel_unlock(c0);
1728 ast_channel_unlock(c1);
1729 /* External RTP Bridge up, now loop and see if something happes that force us to take the
1730 media back to Asterisk */
1731 cs[0] = c0;
1732 cs[1] = c1;
1733 cs[2] = NULL;
1734 oldcodec0 = codec0;
1735 oldcodec1 = codec1;
1736 for (;;) {
1737 /* Check if something changed... */
1738 if ((c0->tech_pvt != pvt0) ||
1739 (c1->tech_pvt != pvt1) ||
1740 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1741 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
1742 if (c0->tech_pvt == pvt0) {
1743 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
1744 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
1746 if (c1->tech_pvt == pvt1) {
1747 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
1748 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
1750 return AST_BRIDGE_RETRY;
1752 /* Now check if they have changed address */
1753 ast_rtp_get_peer(p1, &t1);
1754 ast_rtp_get_peer(p0, &t0);
1755 if (pr0->get_codec)
1756 codec0 = pr0->get_codec(c0);
1757 if (pr1->get_codec)
1758 codec1 = pr1->get_codec(c1);
1759 if (vp1)
1760 ast_rtp_get_peer(vp1, &vt1);
1761 if (vp0)
1762 ast_rtp_get_peer(vp0, &vt0);
1763 if (inaddrcmp(&t1, &ac1) || (vp1 && inaddrcmp(&vt1, &vac1)) || (codec1 != oldcodec1)) {
1764 if (option_debug > 1) {
1765 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
1766 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t1.sin_addr), ntohs(t1.sin_port), codec1);
1767 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
1768 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vt1.sin_addr), ntohs(vt1.sin_port), codec1);
1769 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1770 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
1771 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1772 c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
1774 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)))
1775 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
1776 memcpy(&ac1, &t1, sizeof(ac1));
1777 memcpy(&vac1, &vt1, sizeof(vac1));
1778 oldcodec1 = codec1;
1780 if (inaddrcmp(&t0, &ac0) || (vp0 && inaddrcmp(&vt0, &vac0))) {
1781 if (option_debug) {
1782 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
1783 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t0.sin_addr), ntohs(t0.sin_port), codec0);
1784 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
1785 c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
1787 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)))
1788 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
1789 memcpy(&ac0, &t0, sizeof(ac0));
1790 memcpy(&vac0, &vt0, sizeof(vac0));
1791 oldcodec0 = codec0;
1793 who = ast_waitfor_n(cs, 2, &timeoutms);
1794 if (!who) {
1795 if (!timeoutms)
1796 return AST_BRIDGE_RETRY;
1797 if (option_debug)
1798 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
1799 /* check for hangup / whentohangup */
1800 if (ast_check_hangup(c0) || ast_check_hangup(c1))
1801 break;
1802 continue;
1804 f = ast_read(who);
1805 other = (who == c0) ? c1 : c0; /* the other channel */
1806 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
1807 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
1808 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
1809 /* breaking out of the bridge. */
1810 *fo = f;
1811 *rc = who;
1812 if (option_debug)
1813 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
1814 if ((c0->tech_pvt == pvt0)) {
1815 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
1816 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
1818 if ((c1->tech_pvt == pvt1)) {
1819 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
1820 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
1822 return AST_BRIDGE_COMPLETE;
1823 } else if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1824 if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
1825 (f->subclass == AST_CONTROL_VIDUPDATE)) {
1826 ast_indicate(other, f->subclass);
1827 ast_frfree(f);
1828 } else {
1829 *fo = f;
1830 *rc = who;
1831 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
1832 return AST_BRIDGE_COMPLETE;
1834 } else {
1835 if ((f->frametype == AST_FRAME_DTMF) ||
1836 (f->frametype == AST_FRAME_VOICE) ||
1837 (f->frametype == AST_FRAME_VIDEO)) {
1838 /* Forward voice or DTMF frames if they happen upon us */
1839 ast_write(other, f);
1841 ast_frfree(f);
1843 /* Swap priority not that it's a big deal at this point */
1844 cs[2] = cs[0];
1845 cs[0] = cs[1];
1846 cs[1] = cs[2];
1849 return AST_BRIDGE_FAILED;
1852 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
1854 struct hostent *hp;
1855 struct ast_hostent ahp;
1856 char iabuf[INET_ADDRSTRLEN];
1857 int port = 0;
1858 char *p, *arg;
1860 if (argc != 4)
1861 return RESULT_SHOWUSAGE;
1862 arg = argv[3];
1863 p = strstr(arg, ":");
1864 if (p) {
1865 *p = '\0';
1866 p++;
1867 port = atoi(p);
1869 hp = ast_gethostbyname(arg, &ahp);
1870 if (hp == NULL)
1871 return RESULT_SHOWUSAGE;
1872 rtpdebugaddr.sin_family = AF_INET;
1873 memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
1874 rtpdebugaddr.sin_port = htons(port);
1875 if (port == 0)
1876 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr));
1877 else
1878 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr), port);
1879 rtpdebug = 1;
1880 return RESULT_SUCCESS;
1883 static int rtp_do_debug(int fd, int argc, char *argv[])
1885 if(argc != 2) {
1886 if(argc != 4)
1887 return RESULT_SHOWUSAGE;
1888 return rtp_do_debug_ip(fd, argc, argv);
1890 rtpdebug = 1;
1891 memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
1892 ast_cli(fd, "RTP Debugging Enabled\n");
1893 return RESULT_SUCCESS;
1896 static int rtp_no_debug(int fd, int argc, char *argv[])
1898 if(argc !=3)
1899 return RESULT_SHOWUSAGE;
1900 rtpdebug = 0;
1901 ast_cli(fd,"RTP Debugging Disabled\n");
1902 return RESULT_SUCCESS;
1905 static char debug_usage[] =
1906 "Usage: rtp debug [ip host[:port]]\n"
1907 " Enable dumping of all RTP packets to and from host.\n";
1909 static char no_debug_usage[] =
1910 "Usage: rtp no debug\n"
1911 " Disable all RTP debugging\n";
1913 static struct ast_cli_entry cli_debug_ip =
1914 {{ "rtp", "debug", "ip", NULL } , rtp_do_debug, "Enable RTP debugging on IP", debug_usage };
1916 static struct ast_cli_entry cli_debug =
1917 {{ "rtp", "debug", NULL } , rtp_do_debug, "Enable RTP debugging", debug_usage };
1919 static struct ast_cli_entry cli_no_debug =
1920 {{ "rtp", "no", "debug", NULL } , rtp_no_debug, "Disable RTP debugging", no_debug_usage };
1922 int ast_rtp_reload(void)
1924 struct ast_config *cfg;
1925 char *s;
1927 rtpstart = 5000;
1928 rtpend = 31000;
1929 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
1930 cfg = ast_config_load("rtp.conf");
1931 if (cfg) {
1932 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
1933 rtpstart = atoi(s);
1934 if (rtpstart < 1024)
1935 rtpstart = 1024;
1936 if (rtpstart > 65535)
1937 rtpstart = 65535;
1939 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
1940 rtpend = atoi(s);
1941 if (rtpend < 1024)
1942 rtpend = 1024;
1943 if (rtpend > 65535)
1944 rtpend = 65535;
1946 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
1947 #ifdef SO_NO_CHECK
1948 if (ast_false(s))
1949 nochecksums = 1;
1950 else
1951 nochecksums = 0;
1952 #else
1953 if (ast_false(s))
1954 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
1955 #endif
1957 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
1958 dtmftimeout = atoi(s);
1959 if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
1960 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
1961 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
1962 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
1965 ast_config_destroy(cfg);
1967 if (rtpstart >= rtpend) {
1968 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
1969 rtpstart = 5000;
1970 rtpend = 31000;
1972 if (option_verbose > 1)
1973 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
1974 return 0;
1977 /*! \brief Initialize the RTP system in Asterisk */
1978 void ast_rtp_init(void)
1980 ast_cli_register(&cli_debug);
1981 ast_cli_register(&cli_debug_ip);
1982 ast_cli_register(&cli_no_debug);
1983 ast_rtp_reload();