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