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