ensure that sequential DTMF sent via RTP has some 'dead air' between digits (bug...
[asterisk/asterisk.git] / rtp.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Real-time Protocol Support
5  *      Supports RTP and RTCP with Symmetric RTP support for NAT
6  *      traversal
7  * 
8  * Copyright (C) 1999 - 2005, Digium, Inc.
9  *
10  * Mark Spencer <markster@digium.com>
11  *
12  * This program is free software, distributed under the terms of
13  * the GNU General Public License
14  */
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <sys/time.h>
20 #include <signal.h>
21 #include <errno.h>
22 #include <unistd.h>
23 #include <netinet/in.h>
24 #include <sys/time.h>
25 #include <sys/socket.h>
26 #include <arpa/inet.h>
27 #include <fcntl.h>
28
29 #include <asterisk/rtp.h>
30 #include <asterisk/frame.h>
31 #include <asterisk/logger.h>
32 #include <asterisk/options.h>
33 #include <asterisk/channel.h>
34 #include <asterisk/acl.h>
35 #include <asterisk/channel.h>
36 #include <asterisk/config.h>
37 #include <asterisk/lock.h>
38 #include <asterisk/utils.h>
39 #include <asterisk/cli.h>
40 #include <asterisk/unaligned.h>
41
42 #define MAX_TIMESTAMP_SKEW      640
43
44 #define RTP_MTU         1200
45
46 #define TYPE_HIGH        0x0
47 #define TYPE_LOW         0x1
48 #define TYPE_SILENCE     0x2
49 #define TYPE_DONTSEND    0x3
50 #define TYPE_MASK        0x3
51
52 static int dtmftimeout = 3000;  /* 3000 samples */
53
54 static int rtpstart = 0;
55 static int rtpend = 0;
56 static int rtpdebug = 0;                /* Are we debugging? */
57 static struct sockaddr_in rtpdebugaddr; /* Debug packets to/from this host */
58 #ifdef SO_NO_CHECK
59 static int nochecksums = 0;
60 #endif
61
62 /* The value of each payload format mapping: */
63 struct rtpPayloadType {
64         int isAstFormat;        /* whether the following code is an AST_FORMAT */
65         int code;
66 };
67
68 #define MAX_RTP_PT 256
69
70 #define FLAG_3389_WARNING (1 << 0)
71
72 struct ast_rtp {
73         int s;
74         char resp;
75         struct ast_frame f;
76         unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
77         unsigned int ssrc;
78         unsigned int lastts;
79         unsigned int lastdigitts;
80         unsigned int lastrxts;
81         unsigned int lastividtimestamp;
82         unsigned int lastovidtimestamp;
83         unsigned int lasteventseqn;
84         int lasttxformat;
85         int lastrxformat;
86         int dtmfcount;
87         unsigned int dtmfduration;
88         int nat;
89         int flags;
90         struct sockaddr_in us;
91         struct sockaddr_in them;
92         struct timeval rxcore;
93         struct timeval txcore;
94         struct timeval dtmfmute;
95         struct ast_smoother *smoother;
96         int *ioid;
97         unsigned short seqno;
98         unsigned short rxseqno;
99         struct sched_context *sched;
100         struct io_context *io;
101         void *data;
102         ast_rtp_callback callback;
103         struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
104         int rtp_lookup_code_cache_isAstFormat;  /* a cache for the result of rtp_lookup_code(): */
105         int rtp_lookup_code_cache_code;
106         int rtp_lookup_code_cache_result;
107         int rtp_offered_from_local;
108         struct ast_rtcp *rtcp;
109 };
110
111 struct ast_rtcp {
112         int s;          /* Socket */
113         struct sockaddr_in us;
114         struct sockaddr_in them;
115 };
116
117 static struct ast_rtp_protocol *protos = NULL;
118
119 int ast_rtp_fd(struct ast_rtp *rtp)
120 {
121         return rtp->s;
122 }
123
124 int ast_rtcp_fd(struct ast_rtp *rtp)
125 {
126         if (rtp->rtcp)
127                 return rtp->rtcp->s;
128         return -1;
129 }
130
131 static int g723_len(unsigned char buf)
132 {
133         switch(buf & TYPE_MASK) {
134         case TYPE_DONTSEND:
135                 return 0;
136                 break;
137         case TYPE_SILENCE:
138                 return 4;
139                 break;
140         case TYPE_HIGH:
141                 return 24;
142                 break;
143         case TYPE_LOW:
144                 return 20;
145                 break;
146         default:
147                 ast_log(LOG_WARNING, "Badly encoded frame (%d)\n", buf & TYPE_MASK);
148         }
149         return -1;
150 }
151
152 static int g723_samples(unsigned char *buf, int maxlen)
153 {
154         int pos = 0;
155         int samples = 0;
156         int res;
157         while(pos < maxlen) {
158                 res = g723_len(buf[pos]);
159                 if (res <= 0)
160                         break;
161                 samples += 240;
162                 pos += res;
163         }
164         return samples;
165 }
166
167 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
168 {
169         rtp->data = data;
170 }
171
172 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
173 {
174         rtp->callback = callback;
175 }
176
177 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
178 {
179         rtp->nat = nat;
180 }
181
182 static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
183 {
184         struct timeval tv;
185         static struct ast_frame null_frame = { AST_FRAME_NULL, };
186         char iabuf[INET_ADDRSTRLEN];
187         gettimeofday(&tv, NULL);
188         if ((tv.tv_sec < rtp->dtmfmute.tv_sec) ||
189             ((tv.tv_sec == rtp->dtmfmute.tv_sec) && (tv.tv_usec < rtp->dtmfmute.tv_usec))) {
190                 if (option_debug)
191                         ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
192                 rtp->resp = 0;
193                 rtp->dtmfduration = 0;
194                 return &null_frame;
195         }
196         if (option_debug)
197                 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));
198         if (rtp->resp == 'X') {
199                 rtp->f.frametype = AST_FRAME_CONTROL;
200                 rtp->f.subclass = AST_CONTROL_FLASH;
201         } else {
202                 rtp->f.frametype = AST_FRAME_DTMF;
203                 rtp->f.subclass = rtp->resp;
204         }
205         rtp->f.datalen = 0;
206         rtp->f.samples = 0;
207         rtp->f.mallocd = 0;
208         rtp->f.src = "RTP";
209         rtp->resp = 0;
210         rtp->dtmfduration = 0;
211         return &rtp->f;
212         
213 }
214
215 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
216 {
217         if (rtpdebug == 0)
218                 return 0;
219         if (rtpdebugaddr.sin_addr.s_addr) {
220                 if (((ntohs(rtpdebugaddr.sin_port) != 0)
221                         && (rtpdebugaddr.sin_port != addr->sin_port))
222                         || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
223                 return 0;
224         }
225         return 1;
226 }
227
228 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
229 {
230         unsigned int event;
231         char resp = 0;
232         struct ast_frame *f = NULL;
233         event = ntohl(*((unsigned int *)(data)));
234         event &= 0x001F;
235 #if 0
236         printf("Cisco Digit: %08x (len = %d)\n", event, len);
237 #endif  
238         if (event < 10) {
239                 resp = '0' + event;
240         } else if (event < 11) {
241                 resp = '*';
242         } else if (event < 12) {
243                 resp = '#';
244         } else if (event < 16) {
245                 resp = 'A' + (event - 12);
246         } else if (event < 17) {
247                 resp = 'X';
248         }
249         if (rtp->resp && (rtp->resp != resp)) {
250                 f = send_dtmf(rtp);
251         }
252         rtp->resp = resp;
253         rtp->dtmfcount = dtmftimeout;
254         return f;
255 }
256
257 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len)
258 {
259         unsigned int event;
260         unsigned int event_end;
261         unsigned int duration;
262         char resp = 0;
263         struct ast_frame *f = NULL;
264         event = ntohl(*((unsigned int *)(data)));
265         event >>= 24;
266         event_end = ntohl(*((unsigned int *)(data)));
267         event_end <<= 8;
268         event_end >>= 24;
269         duration = ntohl(*((unsigned int *)(data)));
270         duration &= 0xFFFF;
271 #if 0
272         printf("Event: %08x (len = %d)\n", event, len);
273 #endif
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) {
283                 resp = 'X';
284         }
285         if (rtp->resp && (rtp->resp != resp)) {
286                 f = send_dtmf(rtp);
287         }
288         else if(event_end & 0x80)
289         {
290                 if (rtp->resp) {
291                         f = send_dtmf(rtp);
292                         rtp->resp = 0;
293                 }
294                 resp = 0;
295                 duration = 0;
296         }
297         else if(rtp->dtmfduration && (duration < rtp->dtmfduration))
298         {
299                 f = send_dtmf(rtp);
300         }
301         if (!(event_end & 0x80))
302                 rtp->resp = resp;
303         rtp->dtmfcount = dtmftimeout;
304         rtp->dtmfduration = duration;
305         return f;
306 }
307
308 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
309 {
310         struct ast_frame *f = NULL;
311         /* Convert comfort noise into audio with various codecs.  Unfortunately this doesn't
312            totally help us out becuase we don't have an engine to keep it going and we are not
313            guaranteed to have it every 20ms or anything */
314 #if 1
315         printf("RFC3389: %d bytes, level %d...\n", len, rtp->lastrxformat);
316 #endif  
317         if (!(rtp->flags & FLAG_3389_WARNING)) {
318                 ast_log(LOG_NOTICE, "RFC3389 support incomplete.  Turn off on client if possible\n");
319                 rtp->flags |= FLAG_3389_WARNING;
320         }
321         /* Must have at least one byte */
322         if (!len)
323                 return NULL;
324         if (len < 24) {
325                 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
326                 rtp->f.datalen = len - 1;
327                 rtp->f.offset = AST_FRIENDLY_OFFSET;
328                 memcpy(rtp->f.data, data + 1, len - 1);
329         } else {
330                 rtp->f.data = NULL;
331                 rtp->f.offset = 0;
332                 rtp->f.datalen = 0;
333         }
334         rtp->f.frametype = AST_FRAME_CNG;
335         rtp->f.subclass = data[0] & 0x7f;
336         rtp->f.datalen = len - 1;
337         rtp->f.samples = 0;
338         rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
339         f = &rtp->f;
340         return f;
341 }
342
343 static int rtpread(int *id, int fd, short events, void *cbdata)
344 {
345         struct ast_rtp *rtp = cbdata;
346         struct ast_frame *f;
347         f = ast_rtp_read(rtp);
348         if (f) {
349                 if (rtp->callback)
350                         rtp->callback(rtp, f, rtp->data);
351         }
352         return 1;
353 }
354
355 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
356 {
357         static struct ast_frame null_frame = { AST_FRAME_NULL, };
358         int len;
359         int hdrlen = 8;
360         int res;
361         struct sockaddr_in sin;
362         unsigned int rtcpdata[1024];
363         char iabuf[INET_ADDRSTRLEN];
364         
365         if (!rtp->rtcp)
366                 return &null_frame;
367
368         len = sizeof(sin);
369         
370         res = recvfrom(rtp->rtcp->s, rtcpdata, sizeof(rtcpdata),
371                                         0, (struct sockaddr *)&sin, &len);
372         
373         if (res < 0) {
374                 if (errno == EAGAIN)
375                         ast_log(LOG_NOTICE, "RTP: Received packet with bad UDP checksum\n");
376                 else
377                         ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
378                 if (errno == EBADF)
379                         CRASH;
380                 return &null_frame;
381         }
382
383         if (res < hdrlen) {
384                 ast_log(LOG_WARNING, "RTP Read too short\n");
385                 return &null_frame;
386         }
387
388         if (rtp->nat) {
389                 /* Send to whoever sent to us */
390                 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
391                     (rtp->rtcp->them.sin_port != sin.sin_port)) {
392                         memcpy(&rtp->them, &sin, sizeof(rtp->them));
393                         rtp->rxseqno = 0;
394                         if (option_debug)
395                                 ast_log(LOG_DEBUG, "RTP NAT: Using address %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
396                 }
397         }
398         if (option_debug)
399                 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
400         return &null_frame;
401 }
402
403 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
404 {
405         if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
406                 gettimeofday(&rtp->rxcore, NULL);
407                 rtp->rxcore.tv_sec -= timestamp / 8000;
408                 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
409                 /* Round to 20ms for nice, pretty timestamps */
410                 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 20000;
411                 if (rtp->rxcore.tv_usec < 0) {
412                         /* Adjust appropriately if necessary */
413                         rtp->rxcore.tv_usec += 1000000;
414                         rtp->rxcore.tv_sec -= 1;
415                 }
416         }
417         tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
418         tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
419         if (tv->tv_usec >= 1000000) {
420                 tv->tv_usec -= 1000000;
421                 tv->tv_sec += 1;
422         }
423 }
424
425 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
426 {
427         int res;
428         struct sockaddr_in sin;
429         int len;
430         unsigned int seqno;
431         int version;
432         int payloadtype;
433         int hdrlen = 12;
434         int mark;
435         int ext;
436         int x;
437         char iabuf[INET_ADDRSTRLEN];
438         unsigned int timestamp;
439         unsigned int *rtpheader;
440         static struct ast_frame *f, null_frame = { AST_FRAME_NULL, };
441         struct rtpPayloadType rtpPT;
442         
443         len = sizeof(sin);
444         
445         /* Cache where the header will go */
446         res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
447                                         0, (struct sockaddr *)&sin, &len);
448
449
450         rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
451         if (res < 0) {
452                 if (errno == EAGAIN)
453                         ast_log(LOG_NOTICE, "RTP: Received packet with bad UDP checksum\n");
454                 else
455                         ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
456                 if (errno == EBADF)
457                         CRASH;
458                 return &null_frame;
459         }
460         if (res < hdrlen) {
461                 ast_log(LOG_WARNING, "RTP Read too short\n");
462                 return &null_frame;
463         }
464
465         /* Ignore if the other side hasn't been given an address
466            yet.  */
467         if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
468                 return &null_frame;
469
470         if (rtp->nat) {
471                 /* Send to whoever sent to us */
472                 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
473                     (rtp->them.sin_port != sin.sin_port)) {
474                         memcpy(&rtp->them, &sin, sizeof(rtp->them));
475                         rtp->rxseqno = 0;
476                         ast_log(LOG_DEBUG, "RTP NAT: Using address %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port));
477                 }
478         }
479
480         /* Get fields */
481         seqno = ntohl(rtpheader[0]);
482
483         /* Check RTP version */
484         version = (seqno & 0xC0000000) >> 30;
485         if (version != 2)
486                 return &null_frame;
487         
488         payloadtype = (seqno & 0x7f0000) >> 16;
489         mark = seqno & (1 << 23);
490         ext = seqno & (1 << 28);
491         seqno &= 0xffff;
492         timestamp = ntohl(rtpheader[1]);
493         if (ext) {
494                 /* RTP Extension present */
495                 hdrlen += 4;
496                 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
497         }
498
499         if (res < hdrlen) {
500                 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
501                 return &null_frame;
502         }
503
504         if(rtp_debug_test_addr(&sin))
505                 ast_verbose("Got RTP packet from %s:%d (type %d, seq %d, ts %d, len %d)\n"
506                         , ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
507
508         rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
509         if (!rtpPT.isAstFormat) {
510                 /* This is special in-band data that's not one of our codecs */
511                 if (rtpPT.code == AST_RTP_DTMF) {
512                         /* It's special -- rfc2833 process it */
513                         if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
514                                 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
515                                 rtp->lasteventseqn = seqno;
516                         } else 
517                                 f = NULL;
518                         if (f) 
519                                 return f; 
520                         else 
521                                 return &null_frame;
522                 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
523                         /* It's really special -- process it the Cisco way */
524                         if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
525                                 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
526                                 rtp->lasteventseqn = seqno;
527                         } else 
528                                 f = NULL;
529                         if (f) 
530                                 return f; 
531                         else 
532                                 return &null_frame;
533                 } else if (rtpPT.code == AST_RTP_CN) {
534                         /* Comfort Noise */
535                         f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
536                         if (f) 
537                                 return f; 
538                         else 
539                                 return &null_frame;
540                 } else {
541                         ast_log(LOG_NOTICE, "Unknown RTP codec %d received\n", payloadtype);
542                         return &null_frame;
543                 }
544         }
545         rtp->f.subclass = rtpPT.code;
546         if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO)
547                 rtp->f.frametype = AST_FRAME_VOICE;
548         else
549                 rtp->f.frametype = AST_FRAME_VIDEO;
550         rtp->lastrxformat = rtp->f.subclass;
551
552         if (!rtp->lastrxts)
553                 rtp->lastrxts = timestamp;
554
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";
564                 }
565         }
566         rtp->rxseqno = seqno;
567
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
579         }
580         rtp->lastrxts = timestamp;
581
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);
587         }
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                 switch(rtp->f.subclass) {
594                 case AST_FORMAT_ULAW:
595                 case AST_FORMAT_ALAW:
596                         rtp->f.samples = rtp->f.datalen;
597                         break;
598                 case AST_FORMAT_SLINEAR:
599                         rtp->f.samples = rtp->f.datalen / 2;
600                         ast_frame_byteswap_be(&rtp->f);
601                         break;
602                 case AST_FORMAT_GSM:
603                         rtp->f.samples = 160 * (rtp->f.datalen / 33);
604                         break;
605                 case AST_FORMAT_ILBC:
606                         rtp->f.samples = 240 * (rtp->f.datalen / 50);
607                         break;
608                 case AST_FORMAT_ADPCM:
609                 case AST_FORMAT_G726:
610                         rtp->f.samples = rtp->f.datalen * 2;
611                         break;
612                 case AST_FORMAT_G729A:
613                         rtp->f.samples = rtp->f.datalen * 8;
614                         break;
615                 case AST_FORMAT_G723_1:
616                         rtp->f.samples = g723_samples(rtp->f.data, rtp->f.datalen);
617                         break;
618                 case AST_FORMAT_SPEEX:
619                         /* assumes that the RTP packet contained one Speex frame */
620                         rtp->f.samples = 160;
621                         break;
622                 case AST_FORMAT_LPC10:
623                         rtp->f.samples = 22 * 8;
624                         rtp->f.samples += (((char *)(rtp->f.data))[7] & 0x1) * 8;
625                         break;
626                 default:
627                         ast_log(LOG_NOTICE, "Unable to calculate samples for format %s\n", ast_getformatname(rtp->f.subclass));
628                         break;
629                 }
630                 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
631         } else {
632                 /* Video -- samples is # of samples vs. 90000 */
633                 if (!rtp->lastividtimestamp)
634                         rtp->lastividtimestamp = timestamp;
635                 rtp->f.samples = timestamp - rtp->lastividtimestamp;
636                 rtp->lastividtimestamp = timestamp;
637                 rtp->f.delivery.tv_sec = 0;
638                 rtp->f.delivery.tv_usec = 0;
639                 if (mark)
640                         rtp->f.subclass |= 0x1;
641                 
642         }
643         rtp->f.src = "RTP";
644         return &rtp->f;
645 }
646
647 /* The following array defines the MIME Media type (and subtype) for each
648    of our codecs, or RTP-specific data type. */
649 static struct {
650   struct rtpPayloadType payloadType;
651   char* type;
652   char* subtype;
653 } mimeTypes[] = {
654   {{1, AST_FORMAT_G723_1}, "audio", "G723"},
655   {{1, AST_FORMAT_GSM}, "audio", "GSM"},
656   {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
657   {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
658   {{1, AST_FORMAT_G726}, "audio", "G726-32"},
659   {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
660   {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
661   {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
662   {{1, AST_FORMAT_G729A}, "audio", "G729"},
663   {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
664   {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
665   {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
666   {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
667   {{0, AST_RTP_CN}, "audio", "CN"},
668   {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
669   {{1, AST_FORMAT_PNG}, "video", "PNG"},
670   {{1, AST_FORMAT_H261}, "video", "H261"},
671   {{1, AST_FORMAT_H263}, "video", "H263"},
672   {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
673 };
674
675 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
676    also, our own choices for dynamic payload types.  This is our master
677    table for transmission */
678 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
679   [0] = {1, AST_FORMAT_ULAW},
680 #ifdef USE_DEPRECATED_G726
681   [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
682 #endif
683   [3] = {1, AST_FORMAT_GSM},
684   [4] = {1, AST_FORMAT_G723_1},
685   [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
686   [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
687   [7] = {1, AST_FORMAT_LPC10},
688   [8] = {1, AST_FORMAT_ALAW},
689   [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
690   [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
691   [13] = {0, AST_RTP_CN},
692   [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
693   [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
694   [18] = {1, AST_FORMAT_G729A},
695   [19] = {0, AST_RTP_CN},               /* Also used for CN */
696   [26] = {1, AST_FORMAT_JPEG},
697   [31] = {1, AST_FORMAT_H261},
698   [34] = {1, AST_FORMAT_H263},
699   [103] = {1, AST_FORMAT_H263_PLUS},
700   [97] = {1, AST_FORMAT_ILBC},
701   [101] = {0, AST_RTP_DTMF},
702   [110] = {1, AST_FORMAT_SPEEX},
703   [111] = {1, AST_FORMAT_G726},
704   [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
705 };
706
707 void ast_rtp_pt_clear(struct ast_rtp* rtp) 
708 {
709         int i;
710
711         for (i = 0; i < MAX_RTP_PT; ++i) {
712                 rtp->current_RTP_PT[i].isAstFormat = 0;
713                 rtp->current_RTP_PT[i].code = 0;
714         }
715
716         rtp->rtp_lookup_code_cache_isAstFormat = 0;
717         rtp->rtp_lookup_code_cache_code = 0;
718         rtp->rtp_lookup_code_cache_result = 0;
719 }
720
721 void ast_rtp_pt_default(struct ast_rtp* rtp) 
722 {
723         int i;
724
725         /* Initialize to default payload types */
726         for (i = 0; i < MAX_RTP_PT; ++i) {
727                 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
728                 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
729         }
730
731         rtp->rtp_lookup_code_cache_isAstFormat = 0;
732         rtp->rtp_lookup_code_cache_code = 0;
733         rtp->rtp_lookup_code_cache_result = 0;
734 }
735
736 /* Make a note of a RTP payload type that was seen in a SDP "m=" line. */
737 /* By default, use the well-known value for this type (although it may */
738 /* still be set to a different value by a subsequent "a=rtpmap:" line): */
739 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt) {
740         if (pt < 0 || pt > MAX_RTP_PT) 
741                 return; /* bogus payload type */
742
743         if (static_RTP_PT[pt].code != 0) {
744                 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
745         }
746
747
748 /* Make a note of a RTP payload type (with MIME type) that was seen in */
749 /* a SDP "a=rtpmap:" line. */
750 void ast_rtp_set_rtpmap_type(struct ast_rtp* rtp, int pt,
751                          char* mimeType, char* mimeSubtype) {
752         int i;
753
754         if (pt < 0 || pt > MAX_RTP_PT) 
755                         return; /* bogus payload type */
756
757         for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
758                 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
759                      strcasecmp(mimeType, mimeTypes[i].type) == 0) {
760                         rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
761                 return;
762                 }
763         }
764
765
766 /* Return the union of all of the codecs that were set by rtp_set...() calls */
767 /* They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
768 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
769                              int* astFormats, int* nonAstFormats) {
770         int pt;
771
772         *astFormats = *nonAstFormats = 0;
773         for (pt = 0; pt < MAX_RTP_PT; ++pt) {
774                 if (rtp->current_RTP_PT[pt].isAstFormat) {
775                         *astFormats |= rtp->current_RTP_PT[pt].code;
776                 } else {
777                         *nonAstFormats |= rtp->current_RTP_PT[pt].code;
778                 }
779         }
780 }
781
782 void ast_rtp_offered_from_local(struct ast_rtp* rtp, int local) {
783         if (rtp)
784                 rtp->rtp_offered_from_local = local;
785         else
786                 ast_log(LOG_WARNING, "rtp structure is null\n");
787 }
788
789 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt) 
790 {
791         struct rtpPayloadType result;
792
793         result.isAstFormat = result.code = 0;
794         if (pt < 0 || pt > MAX_RTP_PT) 
795                 return result; /* bogus payload type */
796
797         /* Start with the negotiated codecs */
798         if (!rtp->rtp_offered_from_local)
799                 result = rtp->current_RTP_PT[pt];
800
801         /* If it doesn't exist, check our static RTP type list, just in case */
802         if (!result.code) 
803                 result = static_RTP_PT[pt];
804         return result;
805 }
806
807 /* Looks up an RTP code out of our *static* outbound list */
808 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
809
810         int pt;
811
812         if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
813                 code == rtp->rtp_lookup_code_cache_code) {
814
815                 /* Use our cached mapping, to avoid the overhead of the loop below */
816                 return rtp->rtp_lookup_code_cache_result;
817         }
818
819         /* Check the dynamic list first */
820         for (pt = 0; pt < MAX_RTP_PT; ++pt) {
821                 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
822                         rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
823                         rtp->rtp_lookup_code_cache_code = code;
824                         rtp->rtp_lookup_code_cache_result = pt;
825                         return pt;
826                 }
827         }
828
829         /* Then the static list */
830         for (pt = 0; pt < MAX_RTP_PT; ++pt) {
831                 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
832                         rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
833                         rtp->rtp_lookup_code_cache_code = code;
834                         rtp->rtp_lookup_code_cache_result = pt;
835                         return pt;
836                 }
837         }
838         return -1;
839 }
840
841 char* ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code) {
842
843         int i;
844
845         for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
846         if (mimeTypes[i].payloadType.code == code && mimeTypes[i].payloadType.isAstFormat == isAstFormat) {
847                 return mimeTypes[i].subtype;
848                 }
849         }
850         return "";
851 }
852
853 char *ast_rtp_lookup_mime_multiple(char *buf, int size, const int capability, const int isAstFormat)
854 {
855         int format;
856         unsigned len;
857         char *end = buf;
858         char *start = buf;
859
860         if (!buf || !size)
861                 return NULL;
862
863         snprintf(end, size, "0x%x (", capability);
864
865         len = strlen(end);
866         end += len;
867         size -= len;
868         start = end;
869
870         for (format = 1; format < AST_RTP_MAX; format <<= 1) {
871                 if (capability & format) {
872                         const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format);
873                         snprintf(end, size, "%s|", name);
874                         len = strlen(end);
875                         end += len;
876                         size -= len;
877                 }
878         }
879
880         if (start == end)
881                 snprintf(start, size, "nothing)"); 
882         else if (size > 1)
883                 *(end -1) = ')';
884         
885         return buf;
886 }
887
888 static int rtp_socket(void)
889 {
890         int s;
891         long flags;
892         s = socket(AF_INET, SOCK_DGRAM, 0);
893         if (s > -1) {
894                 flags = fcntl(s, F_GETFL);
895                 fcntl(s, F_SETFL, flags | O_NONBLOCK);
896 #ifdef SO_NO_CHECK
897                 if (nochecksums)
898                         setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
899 #endif
900         }
901         return s;
902 }
903
904 static struct ast_rtcp *ast_rtcp_new(void)
905 {
906         struct ast_rtcp *rtcp;
907         rtcp = malloc(sizeof(struct ast_rtcp));
908         if (!rtcp)
909                 return NULL;
910         memset(rtcp, 0, sizeof(struct ast_rtcp));
911         rtcp->s = rtp_socket();
912         rtcp->us.sin_family = AF_INET;
913         if (rtcp->s < 0) {
914                 free(rtcp);
915                 ast_log(LOG_WARNING, "Unable to allocate socket: %s\n", strerror(errno));
916                 return NULL;
917         }
918         return rtcp;
919 }
920
921 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
922 {
923         struct ast_rtp *rtp;
924         int x;
925         int first;
926         int startplace;
927         rtp = malloc(sizeof(struct ast_rtp));
928         if (!rtp)
929                 return NULL;
930         memset(rtp, 0, sizeof(struct ast_rtp));
931         rtp->them.sin_family = AF_INET;
932         rtp->us.sin_family = AF_INET;
933         rtp->s = rtp_socket();
934         rtp->ssrc = rand();
935         rtp->seqno = rand() & 0xffff;
936         if (rtp->s < 0) {
937                 free(rtp);
938                 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
939                 return NULL;
940         }
941         if (sched && rtcpenable) {
942                 rtp->sched = sched;
943                 rtp->rtcp = ast_rtcp_new();
944         }
945         /* Find us a place */
946         x = (rand() % (rtpend-rtpstart)) + rtpstart;
947         x = x & ~1;
948         startplace = x;
949         for (;;) {
950                 /* Must be an even port number by RTP spec */
951                 rtp->us.sin_port = htons(x);
952                 rtp->us.sin_addr = addr;
953                 if (rtp->rtcp)
954                         rtp->rtcp->us.sin_port = htons(x + 1);
955                 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
956                         (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
957                         break;
958                 if (!first) {
959                         /* Primary bind succeeded! Gotta recreate it */
960                         close(rtp->s);
961                         rtp->s = rtp_socket();
962                 }
963                 if (errno != EADDRINUSE) {
964                         ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
965                         close(rtp->s);
966                         if (rtp->rtcp) {
967                                 close(rtp->rtcp->s);
968                                 free(rtp->rtcp);
969                         }
970                         free(rtp);
971                         return NULL;
972                 }
973                 x += 2;
974                 if (x > rtpend)
975                         x = (rtpstart + 1) & ~1;
976                 if (x == startplace) {
977                         ast_log(LOG_ERROR, "No RTP ports remaining\n");
978                         close(rtp->s);
979                         if (rtp->rtcp) {
980                                 close(rtp->rtcp->s);
981                                 free(rtp->rtcp);
982                         }
983                         free(rtp);
984                         return NULL;
985                 }
986         }
987         if (io && sched && callbackmode) {
988                 /* Operate this one in a callback mode */
989                 rtp->sched = sched;
990                 rtp->io = io;
991                 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
992         }
993         ast_rtp_pt_default(rtp);
994         return rtp;
995 }
996
997 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
998 {
999         struct in_addr ia;
1000
1001         memset(&ia, 0, sizeof(ia));
1002         return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1003 }
1004
1005 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1006 {
1007         int res;
1008
1009         if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)))) 
1010                 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1011         return res;
1012 }
1013
1014 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1015 {
1016         rtp->them.sin_port = them->sin_port;
1017         rtp->them.sin_addr = them->sin_addr;
1018         if (rtp->rtcp) {
1019                 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1020                 rtp->rtcp->them.sin_addr = them->sin_addr;
1021         }
1022         rtp->rxseqno = 0;
1023 }
1024
1025 void ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1026 {
1027         them->sin_family = AF_INET;
1028         them->sin_port = rtp->them.sin_port;
1029         them->sin_addr = rtp->them.sin_addr;
1030 }
1031
1032 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1033 {
1034         memcpy(us, &rtp->us, sizeof(rtp->us));
1035 }
1036
1037 void ast_rtp_stop(struct ast_rtp *rtp)
1038 {
1039         memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1040         memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1041         if (rtp->rtcp) {
1042                 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1043                 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1044         }
1045 }
1046
1047 void ast_rtp_reset(struct ast_rtp *rtp)
1048 {
1049         memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1050         memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1051         memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1052         rtp->lastts = 0;
1053         rtp->lastdigitts = 0;
1054         rtp->lastrxts = 0;
1055         rtp->lastividtimestamp = 0;
1056         rtp->lastovidtimestamp = 0;
1057         rtp->lasteventseqn = 0;
1058         rtp->lasttxformat = 0;
1059         rtp->lastrxformat = 0;
1060         rtp->dtmfcount = 0;
1061         rtp->dtmfduration = 0;
1062         rtp->seqno = 0;
1063         rtp->rxseqno = 0;
1064 }
1065
1066 void ast_rtp_destroy(struct ast_rtp *rtp)
1067 {
1068         if (rtp->smoother)
1069                 ast_smoother_free(rtp->smoother);
1070         if (rtp->ioid)
1071                 ast_io_remove(rtp->io, rtp->ioid);
1072         if (rtp->s > -1)
1073                 close(rtp->s);
1074         if (rtp->rtcp) {
1075                 close(rtp->rtcp->s);
1076                 free(rtp->rtcp);
1077         }
1078         free(rtp);
1079 }
1080
1081 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1082 {
1083         struct timeval now;
1084         unsigned int ms;
1085         if (!rtp->txcore.tv_sec && !rtp->txcore.tv_usec) {
1086                 gettimeofday(&rtp->txcore, NULL);
1087                 /* Round to 20ms for nice, pretty timestamps */
1088                 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1089         }
1090         if (delivery && (delivery->tv_sec || delivery->tv_usec)) {
1091                 /* Use previous txcore */
1092                 ms = (delivery->tv_sec - rtp->txcore.tv_sec) * 1000;
1093                 ms += (1000000 + delivery->tv_usec - rtp->txcore.tv_usec) / 1000 - 1000;
1094                 rtp->txcore.tv_sec = delivery->tv_sec;
1095                 rtp->txcore.tv_usec = delivery->tv_usec;
1096         } else {
1097                 gettimeofday(&now, NULL);
1098                 ms = (now.tv_sec - rtp->txcore.tv_sec) * 1000;
1099                 ms += (1000000 + now.tv_usec - rtp->txcore.tv_usec) / 1000 - 1000;
1100                 /* Use what we just got for next time */
1101                 rtp->txcore.tv_sec = now.tv_sec;
1102                 rtp->txcore.tv_usec = now.tv_usec;
1103         }
1104         return ms;
1105 }
1106
1107 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
1108 {
1109         unsigned int *rtpheader;
1110         int hdrlen = 12;
1111         int res;
1112         int x;
1113         int payload;
1114         char data[256];
1115         char iabuf[INET_ADDRSTRLEN];
1116
1117         if ((digit <= '9') && (digit >= '0'))
1118                 digit -= '0';
1119         else if (digit == '*')
1120                 digit = 10;
1121         else if (digit == '#')
1122                 digit = 11;
1123         else if ((digit >= 'A') && (digit <= 'D')) 
1124                 digit = digit - 'A' + 12;
1125         else if ((digit >= 'a') && (digit <= 'd')) 
1126                 digit = digit - 'a' + 12;
1127         else {
1128                 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
1129                 return -1;
1130         }
1131         payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
1132
1133         /* If we have no peer, return immediately */    
1134         if (!rtp->them.sin_addr.s_addr)
1135                 return 0;
1136
1137         gettimeofday(&rtp->dtmfmute, NULL);
1138         rtp->dtmfmute.tv_usec += (500 * 1000);
1139         if (rtp->dtmfmute.tv_usec > 1000000) {
1140                 rtp->dtmfmute.tv_usec -= 1000000;
1141                 rtp->dtmfmute.tv_sec += 1;
1142         }
1143         
1144         /* Get a pointer to the header */
1145         rtpheader = (unsigned int *)data;
1146         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
1147         rtpheader[1] = htonl(rtp->lastdigitts);
1148         rtpheader[2] = htonl(rtp->ssrc); 
1149         rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
1150         for (x=0;x<6;x++) {
1151                 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1152                         res = sendto(rtp->s, (void *)rtpheader, hdrlen + 4, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1153                         if (res < 0) 
1154                                 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
1155                         if(rtp_debug_test_addr(&rtp->them))
1156                                 ast_verbose("Sent RTP packet to %s:%d (type %d, seq %d, ts %d, len %d)\n"
1157                                                 , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);                
1158                    
1159                 }
1160                 /* Clear marker bit and increment seqno */
1161                 rtpheader[0] = htonl((2 << 30)  | (payload << 16) | (rtp->seqno++));
1162                 /* For the last three packets, set the duration and the end bit */
1163                 if (x == 2) {
1164                         /* Make duration 800 (100ms) */
1165                         rtpheader[3] |= htonl((800));
1166                         /* Set the End bit for the last 3 */
1167                         rtpheader[3] |= htonl((1 << 23));
1168                 }
1169         }
1170         /* Increment the digit timestamp by 120ms, to ensure that digits
1171            sent sequentially with no intervening non-digit packets do not
1172            get sent with the same timestamp, and that sequential digits
1173            have some 'dead air' in between them
1174         */
1175         rtp->lastdigitts += 960;
1176         return 0;
1177 }
1178
1179 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
1180 {
1181         unsigned int *rtpheader;
1182         int hdrlen = 12;
1183         int res;
1184         int payload;
1185         char data[256];
1186         char iabuf[INET_ADDRSTRLEN];
1187         level = 127 - (level & 0x7f);
1188         payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
1189
1190         /* If we have no peer, return immediately */    
1191         if (!rtp->them.sin_addr.s_addr)
1192                 return 0;
1193
1194         gettimeofday(&rtp->dtmfmute, NULL);
1195         rtp->dtmfmute.tv_usec += (500 * 1000);
1196         if (rtp->dtmfmute.tv_usec > 1000000) {
1197                 rtp->dtmfmute.tv_usec -= 1000000;
1198                 rtp->dtmfmute.tv_sec += 1;
1199         }
1200         
1201         /* Get a pointer to the header */
1202         rtpheader = (unsigned int *)data;
1203         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
1204         rtpheader[1] = htonl(rtp->lastts);
1205         rtpheader[2] = htonl(rtp->ssrc); 
1206         data[12] = level;
1207         if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1208                 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1209                 if (res <0) 
1210                         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));
1211                 if(rtp_debug_test_addr(&rtp->them))
1212                         ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %d, len %d)\n"
1213                                         , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);              
1214                    
1215         }
1216         return 0;
1217 }
1218
1219 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
1220 {
1221         unsigned char *rtpheader;
1222         char iabuf[INET_ADDRSTRLEN];
1223         int hdrlen = 12;
1224         int res;
1225         int ms;
1226         int pred;
1227         int mark = 0;
1228
1229         ms = calc_txstamp(rtp, &f->delivery);
1230         /* Default prediction */
1231         if (f->subclass < AST_FORMAT_MAX_AUDIO) {
1232                 pred = rtp->lastts + ms * 8;
1233                 
1234                 switch(f->subclass) {
1235                 case AST_FORMAT_ULAW:
1236                 case AST_FORMAT_ALAW:
1237                         /* If we're within +/- 20ms from when where we
1238                            predict we should be, use that */
1239                         pred = rtp->lastts + f->datalen;
1240                         break;
1241                 case AST_FORMAT_ADPCM:
1242                 case AST_FORMAT_G726:
1243                         /* If we're within +/- 20ms from when where we
1244                            predict we should be, use that */
1245                         pred = rtp->lastts + f->datalen * 2;
1246                         break;
1247                 case AST_FORMAT_G729A:
1248                         pred = rtp->lastts + f->datalen * 8;
1249                         break;
1250                 case AST_FORMAT_GSM:
1251                         pred = rtp->lastts + (f->datalen * 160 / 33);
1252                         break;
1253                 case AST_FORMAT_ILBC:
1254                         pred = rtp->lastts + (f->datalen * 240 / 50);
1255                         break;
1256                 case AST_FORMAT_G723_1:
1257                         pred = rtp->lastts + g723_samples(f->data, f->datalen);
1258                         break;
1259                 case AST_FORMAT_SPEEX:
1260                     pred = rtp->lastts + 160;
1261                         /* assumes that the RTP packet contains one Speex frame */
1262                         break;
1263                 case AST_FORMAT_LPC10:
1264                         /* assumes that the RTP packet contains one LPC10 frame */
1265                         pred = rtp->lastts + 22 * 8;
1266                         pred += (((char *)(f->data))[7] & 0x1) * 8;
1267                         break;
1268                 default:
1269                         ast_log(LOG_WARNING, "Not sure about timestamp format for codec format %s\n", ast_getformatname(f->subclass));
1270                 }
1271                 /* Re-calculate last TS */
1272                 rtp->lastts = rtp->lastts + ms * 8;
1273                 if (!f->delivery.tv_sec && !f->delivery.tv_usec) {
1274                         /* If this isn't an absolute delivery time, Check if it is close to our prediction, 
1275                            and if so, go with our prediction */
1276                         if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
1277                                 rtp->lastts = pred;
1278                         else {
1279                                 if (option_debug > 2)
1280                                         ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
1281                                 mark = 1;
1282                         }
1283                 }
1284         } else {
1285                 mark = f->subclass & 0x1;
1286                 pred = rtp->lastovidtimestamp + f->samples;
1287                 /* Re-calculate last TS */
1288                 rtp->lastts = rtp->lastts + ms * 90;
1289                 /* If it's close to our prediction, go for it */
1290                 if (!f->delivery.tv_sec && !f->delivery.tv_usec) {
1291                         if (abs(rtp->lastts - pred) < 7200) {
1292                                 rtp->lastts = pred;
1293                                 rtp->lastovidtimestamp += f->samples;
1294                         } else {
1295                                 if (option_debug > 2)
1296                                         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);
1297                                 rtp->lastovidtimestamp = rtp->lastts;
1298                         }
1299                 }
1300         }
1301         /* If the timestamp for non-digit packets has moved beyond the timestamp
1302            for digits, update the digit timestamp.
1303         */
1304         if (rtp->lastts > rtp->lastdigitts)
1305                 rtp->lastdigitts = rtp->lastts;
1306
1307         /* Get a pointer to the header */
1308         rtpheader = (unsigned char *)(f->data - hdrlen);
1309
1310         put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
1311         put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
1312         put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc)); 
1313
1314         if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1315                 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
1316                 if (res <0) 
1317                         ast_log(LOG_NOTICE, "RTP Transmission error to %s:%d: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
1318                 if(rtp_debug_test_addr(&rtp->them))
1319                         ast_verbose("Sent RTP packet to %s:%d (type %d, seq %d, ts %d, len %d)\n"
1320                                         , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
1321         }
1322
1323         rtp->seqno++;
1324
1325         return 0;
1326 }
1327
1328 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
1329 {
1330         struct ast_frame *f;
1331         int codec;
1332         int hdrlen = 12;
1333         int subclass;
1334         
1335
1336         /* If we have no peer, return immediately */    
1337         if (!rtp->them.sin_addr.s_addr)
1338                 return 0;
1339
1340         /* If there is no data length, return immediately */
1341         if (!_f->datalen) 
1342                 return 0;
1343         
1344         /* Make sure we have enough space for RTP header */
1345         if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
1346                 ast_log(LOG_WARNING, "RTP can only send voice\n");
1347                 return -1;
1348         }
1349
1350         subclass = _f->subclass;
1351         if (_f->frametype == AST_FRAME_VIDEO)
1352                 subclass &= ~0x1;
1353
1354         codec = ast_rtp_lookup_code(rtp, 1, subclass);
1355         if (codec < 0) {
1356                 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
1357                 return -1;
1358         }
1359
1360         if (rtp->lasttxformat != subclass) {
1361                 /* New format, reset the smoother */
1362                 if (option_debug)
1363                         ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
1364                 rtp->lasttxformat = subclass;
1365                 if (rtp->smoother)
1366                         ast_smoother_free(rtp->smoother);
1367                 rtp->smoother = NULL;
1368         }
1369
1370
1371         switch(subclass) {
1372         case AST_FORMAT_SLINEAR:
1373                 if (!rtp->smoother) {
1374                         rtp->smoother = ast_smoother_new(320);
1375                 }
1376                 if (!rtp->smoother) {
1377                         ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1378                         return -1;
1379                 }
1380                 ast_smoother_feed_be(rtp->smoother, _f);
1381                 
1382                 while((f = ast_smoother_read(rtp->smoother)))
1383                         ast_rtp_raw_write(rtp, f, codec);
1384                 break;
1385         case AST_FORMAT_ULAW:
1386         case AST_FORMAT_ALAW:
1387                 if (!rtp->smoother) {
1388                         rtp->smoother = ast_smoother_new(160);
1389                 }
1390                 if (!rtp->smoother) {
1391                         ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1392                         return -1;
1393                 }
1394                 ast_smoother_feed(rtp->smoother, _f);
1395                 
1396                 while((f = ast_smoother_read(rtp->smoother)))
1397                         ast_rtp_raw_write(rtp, f, codec);
1398                 break;
1399         case AST_FORMAT_ADPCM:
1400         case AST_FORMAT_G726:
1401                 if (!rtp->smoother) {
1402                         rtp->smoother = ast_smoother_new(80);
1403                 }
1404                 if (!rtp->smoother) {
1405                         ast_log(LOG_WARNING, "Unable to create smoother :(\n");
1406                         return -1;
1407                 }
1408                 ast_smoother_feed(rtp->smoother, _f);
1409                 
1410                 while((f = ast_smoother_read(rtp->smoother)))
1411                         ast_rtp_raw_write(rtp, f, codec);
1412                 break;
1413         case AST_FORMAT_G729A:
1414                 if (!rtp->smoother) {
1415                         rtp->smoother = ast_smoother_new(20);
1416                         if (rtp->smoother)
1417                                 ast_smoother_set_flags(rtp->smoother, AST_SMOOTHER_FLAG_G729);
1418                 }
1419                 if (!rtp->smoother) {
1420                         ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
1421                         return -1;
1422                 }
1423                 ast_smoother_feed(rtp->smoother, _f);
1424                 
1425                 while((f = ast_smoother_read(rtp->smoother)))
1426                         ast_rtp_raw_write(rtp, f, codec);
1427                 break;
1428         case AST_FORMAT_GSM:
1429                 if (!rtp->smoother) {
1430                         rtp->smoother = ast_smoother_new(33);
1431                 }
1432                 if (!rtp->smoother) {
1433                         ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
1434                         return -1;
1435                 }
1436                 ast_smoother_feed(rtp->smoother, _f);
1437                 while((f = ast_smoother_read(rtp->smoother)))
1438                         ast_rtp_raw_write(rtp, f, codec);
1439                 break;
1440         case AST_FORMAT_ILBC:
1441                 if (!rtp->smoother) {
1442                         rtp->smoother = ast_smoother_new(50);
1443                 }
1444                 if (!rtp->smoother) {
1445                         ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
1446                         return -1;
1447                 }
1448                 ast_smoother_feed(rtp->smoother, _f);
1449                 while((f = ast_smoother_read(rtp->smoother)))
1450                         ast_rtp_raw_write(rtp, f, codec);
1451                 break;
1452         default:        
1453                 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
1454                 /* fall through to... */
1455         case AST_FORMAT_H261:
1456         case AST_FORMAT_H263:
1457         case AST_FORMAT_H263_PLUS:
1458         case AST_FORMAT_G723_1:
1459         case AST_FORMAT_LPC10:
1460         case AST_FORMAT_SPEEX:
1461                 /* Don't buffer outgoing frames; send them one-per-packet: */
1462                 if (_f->offset < hdrlen) {
1463                         f = ast_frdup(_f);
1464                 } else {
1465                         f = _f;
1466                 }
1467                 ast_rtp_raw_write(rtp, f, codec);
1468         }
1469                 
1470         return 0;
1471 }
1472
1473 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
1474 {
1475         struct ast_rtp_protocol *cur, *prev;
1476
1477         cur = protos;
1478         prev = NULL;
1479         while(cur) {
1480                 if (cur == proto) {
1481                         if (prev)
1482                                 prev->next = proto->next;
1483                         else
1484                                 protos = proto->next;
1485                         return;
1486                 }
1487                 prev = cur;
1488                 cur = cur->next;
1489         }
1490 }
1491
1492 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
1493 {
1494         struct ast_rtp_protocol *cur;
1495         cur = protos;
1496         while(cur) {
1497                 if (cur->type == proto->type) {
1498                         ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
1499                         return -1;
1500                 }
1501                 cur = cur->next;
1502         }
1503         proto->next = protos;
1504         protos = proto;
1505         return 0;
1506 }
1507
1508 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1509 {
1510         struct ast_rtp_protocol *cur;
1511         cur = protos;
1512         while(cur) {
1513                 if (cur->type == chan->type) {
1514                         return cur;
1515                 }
1516                 cur = cur->next;
1517         }
1518         return NULL;
1519 }
1520
1521 int ast_rtp_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1522 {
1523         struct ast_frame *f;
1524         struct ast_channel *who, *cs[3];
1525         struct ast_rtp *p0, *p1;
1526         struct ast_rtp *vp0, *vp1;
1527         struct ast_rtp_protocol *pr0, *pr1;
1528         struct sockaddr_in ac0, ac1;
1529         struct sockaddr_in vac0, vac1;
1530         struct sockaddr_in t0, t1;
1531         struct sockaddr_in vt0, vt1;
1532         char iabuf[INET_ADDRSTRLEN];
1533         
1534         void *pvt0, *pvt1;
1535         int to;
1536         int codec0,codec1, oldcodec0, oldcodec1;
1537         
1538         memset(&vt0, 0, sizeof(vt0));
1539         memset(&vt1, 0, sizeof(vt1));
1540         memset(&vac0, 0, sizeof(vac0));
1541         memset(&vac1, 0, sizeof(vac1));
1542
1543         /* if need DTMF, cant native bridge */
1544         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
1545                 return -2;
1546         ast_mutex_lock(&c0->lock);
1547         while(ast_mutex_trylock(&c1->lock)) {
1548                 ast_mutex_unlock(&c0->lock);
1549                 usleep(1);
1550                 ast_mutex_lock(&c0->lock);
1551         }
1552         pr0 = get_proto(c0);
1553         pr1 = get_proto(c1);
1554         if (!pr0) {
1555                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
1556                 ast_mutex_unlock(&c0->lock);
1557                 ast_mutex_unlock(&c1->lock);
1558                 return -1;
1559         }
1560         if (!pr1) {
1561                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
1562                 ast_mutex_unlock(&c0->lock);
1563                 ast_mutex_unlock(&c1->lock);
1564                 return -1;
1565         }
1566         pvt0 = c0->tech_pvt;
1567         pvt1 = c1->tech_pvt;
1568         p0 = pr0->get_rtp_info(c0);
1569         if (pr0->get_vrtp_info)
1570                 vp0 = pr0->get_vrtp_info(c0);
1571         else
1572                 vp0 = NULL;
1573         p1 = pr1->get_rtp_info(c1);
1574         if (pr1->get_vrtp_info)
1575                 vp1 = pr1->get_vrtp_info(c1);
1576         else
1577                 vp1 = NULL;
1578         if (!p0 || !p1) {
1579                 /* Somebody doesn't want to play... */
1580                 ast_mutex_unlock(&c0->lock);
1581                 ast_mutex_unlock(&c1->lock);
1582                 return -2;
1583         }
1584         if (pr0->get_codec)
1585                 codec0 = pr0->get_codec(c0);
1586         else
1587                 codec0 = 0;
1588         if (pr1->get_codec)
1589                 codec1 = pr1->get_codec(c1);
1590         else
1591                 codec1 = 0;
1592         if (pr0->get_codec && pr1->get_codec) {
1593                 /* Hey, we can't do reinvite if both parties speak diffrent codecs */
1594                 if (!(codec0 & codec1)) {
1595                         ast_log(LOG_WARNING, "codec0 = %d is not codec1 = %d, cannot native bridge.\n",codec0,codec1);
1596                         ast_mutex_unlock(&c0->lock);
1597                         ast_mutex_unlock(&c1->lock);
1598                         return -2;
1599                 }
1600         }
1601         if (pr0->set_rtp_peer(c0, p1, vp1, codec1)) 
1602                 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
1603         else {
1604                 /* Store RTP peer */
1605                 ast_rtp_get_peer(p1, &ac1);
1606                 if (vp1)
1607                         ast_rtp_get_peer(vp1, &vac1);
1608         }
1609         if (pr1->set_rtp_peer(c1, p0, vp0, codec0))
1610                 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
1611         else {
1612                 /* Store RTP peer */
1613                 ast_rtp_get_peer(p0, &ac0);
1614                 if (vp0)
1615                         ast_rtp_get_peer(vp0, &vac0);
1616         }
1617         ast_mutex_unlock(&c0->lock);
1618         ast_mutex_unlock(&c1->lock);
1619         cs[0] = c0;
1620         cs[1] = c1;
1621         cs[2] = NULL;
1622         oldcodec0 = codec0;
1623         oldcodec1 = codec1;
1624         for (;;) {
1625                 if ((c0->tech_pvt != pvt0)  ||
1626                         (c1->tech_pvt != pvt1) ||
1627                         (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
1628                                 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
1629                                 if (c0->tech_pvt == pvt0) {
1630                                         if (pr0->set_rtp_peer(c0, NULL, NULL, 0)) 
1631                                                 ast_log(LOG_WARNING, "Channel '%s' failed to revert\n", c0->name);
1632                                 }
1633                                 if (c1->tech_pvt == pvt1) {
1634                                         if (pr1->set_rtp_peer(c1, NULL, NULL, 0)) 
1635                                                 ast_log(LOG_WARNING, "Channel '%s' failed to revert back\n", c1->name);
1636                                 }
1637                                 /* Tell it to try again later */
1638                                 return -3;
1639                 }
1640                 to = -1;
1641                 ast_rtp_get_peer(p1, &t1);
1642                 ast_rtp_get_peer(p0, &t0);
1643                 if (pr0->get_codec)
1644                         codec0 = pr0->get_codec(c0);
1645                 if (pr1->get_codec)
1646                         codec1 = pr1->get_codec(c1);
1647                 if (vp1)
1648                         ast_rtp_get_peer(vp1, &vt1);
1649                 if (vp0)
1650                         ast_rtp_get_peer(vp0, &vt0);
1651                 if (inaddrcmp(&t1, &ac1) || (vp1 && inaddrcmp(&vt1, &vac1)) || (codec1 != oldcodec1)) {
1652                         if (option_debug) {
1653                                 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n", 
1654                                         c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t1.sin_addr), ntohs(t1.sin_port), codec1);
1655                                 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n", 
1656                                         c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vt1.sin_addr), ntohs(vt1.sin_port), codec1);
1657                                 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n", 
1658                                         c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
1659                                 ast_log(LOG_DEBUG, "Oooh, '%s' wasv %s:%d/(format %d)\n", 
1660                                         c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
1661                         }
1662                         if (pr0->set_rtp_peer(c0, t1.sin_addr.s_addr ? p1 : NULL, vt1.sin_addr.s_addr ? vp1 : NULL, codec1)) 
1663                                 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
1664                         memcpy(&ac1, &t1, sizeof(ac1));
1665                         memcpy(&vac1, &vt1, sizeof(vac1));
1666                         oldcodec1 = codec1;
1667                 }
1668                 if (inaddrcmp(&t0, &ac0) || (vp0 && inaddrcmp(&vt0, &vac0))) {
1669                         if (option_debug) {
1670                                 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n", 
1671                                         c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t0.sin_addr), ntohs(t0.sin_port), codec0);
1672                                 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n", 
1673                                         c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
1674                         }
1675                         if (pr1->set_rtp_peer(c1, t0.sin_addr.s_addr ? p0 : NULL, vt0.sin_addr.s_addr ? vp0 : NULL, codec0))
1676                                 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
1677                         memcpy(&ac0, &t0, sizeof(ac0));
1678                         memcpy(&vac0, &vt0, sizeof(vac0));
1679                         oldcodec0 = codec0;
1680                 }
1681                 who = ast_waitfor_n(cs, 2, &to);
1682                 if (!who) {
1683                         if (option_debug)
1684                                 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
1685                         /* check for hagnup / whentohangup */
1686                         if (ast_check_hangup(c0) || ast_check_hangup(c1))
1687                                 break;
1688                         continue;
1689                 }
1690                 f = ast_read(who);
1691                 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
1692                                    (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
1693                                ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
1694                         *fo = f;
1695                         *rc = who;
1696                         if (option_debug)
1697                                 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
1698                         if ((c0->tech_pvt == pvt0) && (!c0->_softhangup)) {
1699                                 if (pr0->set_rtp_peer(c0, NULL, NULL, 0)) 
1700                                         ast_log(LOG_WARNING, "Channel '%s' failed to revert\n", c0->name);
1701                         }
1702                         if ((c1->tech_pvt == pvt1) && (!c1->_softhangup)) {
1703                                 if (pr1->set_rtp_peer(c1, NULL, NULL, 0)) 
1704                                         ast_log(LOG_WARNING, "Channel '%s' failed to revert back\n", c1->name);
1705                         }
1706                         /* That's all we needed */
1707                         return 0;
1708                 } else {
1709                         if ((f->frametype == AST_FRAME_DTMF) || 
1710                                 (f->frametype == AST_FRAME_VOICE) || 
1711                                 (f->frametype == AST_FRAME_VIDEO)) {
1712                                 /* Forward voice or DTMF frames if they happen upon us */
1713                                 if (who == c0) {
1714                                         ast_write(c1, f);
1715                                 } else if (who == c1) {
1716                                         ast_write(c0, f);
1717                                 }
1718                         }
1719                         ast_frfree(f);
1720                 }
1721                 /* Swap priority not that it's a big deal at this point */
1722                 cs[2] = cs[0];
1723                 cs[0] = cs[1];
1724                 cs[1] = cs[2];
1725                 
1726         }
1727         return -1;
1728 }
1729
1730 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
1731 {
1732         struct hostent *hp;
1733         struct ast_hostent ahp;
1734         char iabuf[INET_ADDRSTRLEN];
1735         int port = 0;
1736         char *p, *arg;
1737
1738         if (argc != 4)
1739                 return RESULT_SHOWUSAGE;
1740         arg = argv[3];
1741         p = strstr(arg, ":");
1742         if (p) {
1743                 *p = '\0';
1744                 p++;
1745                 port = atoi(p);
1746         }
1747         hp = ast_gethostbyname(arg, &ahp);
1748         if (hp == NULL)
1749                 return RESULT_SHOWUSAGE;
1750         rtpdebugaddr.sin_family = AF_INET;
1751         memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
1752         rtpdebugaddr.sin_port = htons(port);
1753         if (port == 0)
1754                 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr));
1755         else
1756                 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr), port);
1757         rtpdebug = 1;
1758         return RESULT_SUCCESS;
1759 }
1760
1761 static int rtp_do_debug(int fd, int argc, char *argv[])
1762 {
1763         if(argc != 2){
1764                 if(argc != 4)
1765                         return RESULT_SHOWUSAGE;
1766                 return rtp_do_debug_ip(fd, argc, argv);
1767         }
1768         rtpdebug = 1;
1769         memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
1770         ast_cli(fd, "RTP Debugging Enabled\n");
1771         return RESULT_SUCCESS;
1772 }
1773    
1774 static int rtp_no_debug(int fd, int argc, char *argv[])
1775 {
1776         if(argc !=3)
1777                 return RESULT_SHOWUSAGE;
1778         rtpdebug = 0;
1779         ast_cli(fd,"RTP Debugging Disabled\n");
1780         return RESULT_SUCCESS;
1781 }
1782
1783 static char debug_usage[] =
1784   "Usage: rtp debug [ip host[:port]]\n"
1785   "       Enable dumping of all RTP packets to and from host.\n";
1786
1787 static char no_debug_usage[] =
1788   "Usage: rtp no debug\n"
1789   "       Disable all RTP debugging\n";
1790
1791 static struct ast_cli_entry  cli_debug_ip =
1792 {{ "rtp", "debug", "ip", NULL } , rtp_do_debug, "Enable RTP debugging on IP", debug_usage };
1793
1794 static struct ast_cli_entry  cli_debug =
1795 {{ "rtp", "debug", NULL } , rtp_do_debug, "Enable RTP debugging", debug_usage };
1796
1797 static struct ast_cli_entry  cli_no_debug =
1798 {{ "rtp", "no", "debug", NULL } , rtp_no_debug, "Disable RTP debugging", no_debug_usage };
1799
1800 void ast_rtp_reload(void)
1801 {
1802         struct ast_config *cfg;
1803         char *s;
1804
1805         rtpstart = 5000;
1806         rtpend = 31000;
1807         cfg = ast_config_load("rtp.conf");
1808         if (cfg) {
1809                 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
1810                         rtpstart = atoi(s);
1811                         if (rtpstart < 1024)
1812                                 rtpstart = 1024;
1813                         if (rtpstart > 65535)
1814                                 rtpstart = 65535;
1815                 }
1816                 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
1817                         rtpend = atoi(s);
1818                         if (rtpend < 1024)
1819                                 rtpend = 1024;
1820                         if (rtpend > 65535)
1821                                 rtpend = 65535;
1822                 }
1823                 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
1824 #ifdef SO_NO_CHECK
1825                         if (ast_false(s))
1826                                 nochecksums = 1;
1827                         else
1828                                 nochecksums = 0;
1829 #else
1830                         if (ast_false(s))
1831                                 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
1832 #endif
1833                 }
1834                 ast_config_destroy(cfg);
1835         }
1836         if (rtpstart >= rtpend) {
1837                 ast_log(LOG_WARNING, "Unreasonable values for RTP start in rtp.conf/end\n");
1838                 rtpstart = 5000;
1839                 rtpend = 31000;
1840         }
1841         if (option_verbose > 1)
1842                 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
1843         
1844 }
1845
1846 void ast_rtp_init(void)
1847 {
1848         ast_cli_register(&cli_debug);
1849         ast_cli_register(&cli_debug_ip);
1850         ast_cli_register(&cli_no_debug);
1851         ast_rtp_reload();
1852 }