resolve some pointer signedness warnings
[asterisk/asterisk.git] / rtp.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! 
20  * \file 
21  *
22  * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
23  *
24  * \author Mark Spencer <markster@digium.com>
25  * 
26  * \note RTP is defined in RFC 3550.
27  */
28
29 #include "asterisk.h"
30
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <sys/time.h>
37 #include <signal.h>
38 #include <errno.h>
39 #include <unistd.h>
40 #include <netinet/in.h>
41 #include <sys/time.h>
42 #include <sys/socket.h>
43 #include <arpa/inet.h>
44 #include <fcntl.h>
45
46 #include "asterisk/rtp.h"
47 #include "asterisk/frame.h"
48 #include "asterisk/logger.h"
49 #include "asterisk/options.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/acl.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/config.h"
54 #include "asterisk/lock.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/cli.h"
57 #include "asterisk/unaligned.h"
58 #include "asterisk/utils.h"
59
60 #define MAX_TIMESTAMP_SKEW      640
61
62 #define RTP_SEQ_MOD     (1<<16)         /*!< A sequence number can't be more than 16 bits */
63 #define RTCP_DEFAULT_INTERVALMS   5000  /*!< Default milli-seconds between RTCP reports we send */
64 #define RTCP_MIN_INTERVALMS       500   /*!< Min milli-seconds between RTCP reports we send */
65 #define RTCP_MAX_INTERVALMS       60000 /*!< Max milli-seconds between RTCP reports we send */
66
67 #define RTCP_PT_FUR     192
68 #define RTCP_PT_SR      200
69 #define RTCP_PT_RR      201
70 #define RTCP_PT_SDES    202
71 #define RTCP_PT_BYE     203
72 #define RTCP_PT_APP     204
73
74 #define RTP_MTU         1200
75
76 #define DEFAULT_DTMF_TIMEOUT 3000       /*!< samples */
77
78 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
79
80 static int rtpstart = 0;                /*!< First port for RTP sessions (set in rtp.conf) */
81 static int rtpend = 0;                  /*!< Last port for RTP sessions (set in rtp.conf) */
82 static int rtpdebug = 0;                /*!< Are we debugging? */
83 static int rtcpdebug = 0;               /*!< Are we debugging RTCP? */
84 static int rtcpstats = 0;               /*!< Are we debugging RTCP? */
85 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
86 static int stundebug = 0;               /*!< Are we debugging stun? */
87 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
88 static struct sockaddr_in rtcpdebugaddr;        /*!< Debug RTCP packets to/from this host */
89 #ifdef SO_NO_CHECK
90 static int nochecksums = 0;
91 #endif
92
93 /*!
94  * \brief Structure representing a RTP session.
95  *
96  * RTP session is defined on page 9 of RFC 3550: "An association among a set of participants communicating with RTP.  A participant may be involved in multiple RTP sessions at the same time [...]"
97  *
98  */
99 /*! \brief The value of each payload format mapping: */
100 struct rtpPayloadType {
101         int isAstFormat;        /*!< whether the following code is an AST_FORMAT */
102         int code;
103 };
104
105
106 /*! \brief RTP session description */
107 struct ast_rtp {
108         int s;
109         char resp;
110         struct ast_frame f;
111         unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
112         unsigned int ssrc;              /*!< Synchronization source, RFC 3550, page 10. */
113         unsigned int themssrc;          /*!< Their SSRC */
114         unsigned int rxssrc;
115         unsigned int lastts;
116         unsigned int lastdigitts;
117         unsigned int lastrxts;
118         unsigned int lastividtimestamp;
119         unsigned int lastovidtimestamp;
120         unsigned int lasteventseqn;
121         int lastrxseqno;                /*!< Last received sequence number */
122         unsigned short seedrxseqno;     /*!< What sequence number did they start with?*/
123         unsigned int seedrxts;          /*!< What RTP timestamp did they start with? */
124         unsigned int rxcount;           /*!< How many packets have we received? */
125         unsigned int rxoctetcount;      /*!< How many octets have we received? should be rxcount *160*/
126         unsigned int txcount;           /*!< How many packets have we sent? */
127         unsigned int txoctetcount;      /*!< How many octets have we sent? (txcount*160)*/
128         unsigned int cycles;            /*!< Shifted count of sequence number cycles */
129         double rxjitter;                /*!< Interarrival jitter at the moment */
130         double rxtransit;               /*!< Relative transit time for previous packet */
131         unsigned int lasteventendseqn;
132         int lasttxformat;
133         int lastrxformat;
134         int dtmfcount;
135         unsigned int dtmfduration;
136         int nat;
137         unsigned int flags;
138         struct sockaddr_in us;          /*!< Socket representation of the local endpoint. */
139         struct sockaddr_in them;        /*!< Socket representation of the remote endpoint. */
140         struct timeval rxcore;
141         struct timeval txcore;
142         double drxcore;                 /*!< The double representation of the first received packet */
143         struct timeval lastrx;          /*!< timeval when we last received a packet */
144         struct timeval dtmfmute;
145         struct ast_smoother *smoother;
146         int *ioid;
147         unsigned short seqno;           /*!< Sequence number, RFC 3550, page 13. */
148         unsigned short rxseqno;
149         struct sched_context *sched;
150         struct io_context *io;
151         void *data;
152         ast_rtp_callback callback;
153         struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
154         int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
155         int rtp_lookup_code_cache_code;
156         int rtp_lookup_code_cache_result;
157         struct ast_rtcp *rtcp;
158 };
159
160 /* Forward declarations */
161 static int ast_rtcp_write(void *data);
162 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
163 static int ast_rtcp_write_sr(void *data);
164 static int ast_rtcp_write_rr(void *data);
165 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
166
167 #define FLAG_3389_WARNING               (1 << 0)
168 #define FLAG_NAT_ACTIVE                 (3 << 1)
169 #define FLAG_NAT_INACTIVE               (0 << 1)
170 #define FLAG_NAT_INACTIVE_NOWARN        (1 << 1)
171 #define FLAG_HAS_DTMF                   (1 << 3)
172
173 /*!
174  * \brief Structure defining an RTCP session.
175  * 
176  * The concept "RTCP session" is not defined in RFC 3550, but since 
177  * this structure is analogous to ast_rtp, which tracks a RTP session, 
178  * it is logical to think of this as a RTCP session.
179  *
180  * RTCP packet is defined on page 9 of RFC 3550.
181  * 
182  */
183 struct ast_rtcp {
184         int s;                          /*!< Socket */
185         struct sockaddr_in us;          /*!< Socket representation of the local endpoint. */
186         struct sockaddr_in them;        /*!< Socket representation of the remote endpoint. */
187         unsigned int soc;               /*!< What they told us */
188         unsigned int spc;               /*!< What they told us */
189         unsigned int themrxlsr;         /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
190         struct timeval rxlsr;           /*!< Time when we got their last SR */
191         struct timeval txlsr;           /*!< Time when we sent or last SR*/
192         unsigned int expected_prior;    /*!< no. packets in previous interval */
193         unsigned int received_prior;    /*!< no. packets received in previous interval */
194         int schedid;                    /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
195         unsigned int rr_count;          /*!< number of RRs we've sent, not including report blocks in SR's */
196         unsigned int sr_count;          /*!< number of SRs we've sent */
197         unsigned int lastsrtxcount;     /*!< Transmit packet count when last SR sent */
198         double accumulated_transit;     /*!< accumulated a-dlsr-lsr */
199         double rtt;                     /*!< Last reported rtt */
200         unsigned int reported_jitter;   /*!< The contents of their last jitter entry in the RR */
201         unsigned int reported_lost;     /*!< Reported lost packets in their RR */
202         char quality[AST_MAX_USER_FIELD];
203         double maxrxjitter;
204         double minrxjitter;
205         double maxrtt;
206         double minrtt;
207         int sendfur;
208 };
209
210
211 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
212
213 /* XXX Maybe stun belongs in another file if it ever has use outside of RTP */
214 struct stun_header {
215         unsigned short msgtype;
216         unsigned short msglen;
217         stun_trans_id  id;
218         unsigned char ies[0];
219 } __attribute__((packed));
220
221 struct stun_attr {
222         unsigned short attr;
223         unsigned short len;
224         unsigned char value[0];
225 } __attribute__((packed));
226
227 struct stun_addr {
228         unsigned char unused;
229         unsigned char family;
230         unsigned short port;
231         unsigned int addr;
232 } __attribute__((packed));
233
234 #define STUN_IGNORE             (0)
235 #define STUN_ACCEPT             (1)
236
237 #define STUN_BINDREQ    0x0001
238 #define STUN_BINDRESP   0x0101
239 #define STUN_BINDERR    0x0111
240 #define STUN_SECREQ     0x0002
241 #define STUN_SECRESP    0x0102
242 #define STUN_SECERR     0x0112
243
244 #define STUN_MAPPED_ADDRESS     0x0001
245 #define STUN_RESPONSE_ADDRESS   0x0002
246 #define STUN_CHANGE_REQUEST     0x0003
247 #define STUN_SOURCE_ADDRESS     0x0004
248 #define STUN_CHANGED_ADDRESS    0x0005
249 #define STUN_USERNAME           0x0006
250 #define STUN_PASSWORD           0x0007
251 #define STUN_MESSAGE_INTEGRITY  0x0008
252 #define STUN_ERROR_CODE         0x0009
253 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
254 #define STUN_REFLECTED_FROM     0x000b
255
256 static const char *stun_msg2str(int msg)
257 {
258         switch(msg) {
259         case STUN_BINDREQ:
260                 return "Binding Request";
261         case STUN_BINDRESP:
262                 return "Binding Response";
263         case STUN_BINDERR:
264                 return "Binding Error Response";
265         case STUN_SECREQ:
266                 return "Shared Secret Request";
267         case STUN_SECRESP:
268                 return "Shared Secret Response";
269         case STUN_SECERR:
270                 return "Shared Secret Error Response";
271         }
272         return "Non-RFC3489 Message";
273 }
274
275 static const char *stun_attr2str(int msg)
276 {
277         switch(msg) {
278         case STUN_MAPPED_ADDRESS:
279                 return "Mapped Address";
280         case STUN_RESPONSE_ADDRESS:
281                 return "Response Address";
282         case STUN_CHANGE_REQUEST:
283                 return "Change Request";
284         case STUN_SOURCE_ADDRESS:
285                 return "Source Address";
286         case STUN_CHANGED_ADDRESS:
287                 return "Changed Address";
288         case STUN_USERNAME:
289                 return "Username";
290         case STUN_PASSWORD:
291                 return "Password";
292         case STUN_MESSAGE_INTEGRITY:
293                 return "Message Integrity";
294         case STUN_ERROR_CODE:
295                 return "Error Code";
296         case STUN_UNKNOWN_ATTRIBUTES:
297                 return "Unknown Attributes";
298         case STUN_REFLECTED_FROM:
299                 return "Reflected From";
300         }
301         return "Non-RFC3489 Attribute";
302 }
303
304 struct stun_state {
305         const char *username;
306         const char *password;
307 };
308
309 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
310 {
311         if (stundebug)
312                 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
313                         stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
314         switch(ntohs(attr->attr)) {
315         case STUN_USERNAME:
316                 state->username = (const char *) (attr->value);
317                 break;
318         case STUN_PASSWORD:
319                 state->password = (const char *) (attr->value);
320                 break;
321         default:
322                 if (stundebug)
323                         ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n", 
324                                 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
325         }
326         return 0;
327 }
328
329 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
330 {
331         int size = sizeof(**attr) + strlen(s);
332         if (*left > size) {
333                 (*attr)->attr = htons(attrval);
334                 (*attr)->len = htons(strlen(s));
335                 memcpy((*attr)->value, s, strlen(s));
336                 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
337                 *len += size;
338                 *left -= size;
339         }
340 }
341
342 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
343 {
344         int size = sizeof(**attr) + 8;
345         struct stun_addr *addr;
346         if (*left > size) {
347                 (*attr)->attr = htons(attrval);
348                 (*attr)->len = htons(8);
349                 addr = (struct stun_addr *)((*attr)->value);
350                 addr->unused = 0;
351                 addr->family = 0x01;
352                 addr->port = sin->sin_port;
353                 addr->addr = sin->sin_addr.s_addr;
354                 (*attr) = (struct stun_attr *)((*attr)->value + 8);
355                 *len += size;
356                 *left -= size;
357         }
358 }
359
360 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
361 {
362         return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
363                 (struct sockaddr *)dst, sizeof(*dst));
364 }
365
366 static void stun_req_id(struct stun_header *req)
367 {
368         int x;
369         for (x=0;x<4;x++)
370                 req->id.id[x] = ast_random();
371 }
372
373 size_t ast_rtp_alloc_size(void)
374 {
375         return sizeof(struct ast_rtp);
376 }
377
378 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
379 {
380         struct stun_header *req;
381         unsigned char reqdata[1024];
382         int reqlen, reqleft;
383         struct stun_attr *attr;
384
385         req = (struct stun_header *)reqdata;
386         stun_req_id(req);
387         reqlen = 0;
388         reqleft = sizeof(reqdata) - sizeof(struct stun_header);
389         req->msgtype = 0;
390         req->msglen = 0;
391         attr = (struct stun_attr *)req->ies;
392         if (username)
393                 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
394         req->msglen = htons(reqlen);
395         req->msgtype = htons(STUN_BINDREQ);
396         stun_send(rtp->s, suggestion, req);
397 }
398
399 static int stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len)
400 {
401         struct stun_header *resp, *hdr = (struct stun_header *)data;
402         struct stun_attr *attr;
403         struct stun_state st;
404         int ret = STUN_IGNORE;  
405         unsigned char respdata[1024];
406         int resplen, respleft;
407         
408         if (len < sizeof(struct stun_header)) {
409                 if (option_debug)
410                         ast_log(LOG_DEBUG, "Runt STUN packet (only %zd, wanting at least %zd)\n", len, sizeof(struct stun_header));
411                 return -1;
412         }
413         if (stundebug)
414                 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), ntohs(hdr->msglen));
415         if (ntohs(hdr->msglen) > len - sizeof(struct stun_header)) {
416                 if (option_debug)
417                         ast_log(LOG_DEBUG, "Scrambled STUN packet length (got %d, expecting %zd)\n", ntohs(hdr->msglen), len - sizeof(struct stun_header));
418         } else
419                 len = ntohs(hdr->msglen);
420         data += sizeof(struct stun_header);
421         memset(&st, 0, sizeof(st));
422         while(len) {
423                 if (len < sizeof(struct stun_attr)) {
424                         if (option_debug)
425                                 ast_log(LOG_DEBUG, "Runt Attribute (got %zd, expecting %zd)\n", len, sizeof(struct stun_attr));
426                         break;
427                 }
428                 attr = (struct stun_attr *)data;
429                 if (ntohs(attr->len) > len) {
430                         if (option_debug)
431                                 ast_log(LOG_DEBUG, "Inconsistent Attribute (length %d exceeds remaining msg len %zd)\n", ntohs(attr->len), len);
432                         break;
433                 }
434                 if (stun_process_attr(&st, attr)) {
435                         if (option_debug)
436                                 ast_log(LOG_DEBUG, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
437                         break;
438                 }
439                 /* Clear attribute in case previous entry was a string */
440                 attr->attr = 0;
441                 data += ntohs(attr->len) + sizeof(struct stun_attr);
442                 len -= ntohs(attr->len) + sizeof(struct stun_attr);
443         }
444         /* Null terminate any string */
445         *data = '\0';
446         resp = (struct stun_header *)respdata;
447         resplen = 0;
448         respleft = sizeof(respdata) - sizeof(struct stun_header);
449         resp->id = hdr->id;
450         resp->msgtype = 0;
451         resp->msglen = 0;
452         attr = (struct stun_attr *)resp->ies;
453         if (!len) {
454                 switch(ntohs(hdr->msgtype)) {
455                 case STUN_BINDREQ:
456                         if (stundebug)
457                                 ast_verbose("STUN Bind Request, username: %s\n", 
458                                         st.username ? st.username : "<none>");
459                         if (st.username)
460                                 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
461                         append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
462                         resp->msglen = htons(resplen);
463                         resp->msgtype = htons(STUN_BINDRESP);
464                         stun_send(s, src, resp);
465                         ret = STUN_ACCEPT;
466                         break;
467                 default:
468                         if (stundebug)
469                                 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
470                 }
471         }
472         return ret;
473 }
474
475 /*! \brief List of current sessions */
476 static AST_LIST_HEAD_STATIC(protos, ast_rtp_protocol);
477
478 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
479 {
480         unsigned int sec, usec, frac;
481         sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
482         usec = tv.tv_usec;
483         frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
484         *msw = sec;
485         *lsw = frac;
486 }
487
488 int ast_rtp_fd(struct ast_rtp *rtp)
489 {
490         return rtp->s;
491 }
492
493 int ast_rtcp_fd(struct ast_rtp *rtp)
494 {
495         if (rtp->rtcp)
496                 return rtp->rtcp->s;
497         return -1;
498 }
499
500 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
501 {
502         unsigned int interval;
503         /*! \todo XXX Do a more reasonable calculation on this one
504         * Look in RFC 3550 Section A.7 for an example*/
505         interval = rtcpinterval;
506         return interval;
507 }
508
509 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
510 {
511         rtp->data = data;
512 }
513
514 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
515 {
516         rtp->callback = callback;
517 }
518
519 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
520 {
521         rtp->nat = nat;
522 }
523
524 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
525 {
526         ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
527 }
528
529 static struct ast_frame *send_dtmf(struct ast_rtp *rtp)
530 {
531         char iabuf[INET_ADDRSTRLEN];
532
533         if (ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
534                 if (option_debug)
535                         ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
536                 rtp->resp = 0;
537                 rtp->dtmfduration = 0;
538                 return &ast_null_frame;
539         }
540         if (option_debug)
541                 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));
542         if (rtp->resp == 'X') {
543                 rtp->f.frametype = AST_FRAME_CONTROL;
544                 rtp->f.subclass = AST_CONTROL_FLASH;
545         } else {
546                 rtp->f.frametype = AST_FRAME_DTMF;
547                 rtp->f.subclass = rtp->resp;
548         }
549         rtp->f.datalen = 0;
550         rtp->f.samples = 0;
551         rtp->f.mallocd = 0;
552         rtp->f.src = "RTP";
553         rtp->resp = 0;
554         rtp->dtmfduration = 0;
555         return &rtp->f;
556         
557 }
558
559 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
560 {
561         if (rtpdebug == 0)
562                 return 0;
563         if (rtpdebugaddr.sin_addr.s_addr) {
564                 if (((ntohs(rtpdebugaddr.sin_port) != 0)
565                         && (rtpdebugaddr.sin_port != addr->sin_port))
566                         || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
567                 return 0;
568         }
569         return 1;
570 }
571
572 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
573 {
574         if (rtcpdebug == 0)
575                 return 0;
576         if (rtcpdebugaddr.sin_addr.s_addr) {
577                 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
578                         && (rtcpdebugaddr.sin_port != addr->sin_port))
579                         || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
580                 return 0;
581         }
582         return 1;
583 }
584
585
586 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
587 {
588         unsigned int event;
589         char resp = 0;
590         struct ast_frame *f = NULL;
591         event = ntohl(*((unsigned int *)(data)));
592         event &= 0x001F;
593         if (option_debug > 2 || rtpdebug)
594                 ast_log(LOG_DEBUG, "Cisco DTMF Digit: %08x (len = %d)\n", event, len);
595         if (event < 10) {
596                 resp = '0' + event;
597         } else if (event < 11) {
598                 resp = '*';
599         } else if (event < 12) {
600                 resp = '#';
601         } else if (event < 16) {
602                 resp = 'A' + (event - 12);
603         } else if (event < 17) {
604                 resp = 'X';
605         }
606         if (rtp->resp && (rtp->resp != resp)) {
607                 f = send_dtmf(rtp);
608         }
609         rtp->resp = resp;
610         rtp->dtmfcount = dtmftimeout;
611         return f;
612 }
613
614 /*! 
615  * \brief Process RTP DTMF and events according to RFC 2833.
616  * 
617  * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
618  * 
619  * \param rtp
620  * \param data
621  * \param len
622  * \param seqno
623  * \returns
624  */
625 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
626 {
627         unsigned int event;
628         unsigned int event_end;
629         unsigned int duration;
630         char resp = 0;
631         struct ast_frame *f = NULL;
632
633         event = ntohl(*((unsigned int *)(data)));
634         event >>= 24;
635         event_end = ntohl(*((unsigned int *)(data)));
636         event_end <<= 8;
637         event_end >>= 24;
638         duration = ntohl(*((unsigned int *)(data)));
639         duration &= 0xFFFF;
640         if (rtpdebug || option_debug > 2)
641                 ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
642         if (event < 10) {
643                 resp = '0' + event;
644         } else if (event < 11) {
645                 resp = '*';
646         } else if (event < 12) {
647                 resp = '#';
648         } else if (event < 16) {
649                 resp = 'A' + (event - 12);
650         } else if (event < 17) {        /* Event 16: Hook flash */
651                 resp = 'X';     
652         }
653         if (rtp->resp && (rtp->resp != resp)) {
654                 f = send_dtmf(rtp);
655         } else if (event_end & 0x80) {
656                 if (rtp->resp) {
657                         if (rtp->lasteventendseqn != seqno) {
658                                 f = send_dtmf(rtp);
659                                 rtp->lasteventendseqn = seqno;
660                         }
661                         rtp->resp = 0;
662                 }
663                 resp = 0;
664                 duration = 0;
665         } else if (rtp->resp && rtp->dtmfduration && (duration < rtp->dtmfduration)) {
666                 f = send_dtmf(rtp);
667         }
668         if (!(event_end & 0x80))
669                 rtp->resp = resp;
670         rtp->dtmfcount = dtmftimeout;
671         rtp->dtmfduration = duration;
672         return f;
673 }
674
675 /*!
676  * \brief Process Comfort Noise RTP.
677  * 
678  * This is incomplete at the moment.
679  * 
680 */
681 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
682 {
683         struct ast_frame *f = NULL;
684         /* Convert comfort noise into audio with various codecs.  Unfortunately this doesn't
685            totally help us out becuase we don't have an engine to keep it going and we are not
686            guaranteed to have it every 20ms or anything */
687         if (rtpdebug)
688                 ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
689
690         if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
691                 char iabuf[INET_ADDRSTRLEN];
692
693                 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
694                         ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
695                 ast_set_flag(rtp, FLAG_3389_WARNING);
696         }
697
698         /* Must have at least one byte */
699         if (!len)
700                 return NULL;
701         if (len < 24) {
702                 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
703                 rtp->f.datalen = len - 1;
704                 rtp->f.offset = AST_FRIENDLY_OFFSET;
705                 memcpy(rtp->f.data, data + 1, len - 1);
706         } else {
707                 rtp->f.data = NULL;
708                 rtp->f.offset = 0;
709                 rtp->f.datalen = 0;
710         }
711         rtp->f.frametype = AST_FRAME_CNG;
712         rtp->f.subclass = data[0] & 0x7f;
713         rtp->f.datalen = len - 1;
714         rtp->f.samples = 0;
715         rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
716         f = &rtp->f;
717         return f;
718 }
719
720 static int rtpread(int *id, int fd, short events, void *cbdata)
721 {
722         struct ast_rtp *rtp = cbdata;
723         struct ast_frame *f;
724         f = ast_rtp_read(rtp);
725         if (f) {
726                 if (rtp->callback)
727                         rtp->callback(rtp, f, rtp->data);
728         }
729         return 1;
730 }
731
732 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
733 {
734         socklen_t len;
735         int position, i, packetwords;
736         int res;
737         struct sockaddr_in sin;
738         unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
739         char iabuf[INET_ADDRSTRLEN];
740         unsigned int *rtcpheader;
741         int pt;
742         struct timeval now;
743         unsigned int length;
744         int rc;
745         double rtt = 0;
746         double a;
747         double dlsr;
748         double lsr;
749         unsigned int msw;
750         unsigned int lsw;
751         unsigned int comp;
752         struct ast_frame *f = &ast_null_frame;
753         
754         if (!rtp || !rtp->rtcp)
755                 return &ast_null_frame;
756
757         len = sizeof(sin);
758         
759         res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
760                                         0, (struct sockaddr *)&sin, &len);
761         rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
762         
763         if (res < 0) {
764                 if (errno != EAGAIN)
765                         ast_log(LOG_WARNING, "RTCP Read error: %s\n", strerror(errno));
766                 if (errno == EBADF)
767                         CRASH;
768                 return &ast_null_frame;
769         }
770
771         packetwords = res / 4;
772         
773         if (rtp->nat) {
774                 /* Send to whoever sent to us */
775                 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
776                     (rtp->rtcp->them.sin_port != sin.sin_port)) {
777                         memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
778                         if (option_debug || rtpdebug)
779                                 ast_log(LOG_DEBUG, "RTCP NAT: Got RTCP from other end. Now sending to address %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
780                 }
781         }
782         if (option_debug)
783                 ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
784
785         /* Process a compound packet */
786         position = 0;
787         while (position < packetwords) {
788                 i = position;
789                 length = ntohl(rtcpheader[i]);
790                 pt = (length & 0xff0000) >> 16;
791                 rc = (length & 0x1f000000) >> 24;
792                 length &= 0xffff;
793     
794                 if ((i + length) > packetwords) {
795                         ast_log(LOG_WARNING, "RTCP Read too short\n");
796                         return &ast_null_frame;
797                 }
798                 
799                 if (rtcp_debug_test_addr(&sin)) {
800                         ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port));
801                         ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
802                         ast_verbose("Reception reports: %d\n", rc);
803                         ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
804                 }
805     
806                 i += 2; /* Advance past header and ssrc */
807                 
808                 switch (pt) {
809                 case RTCP_PT_SR:
810                         gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
811                         rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
812                         rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
813                         rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff) >> 16); /* Going to LSR in RR*/
814     
815                         if (rtcp_debug_test_addr(&sin)) {
816                                 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
817                                 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
818                                 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
819                         }
820                         i += 5;
821                         if (rc < 1)
822                                 break;
823                         /* Intentional fall through */
824                 case RTCP_PT_RR:
825                         /* This is the place to calculate RTT */
826                         /* Don't handle multiple reception reports (rc > 1) yet */
827                         gettimeofday(&now, NULL);
828                         timeval2ntp(now, &msw, &lsw);
829                         /* Use the one we sent them in our SR instead, rtcp->txlsr could have been rewritten if the dlsr is large */
830                         if (ntohl(rtcpheader[i + 4])) { /* We must have the LSR */
831                                 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
832                                 a = (double)((comp & 0xffff0000) >> 16) + (double)((double)(comp & 0xffff)/1000000.);
833                                 lsr = (double)((ntohl(rtcpheader[i + 4]) & 0xffff0000) >> 16) + (double)((double)(ntohl(rtcpheader[i + 4]) & 0xffff) / 1000000.);
834                                 dlsr = (double)(ntohl(rtcpheader[i + 5])/65536.);
835                                 rtt = a - dlsr - lsr;
836                                 rtp->rtcp->accumulated_transit += rtt;
837                                 rtp->rtcp->rtt = rtt;
838                                 if (rtp->rtcp->maxrtt<rtt)
839                                         rtp->rtcp->maxrtt = rtt;
840                                 if (rtp->rtcp->minrtt>rtt)
841                                 rtp->rtcp->minrtt = rtt;
842                         }
843                         rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
844                         rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
845                         if (rtcp_debug_test_addr(&sin)) {
846                                 ast_verbose("Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
847                                 ast_verbose("Packets lost so far: %d\n", rtp->rtcp->reported_lost);
848                                 ast_verbose("Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
849                                 ast_verbose("Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
850                                 ast_verbose("Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
851                                 ast_verbose("Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
852                                 ast_verbose("DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
853                                 if (rtt)
854                                         ast_verbose("RTT: %f(sec)\n", rtt);
855                         }
856                         break;
857                 case RTCP_PT_FUR:
858                         if (rtcp_debug_test_addr(&sin))
859                                 ast_verbose("Received an RTCP Fast Update Request\n");
860                         rtp->f.frametype = AST_FRAME_CONTROL;
861                         rtp->f.subclass = AST_CONTROL_VIDUPDATE;
862                         rtp->f.datalen = 0;
863                         rtp->f.samples = 0;
864                         rtp->f.mallocd = 0;
865                         rtp->f.src = "RTP";
866                         f = &rtp->f;
867                         break;
868                 case RTCP_PT_SDES:
869                         if (rtcp_debug_test_addr(&sin))
870                                 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
871                         break;
872                 case RTCP_PT_BYE:
873                         if (rtcp_debug_test_addr(&sin))
874                                 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
875                         break;
876                 default:
877                         ast_log(LOG_NOTICE, "Unknown RTCP packet (pt=%d) received from %s:%d\n", pt, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
878                         break;
879                 }
880                 position += (length + 1);
881         }
882                         
883         return f;
884 }
885
886 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
887 {
888         struct timeval now;
889         double transit;
890         double current_time;
891         double d;
892         double dtv;
893         double prog;
894         
895         if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
896                 gettimeofday(&rtp->rxcore, NULL);
897                 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
898                 /* map timestamp to a real time */
899                 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
900                 rtp->rxcore.tv_sec -= timestamp / 8000;
901                 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
902                 /* Round to 0.1ms for nice, pretty timestamps */
903                 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
904                 if (rtp->rxcore.tv_usec < 0) {
905                         /* Adjust appropriately if necessary */
906                         rtp->rxcore.tv_usec += 1000000;
907                         rtp->rxcore.tv_sec -= 1;
908                 }
909         }
910
911         gettimeofday(&now,NULL);
912         /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
913         tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
914         tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
915         if (tv->tv_usec >= 1000000) {
916                 tv->tv_usec -= 1000000;
917                 tv->tv_sec += 1;
918         }
919         prog = (double)((timestamp-rtp->seedrxts)/8000.);
920         dtv = (double)rtp->drxcore + (double)(prog);
921         current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
922         transit = current_time - dtv;
923         d = transit - rtp->rxtransit;
924         rtp->rxtransit = transit;
925         if (d<0)
926                 d=-d;
927         rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
928         if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
929                 rtp->rtcp->maxrxjitter = rtp->rxjitter;
930         if (rtp->rxjitter < rtp->rtcp->minrxjitter)
931                 rtp->rtcp->minrxjitter = rtp->rxjitter;
932 }
933
934 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
935 {
936         int res;
937         struct sockaddr_in sin;
938         socklen_t len;
939         unsigned int seqno;
940         int version;
941         int payloadtype;
942         int tseqno;
943         int hdrlen = 12;
944         int padding;
945         int mark;
946         int ext;
947         char iabuf[INET_ADDRSTRLEN];
948         unsigned int ssrc;
949         unsigned int timestamp;
950         unsigned int *rtpheader;
951         struct rtpPayloadType rtpPT;
952         
953         len = sizeof(sin);
954         
955         /* Cache where the header will go */
956         res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
957                                         0, (struct sockaddr *)&sin, &len);
958
959         rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
960         if (res < 0) {
961                 if (errno != EAGAIN)
962                         ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
963                 if (errno == EBADF)
964                         CRASH;
965                 return &ast_null_frame;
966         }
967         
968         if (res < hdrlen) {
969                 ast_log(LOG_WARNING, "RTP Read too short\n");
970                 return &ast_null_frame;
971         }
972
973         /* Get fields */
974         seqno = ntohl(rtpheader[0]);
975
976         /* Check RTP version */
977         version = (seqno & 0xC0000000) >> 30;
978         if (!version) {
979                 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res) == STUN_ACCEPT) &&
980                         (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
981                         memcpy(&rtp->them, &sin, sizeof(rtp->them));
982                 }
983                 return &ast_null_frame;
984         }
985
986         if (version != 2)
987                 return &ast_null_frame;
988         /* Ignore if the other side hasn't been given an address
989            yet.  */
990         if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
991                 return &ast_null_frame;
992
993         if (rtp->nat) {
994                 /* Send to whoever sent to us */
995                 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
996                     (rtp->them.sin_port != sin.sin_port)) {
997                         rtp->them = sin;
998                         if (rtp->rtcp) {
999                                 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1000                                 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1001                         }
1002                         rtp->rxseqno = 0;
1003                         ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1004                         if (option_debug || rtpdebug)
1005                                 ast_log(LOG_DEBUG, "RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port));
1006                 }
1007         }
1008
1009         payloadtype = (seqno & 0x7f0000) >> 16;
1010         padding = seqno & (1 << 29);
1011         mark = seqno & (1 << 23);
1012         ext = seqno & (1 << 28);
1013         seqno &= 0xffff;
1014         timestamp = ntohl(rtpheader[1]);
1015         ssrc = ntohl(rtpheader[2]);
1016         
1017         if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1018                 if (option_verbose > 1)
1019                         ast_verbose(VERBOSE_PREFIX_2 "Forcing Marker bit, because SSRC has changed\n");
1020                 mark = 1;
1021         }
1022
1023         rtp->rxssrc = ssrc;
1024         
1025         if (padding) {
1026                 /* Remove padding bytes */
1027                 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1028         }
1029         
1030         if (ext) {
1031                 /* RTP Extension present */
1032                 hdrlen += 4;
1033                 hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
1034         }
1035
1036         if (res < hdrlen) {
1037                 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1038                 return &ast_null_frame;
1039         }
1040
1041         rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1042
1043         tseqno = rtp->lastrxseqno +1;
1044
1045         if (rtp->rxcount==1) {
1046                 /* This is the first RTP packet successfully received from source */
1047                 rtp->seedrxseqno = seqno;
1048         }
1049
1050         if (rtp->rtcp->schedid < 1) {
1051                 /* Schedule transmission of Receiver Report */
1052                 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1053         }
1054
1055         if (tseqno > RTP_SEQ_MOD) { /* if tseqno is greater than RTP_SEQ_MOD it would indicate that the sender cycled */
1056                 rtp->cycles += RTP_SEQ_MOD;
1057                 ast_verbose("SEQNO cycled: %u\t%d\n", rtp->cycles, seqno);
1058         }
1059
1060         rtp->lastrxseqno = seqno;
1061         
1062         if (rtp->themssrc==0)
1063                 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1064         
1065         if (rtp_debug_test_addr(&sin))
1066                 ast_verbose("Got  RTP packet from    %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1067                         ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1068
1069         rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1070         if (!rtpPT.isAstFormat) {
1071                 struct ast_frame *f = NULL;
1072
1073                 /* This is special in-band data that's not one of our codecs */
1074                 if (rtpPT.code == AST_RTP_DTMF) {
1075                         /* It's special -- rfc2833 process it */
1076                         if (rtp_debug_test_addr(&sin)) {
1077                                 unsigned char *data;
1078                                 unsigned int event;
1079                                 unsigned int event_end;
1080                                 unsigned int duration;
1081                                 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1082                                 event = ntohl(*((unsigned int *)(data)));
1083                                 event >>= 24;
1084                                 event_end = ntohl(*((unsigned int *)(data)));
1085                                 event_end <<= 8;
1086                                 event_end >>= 24;
1087                                 duration = ntohl(*((unsigned int *)(data)));
1088                                 duration &= 0xFFFF;
1089                                 ast_verbose("Got  RTP RFC2833 from   %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n", ast_inet_ntoa(iabuf, sizeof(iabuf), sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
1090                         }
1091                         if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
1092                                 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
1093                                 rtp->lasteventseqn = seqno;
1094                         }
1095                 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1096                         /* It's really special -- process it the Cisco way */
1097                         if (rtp->lasteventseqn <= seqno || rtp->resp == 0 || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
1098                                 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1099                                 rtp->lasteventseqn = seqno;
1100                         }
1101                 } else if (rtpPT.code == AST_RTP_CN) {
1102                         /* Comfort Noise */
1103                         f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1104                 } else {
1105                         ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr));
1106                 }
1107                 return f ? f : &ast_null_frame;
1108         }
1109         rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1110         rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : AST_FRAME_VIDEO;
1111
1112         if (!rtp->lastrxts)
1113                 rtp->lastrxts = timestamp;
1114
1115         rtp->rxseqno = seqno;
1116
1117         if (rtp->dtmfcount) {
1118 #if 0
1119                 printf("dtmfcount was %d\n", rtp->dtmfcount);
1120 #endif          
1121                 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
1122                 if (rtp->dtmfcount < 0)
1123                         rtp->dtmfcount = 0;
1124 #if 0
1125                 if (dtmftimeout != rtp->dtmfcount)
1126                         printf("dtmfcount is %d\n", rtp->dtmfcount);
1127 #endif
1128         }
1129         rtp->lastrxts = timestamp;
1130
1131         /* Send any pending DTMF */
1132         if (rtp->resp && !rtp->dtmfcount) {
1133                 if (option_debug)
1134                         ast_log(LOG_DEBUG, "Sending pending DTMF\n");
1135                 return send_dtmf(rtp);
1136         }
1137         rtp->f.mallocd = 0;
1138         rtp->f.datalen = res - hdrlen;
1139         rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1140         rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1141         if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
1142                 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1143                 if (rtp->f.subclass == AST_FORMAT_SLINEAR) 
1144                         ast_frame_byteswap_be(&rtp->f);
1145                 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1146                 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1147                 rtp->f.has_timing_info = 1;
1148                 rtp->f.ts = timestamp / 8;
1149                 rtp->f.len = rtp->f.samples / 8;
1150                 rtp->f.seqno = seqno;
1151         } else {
1152                 /* Video -- samples is # of samples vs. 90000 */
1153                 if (!rtp->lastividtimestamp)
1154                         rtp->lastividtimestamp = timestamp;
1155                 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1156                 rtp->lastividtimestamp = timestamp;
1157                 rtp->f.delivery.tv_sec = 0;
1158                 rtp->f.delivery.tv_usec = 0;
1159                 if (mark)
1160                         rtp->f.subclass |= 0x1;
1161                 
1162         }
1163         rtp->f.src = "RTP";
1164         return &rtp->f;
1165 }
1166
1167 /* The following array defines the MIME Media type (and subtype) for each
1168    of our codecs, or RTP-specific data type. */
1169 static struct {
1170         struct rtpPayloadType payloadType;
1171         char* type;
1172         char* subtype;
1173 } mimeTypes[] = {
1174         {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1175         {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1176         {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1177         {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1178         {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1179         {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1180         {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1181         {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1182         {{1, AST_FORMAT_G729A}, "audio", "G729"},
1183         {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1184         {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1185         {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1186         {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1187         {{0, AST_RTP_CN}, "audio", "CN"},
1188         {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1189         {{1, AST_FORMAT_PNG}, "video", "PNG"},
1190         {{1, AST_FORMAT_H261}, "video", "H261"},
1191         {{1, AST_FORMAT_H263}, "video", "H263"},
1192         {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1193         {{1, AST_FORMAT_H264}, "video", "H264"},
1194 };
1195
1196 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1197    also, our own choices for dynamic payload types.  This is our master
1198    table for transmission */
1199 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1200         [0] = {1, AST_FORMAT_ULAW},
1201 #ifdef USE_DEPRECATED_G726
1202         [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1203 #endif
1204         [3] = {1, AST_FORMAT_GSM},
1205         [4] = {1, AST_FORMAT_G723_1},
1206         [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1207         [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1208         [7] = {1, AST_FORMAT_LPC10},
1209         [8] = {1, AST_FORMAT_ALAW},
1210         [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1211         [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1212         [13] = {0, AST_RTP_CN},
1213         [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1214         [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1215         [18] = {1, AST_FORMAT_G729A},
1216         [19] = {0, AST_RTP_CN},         /* Also used for CN */
1217         [26] = {1, AST_FORMAT_JPEG},
1218         [31] = {1, AST_FORMAT_H261},
1219         [34] = {1, AST_FORMAT_H263},
1220         [103] = {1, AST_FORMAT_H263_PLUS},
1221         [97] = {1, AST_FORMAT_ILBC},
1222         [99] = {1, AST_FORMAT_H264},
1223         [101] = {0, AST_RTP_DTMF},
1224         [110] = {1, AST_FORMAT_SPEEX},
1225         [111] = {1, AST_FORMAT_G726},
1226         [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1227 };
1228
1229 void ast_rtp_pt_clear(struct ast_rtp* rtp) 
1230 {
1231         int i;
1232         if (!rtp)
1233                 return;
1234
1235         for (i = 0; i < MAX_RTP_PT; ++i) {
1236                 rtp->current_RTP_PT[i].isAstFormat = 0;
1237                 rtp->current_RTP_PT[i].code = 0;
1238         }
1239
1240         rtp->rtp_lookup_code_cache_isAstFormat = 0;
1241         rtp->rtp_lookup_code_cache_code = 0;
1242         rtp->rtp_lookup_code_cache_result = 0;
1243 }
1244
1245 void ast_rtp_pt_default(struct ast_rtp* rtp) 
1246 {
1247         int i;
1248
1249         /* Initialize to default payload types */
1250         for (i = 0; i < MAX_RTP_PT; ++i) {
1251                 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1252                 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1253         }
1254
1255         rtp->rtp_lookup_code_cache_isAstFormat = 0;
1256         rtp->rtp_lookup_code_cache_code = 0;
1257         rtp->rtp_lookup_code_cache_result = 0;
1258 }
1259
1260 void ast_rtp_pt_copy(struct ast_rtp *dest, const struct ast_rtp *src)
1261 {
1262         unsigned int i;
1263
1264         for (i=0; i < MAX_RTP_PT; ++i) {
1265                 dest->current_RTP_PT[i].isAstFormat = 
1266                         src->current_RTP_PT[i].isAstFormat;
1267                 dest->current_RTP_PT[i].code = 
1268                         src->current_RTP_PT[i].code; 
1269         }
1270         dest->rtp_lookup_code_cache_isAstFormat = 0;
1271         dest->rtp_lookup_code_cache_code = 0;
1272         dest->rtp_lookup_code_cache_result = 0;
1273 }
1274
1275 /*! \brief Get channel driver interface structure */
1276 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1277 {
1278         struct ast_rtp_protocol *cur = NULL;
1279
1280         AST_LIST_LOCK(&protos);
1281         AST_LIST_TRAVERSE(&protos, cur, list) {
1282                 if (cur->type == chan->tech->type)
1283                         break;
1284         }
1285         AST_LIST_UNLOCK(&protos);
1286
1287         return cur;
1288 }
1289
1290 int ast_rtp_early_bridge(struct ast_channel *dest, struct ast_channel *src)
1291 {
1292         struct ast_rtp *destp, *srcp=NULL;              /* Audio RTP Channels */
1293         struct ast_rtp *vdestp, *vsrcp=NULL;            /* Video RTP channels */
1294         struct ast_rtp_protocol *destpr, *srcpr=NULL;
1295         int srccodec;
1296
1297         /* Lock channels */
1298         ast_channel_lock(dest);
1299         if (src) {
1300                 while(ast_channel_trylock(src)) {
1301                         ast_channel_unlock(dest);
1302                         usleep(1);
1303                         ast_channel_lock(dest);
1304                 }
1305         }
1306
1307         /* Find channel driver interfaces */
1308         destpr = get_proto(dest);
1309         if (src)
1310                 srcpr = get_proto(src);
1311         if (!destpr) {
1312                 if (option_debug)
1313                         ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1314                 ast_channel_unlock(dest);
1315                 if (src)
1316                         ast_channel_unlock(src);
1317                 return 0;
1318         }
1319         if (!srcpr) {
1320                 if (option_debug)
1321                         ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src ? src->name : "<unspecified>");
1322                 ast_channel_unlock(dest);
1323                 if (src)
1324                         ast_channel_unlock(src);
1325                 return 0;
1326         }
1327
1328         /* Get audio and video interface (if native bridge is possible) */
1329         destp = destpr->get_rtp_info(dest);
1330         vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
1331         if (srcpr) {
1332                 srcp = srcpr->get_rtp_info(src);
1333                 vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
1334         }
1335
1336         /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1337         if (!destp) {
1338                 /* Somebody doesn't want to play... */
1339                 ast_channel_unlock(dest);
1340                 if (src)
1341                         ast_channel_unlock(src);
1342                 return 0;
1343         }
1344         if (srcpr && srcpr->get_codec)
1345                 srccodec = srcpr->get_codec(src);
1346         else
1347                 srccodec = 0;
1348         /* Consider empty media as non-existant */
1349         if (srcp && !srcp->them.sin_addr.s_addr)
1350                 srcp = NULL;
1351         /* Bridge media early */
1352         if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, srcp ? ast_test_flag(srcp, FLAG_NAT_ACTIVE) : 0))
1353                 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src ? src->name : "<unspecified>");
1354         ast_channel_unlock(dest);
1355         if (src)
1356                 ast_channel_unlock(src);
1357         if (option_debug)
1358                 ast_log(LOG_DEBUG, "Setting early bridge SDP of '%s' with that of '%s'\n", dest->name, src ? src->name : "<unspecified>");
1359         return 1;
1360 }
1361
1362 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1363 {
1364         struct ast_rtp *destp, *srcp;           /* Audio RTP Channels */
1365         struct ast_rtp *vdestp, *vsrcp;         /* Video RTP channels */
1366         struct ast_rtp_protocol *destpr, *srcpr;
1367         int srccodec;
1368         /* Lock channels */
1369         ast_channel_lock(dest);
1370         while(ast_channel_trylock(src)) {
1371                 ast_channel_unlock(dest);
1372                 usleep(1);
1373                 ast_channel_lock(dest);
1374         }
1375
1376         /* Find channel driver interfaces */
1377         destpr = get_proto(dest);
1378         srcpr = get_proto(src);
1379         if (!destpr) {
1380                 if (option_debug)
1381                         ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1382                 ast_channel_unlock(dest);
1383                 ast_channel_unlock(src);
1384                 return 0;
1385         }
1386         if (!srcpr) {
1387                 if (option_debug)
1388                         ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
1389                 ast_channel_unlock(dest);
1390                 ast_channel_unlock(src);
1391                 return 0;
1392         }
1393
1394         /* Get audio and video interface (if native bridge is possible) */
1395         destp = destpr->get_rtp_info(dest);
1396         vdestp = (destpr->get_vrtp_info) ? destpr->get_vrtp_info(dest) : NULL;
1397         srcp = srcpr->get_rtp_info(src);
1398         vsrcp = (srcpr->get_vrtp_info) ? srcpr->get_vrtp_info(src) : NULL;
1399
1400         /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1401         if (!destp || !srcp) {
1402                 /* Somebody doesn't want to play... */
1403                 ast_channel_unlock(dest);
1404                 ast_channel_unlock(src);
1405                 return 0;
1406         }
1407         ast_rtp_pt_copy(destp, srcp);
1408         if (vdestp && vsrcp)
1409                 ast_rtp_pt_copy(vdestp, vsrcp);
1410         if (srcpr->get_codec)
1411                 srccodec = srcpr->get_codec(src);
1412         else
1413                 srccodec = 0;
1414         if (media) {
1415                 /* Bridge early */
1416                 if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1417                         ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1418         }
1419         ast_channel_unlock(dest);
1420         ast_channel_unlock(src);
1421         if (option_debug)
1422                 ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1423         return 1;
1424 }
1425
1426 /*! \brief  Make a note of a RTP payload type that was seen in a SDP "m=" line.
1427  * By default, use the well-known value for this type (although it may 
1428  * still be set to a different value by a subsequent "a=rtpmap:" line)
1429  */
1430 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt) 
1431 {
1432         if (pt < 0 || pt > MAX_RTP_PT) 
1433                 return; /* bogus payload type */
1434
1435         if (static_RTP_PT[pt].code != 0) 
1436                 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1437
1438
1439 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1440         a SDP "a=rtpmap:" line. */
1441 void ast_rtp_set_rtpmap_type(struct ast_rtp* rtp, int pt,
1442                          char* mimeType, char* mimeSubtype) 
1443 {
1444         int i;
1445
1446         if (pt < 0 || pt > MAX_RTP_PT) 
1447                 return; /* bogus payload type */
1448
1449         for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
1450                 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1451                      strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1452                         rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1453                         return;
1454                 }
1455         }
1456
1457
1458 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls 
1459  * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1460 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1461                              int* astFormats, int* nonAstFormats) {
1462         int pt;
1463
1464         *astFormats = *nonAstFormats = 0;
1465         for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1466                 if (rtp->current_RTP_PT[pt].isAstFormat) {
1467                         *astFormats |= rtp->current_RTP_PT[pt].code;
1468                 } else {
1469                         *nonAstFormats |= rtp->current_RTP_PT[pt].code;
1470                 }
1471         }
1472 }
1473
1474 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt) 
1475 {
1476         struct rtpPayloadType result;
1477
1478         result.isAstFormat = result.code = 0;
1479         if (pt < 0 || pt > MAX_RTP_PT) 
1480                 return result; /* bogus payload type */
1481
1482         /* Start with negotiated codecs */
1483         result = rtp->current_RTP_PT[pt];
1484
1485         /* If it doesn't exist, check our static RTP type list, just in case */
1486         if (!result.code) 
1487                 result = static_RTP_PT[pt];
1488         return result;
1489 }
1490
1491 /*! \brief Looks up an RTP code out of our *static* outbound list */
1492 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code) {
1493
1494         int pt;
1495
1496         if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
1497                 code == rtp->rtp_lookup_code_cache_code) {
1498
1499                 /* Use our cached mapping, to avoid the overhead of the loop below */
1500                 return rtp->rtp_lookup_code_cache_result;
1501         }
1502
1503         /* Check the dynamic list first */
1504         for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1505                 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
1506                         rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1507                         rtp->rtp_lookup_code_cache_code = code;
1508                         rtp->rtp_lookup_code_cache_result = pt;
1509                         return pt;
1510                 }
1511         }
1512
1513         /* Then the static list */
1514         for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1515                 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
1516                         rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
1517                         rtp->rtp_lookup_code_cache_code = code;
1518                         rtp->rtp_lookup_code_cache_result = pt;
1519                         return pt;
1520                 }
1521         }
1522         return -1;
1523 }
1524
1525 char* ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code) 
1526 {
1527
1528         int i;
1529
1530         for (i = 0; i < sizeof mimeTypes/sizeof mimeTypes[0]; ++i) {
1531                 if (mimeTypes[i].payloadType.code == code && mimeTypes[i].payloadType.isAstFormat == isAstFormat)
1532                         return mimeTypes[i].subtype;
1533         }
1534         return "";
1535 }
1536
1537 char *ast_rtp_lookup_mime_multiple(char *buf, int size, const int capability, const int isAstFormat)
1538 {
1539         int format;
1540         unsigned len;
1541         char *end = buf;
1542         char *start = buf;
1543
1544         if (!buf || !size)
1545                 return NULL;
1546
1547         snprintf(end, size, "0x%x (", capability);
1548
1549         len = strlen(end);
1550         end += len;
1551         size -= len;
1552         start = end;
1553
1554         for (format = 1; format < AST_RTP_MAX; format <<= 1) {
1555                 if (capability & format) {
1556                         const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format);
1557                         snprintf(end, size, "%s|", name);
1558                         len = strlen(end);
1559                         end += len;
1560                         size -= len;
1561                 }
1562         }
1563
1564         if (start == end)
1565                 snprintf(start, size, "nothing)"); 
1566         else if (size > 1)
1567                 *(end -1) = ')';
1568         
1569         return buf;
1570 }
1571
1572 static int rtp_socket(void)
1573 {
1574         int s;
1575         long flags;
1576         s = socket(AF_INET, SOCK_DGRAM, 0);
1577         if (s > -1) {
1578                 flags = fcntl(s, F_GETFL);
1579                 fcntl(s, F_SETFL, flags | O_NONBLOCK);
1580 #ifdef SO_NO_CHECK
1581                 if (nochecksums)
1582                         setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
1583 #endif
1584         }
1585         return s;
1586 }
1587
1588 /*!
1589  * \brief Initialize a new RTCP session.
1590  * 
1591  * \returns The newly initialized RTCP session.
1592  */
1593 static struct ast_rtcp *ast_rtcp_new(void)
1594 {
1595         struct ast_rtcp *rtcp;
1596
1597         if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
1598                 return NULL;
1599         rtcp->s = rtp_socket();
1600         rtcp->us.sin_family = AF_INET;
1601         rtcp->them.sin_family = AF_INET;
1602
1603         if (rtcp->s < 0) {
1604                 free(rtcp);
1605                 ast_log(LOG_WARNING, "Unable to allocate RTCP socket: %s\n", strerror(errno));
1606                 return NULL;
1607         }
1608
1609         return rtcp;
1610 }
1611
1612 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
1613 {
1614         struct ast_rtp *rtp;
1615         int x;
1616         int first;
1617         int startplace;
1618         
1619         if (!(rtp = ast_calloc(1, sizeof(*rtp))))
1620                 return NULL;
1621         rtp->them.sin_family = AF_INET;
1622         rtp->us.sin_family = AF_INET;
1623         rtp->s = rtp_socket();
1624         rtp->ssrc = ast_random();
1625         rtp->seqno = ast_random() & 0xffff;
1626         ast_set_flag(rtp, FLAG_HAS_DTMF);
1627         if (rtp->s < 0) {
1628                 free(rtp);
1629                 ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
1630                 return NULL;
1631         }
1632         if (sched && rtcpenable) {
1633                 rtp->sched = sched;
1634                 rtp->rtcp = ast_rtcp_new();
1635         }
1636         
1637         /* Select a random port number in the range of possible RTP */
1638         x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
1639         x = x & ~1;
1640         /* Save it for future references. */
1641         startplace = x;
1642         /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
1643         for (;;) {
1644                 /* Must be an even port number by RTP spec */
1645                 rtp->us.sin_port = htons(x);
1646                 rtp->us.sin_addr = addr;
1647                 /* If there's rtcp, initialize it as well. */
1648                 if (rtp->rtcp)
1649                         rtp->rtcp->us.sin_port = htons(x + 1);
1650                 /* Try to bind it/them. */
1651                 if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
1652                         (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
1653                         break;
1654                 if (!first) {
1655                         /* Primary bind succeeded! Gotta recreate it */
1656                         close(rtp->s);
1657                         rtp->s = rtp_socket();
1658                 }
1659                 if (errno != EADDRINUSE) {
1660                         /* We got an error that wasn't expected, abort! */
1661                         ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
1662                         close(rtp->s);
1663                         if (rtp->rtcp) {
1664                                 close(rtp->rtcp->s);
1665                                 free(rtp->rtcp);
1666                         }
1667                         free(rtp);
1668                         return NULL;
1669                 }
1670                 /* The port was used, increment it (by two). */
1671                 x += 2;
1672                 /* Did we go over the limit ? */
1673                 if (x > rtpend)
1674                         /* then, start from the begingig. */
1675                         x = (rtpstart + 1) & ~1;
1676                 /* Check if we reached the place were we started. */
1677                 if (x == startplace) {
1678                         /* If so, there's no ports available. */
1679                         ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
1680                         close(rtp->s);
1681                         if (rtp->rtcp) {
1682                                 close(rtp->rtcp->s);
1683                                 free(rtp->rtcp);
1684                         }
1685                         free(rtp);
1686                         return NULL;
1687                 }
1688         }
1689         if (io && sched && callbackmode) {
1690                 /* Operate this one in a callback mode */
1691                 rtp->sched = sched;
1692                 rtp->io = io;
1693                 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
1694         }
1695         ast_rtp_pt_default(rtp);
1696         return rtp;
1697 }
1698
1699 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
1700 {
1701         struct in_addr ia;
1702
1703         memset(&ia, 0, sizeof(ia));
1704         return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
1705 }
1706
1707 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
1708 {
1709         int res;
1710
1711         if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)))) 
1712                 ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
1713         return res;
1714 }
1715
1716 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1717 {
1718         rtp->them.sin_port = them->sin_port;
1719         rtp->them.sin_addr = them->sin_addr;
1720         if (rtp->rtcp) {
1721                 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
1722                 rtp->rtcp->them.sin_addr = them->sin_addr;
1723         }
1724         rtp->rxseqno = 0;
1725 }
1726
1727 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
1728 {
1729         if ((them->sin_family != AF_INET) ||
1730                 (them->sin_port != rtp->them.sin_port) ||
1731                 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
1732                 them->sin_family = AF_INET;
1733                 them->sin_port = rtp->them.sin_port;
1734                 them->sin_addr = rtp->them.sin_addr;
1735                 return 1;
1736         }
1737         return 0;
1738 }
1739
1740 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
1741 {
1742         *us = rtp->us;
1743 }
1744
1745 void ast_rtp_stop(struct ast_rtp *rtp)
1746 {
1747         if (rtp->rtcp->schedid > 0) {
1748                 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1749                 rtp->rtcp->schedid = -1;
1750         }
1751
1752         memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
1753         memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
1754         if (rtp->rtcp) {
1755                 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
1756                 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
1757         }
1758 }
1759
1760 void ast_rtp_reset(struct ast_rtp *rtp)
1761 {
1762         memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
1763         memset(&rtp->txcore, 0, sizeof(rtp->txcore));
1764         memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
1765         rtp->lastts = 0;
1766         rtp->lastdigitts = 0;
1767         rtp->lastrxts = 0;
1768         rtp->lastividtimestamp = 0;
1769         rtp->lastovidtimestamp = 0;
1770         rtp->lasteventseqn = 0;
1771         rtp->lasteventendseqn = 0;
1772         rtp->lasttxformat = 0;
1773         rtp->lastrxformat = 0;
1774         rtp->dtmfcount = 0;
1775         rtp->dtmfduration = 0;
1776         rtp->seqno = 0;
1777         rtp->rxseqno = 0;
1778 }
1779
1780 char *ast_rtp_get_quality(struct ast_rtp *rtp)
1781 {
1782         /*
1783         *ssrc          our ssrc
1784         *themssrc      their ssrc
1785         *lp            lost packets
1786         *rxjitter      our calculated jitter(rx)
1787         *rxcount       no. received packets
1788         *txjitter      reported jitter of the other end
1789         *txcount       transmitted packets
1790         *rlp           remote lost packets
1791         */
1792         
1793         snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality), "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f", rtp->ssrc, rtp->themssrc, rtp->rtcp->expected_prior - rtp->rtcp->received_prior, rtp->rxjitter, rtp->rxcount, (double)rtp->rtcp->reported_jitter/65536., rtp->txcount, rtp->rtcp->reported_lost, rtp->rtcp->rtt);
1794         
1795         return rtp->rtcp->quality;
1796 }
1797
1798 void ast_rtp_destroy(struct ast_rtp *rtp)
1799 {
1800         if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
1801                 /*Print some info on the call here */
1802                 ast_verbose("  RTP-stats\n");
1803                 ast_verbose("* Our Receiver:\n");
1804                 ast_verbose("  SSRC:             %u\n", rtp->themssrc);
1805                 ast_verbose("  Received packets: %u\n", rtp->rxcount);
1806                 ast_verbose("  Lost packets:     %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
1807                 ast_verbose("  Jitter:           %.4f\n", rtp->rxjitter);
1808                 ast_verbose("  Transit:          %.4f\n", rtp->rxtransit);
1809                 ast_verbose("  RR-count:         %u\n", rtp->rtcp->rr_count);
1810                 ast_verbose("* Our Sender:\n");
1811                 ast_verbose("  SSRC:             %u\n", rtp->ssrc);
1812                 ast_verbose("  Sent packets:     %u\n", rtp->txcount);
1813                 ast_verbose("  Lost packets:     %u\n", rtp->rtcp->reported_lost);
1814                 ast_verbose("  Jitter:           %u\n", rtp->rtcp->reported_jitter);
1815                 ast_verbose("  SR-count:         %u\n", rtp->rtcp->sr_count);
1816                 ast_verbose("  RTT:              %f\n", rtp->rtcp->rtt);
1817         }
1818
1819         if (rtp->rtcp->schedid > 0) {
1820                 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1821                 rtp->rtcp->schedid = -1;
1822         }
1823
1824         if (rtp->smoother)
1825                 ast_smoother_free(rtp->smoother);
1826         if (rtp->ioid)
1827                 ast_io_remove(rtp->io, rtp->ioid);
1828         if (rtp->s > -1)
1829                 close(rtp->s);
1830         if (rtp->rtcp) {
1831                 close(rtp->rtcp->s);
1832                 free(rtp->rtcp);
1833                 rtp->rtcp=NULL;
1834         }
1835         free(rtp);
1836 }
1837
1838 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
1839 {
1840         struct timeval t;
1841         long ms;
1842         if (ast_tvzero(rtp->txcore)) {
1843                 rtp->txcore = ast_tvnow();
1844                 /* Round to 20ms for nice, pretty timestamps */
1845                 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
1846         }
1847         /* Use previous txcore if available */
1848         t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
1849         ms = ast_tvdiff_ms(t, rtp->txcore);
1850         if (ms < 0)
1851                 ms = 0;
1852         /* Use what we just got for next time */
1853         rtp->txcore = t;
1854         return (unsigned int) ms;
1855 }
1856
1857 int ast_rtp_senddigit(struct ast_rtp *rtp, char digit)
1858 {
1859         unsigned int *rtpheader;
1860         int hdrlen = 12;
1861         int res;
1862         int x;
1863         int payload;
1864         char data[256];
1865         char iabuf[INET_ADDRSTRLEN];
1866
1867         if ((digit <= '9') && (digit >= '0'))
1868                 digit -= '0';
1869         else if (digit == '*')
1870                 digit = 10;
1871         else if (digit == '#')
1872                 digit = 11;
1873         else if ((digit >= 'A') && (digit <= 'D')) 
1874                 digit = digit - 'A' + 12;
1875         else if ((digit >= 'a') && (digit <= 'd')) 
1876                 digit = digit - 'a' + 12;
1877         else {
1878                 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
1879                 return -1;
1880         }
1881         payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
1882
1883         /* If we have no peer, return immediately */    
1884         if (!rtp->them.sin_addr.s_addr)
1885                 return 0;
1886
1887         rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
1888         
1889         /* Get a pointer to the header */
1890         rtpheader = (unsigned int *)data;
1891         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
1892         rtpheader[1] = htonl(rtp->lastdigitts);
1893         rtpheader[2] = htonl(rtp->ssrc); 
1894         rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (0));
1895         for (x = 0; x < 6; x++) {
1896                 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
1897                         res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
1898                         if (res < 0) 
1899                                 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
1900                                         ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1901                                         ntohs(rtp->them.sin_port), strerror(errno));
1902                         if (rtp_debug_test_addr(&rtp->them))
1903                                 ast_verbose("Sent RTP DTMF packet to %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1904                                             ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr),
1905                                             ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
1906                 }
1907                 /* Sequence number of last two end packets does not get incremented */
1908                 if (x < 3)
1909                         rtp->seqno++;
1910                 /* Clear marker bit and set seqno */
1911                 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
1912                 /* For the last three packets, set the duration and the end bit */
1913                 if (x == 2) {
1914 #if 0
1915                         /* No, this is wrong...  Do not increment lastdigitts, that's not according
1916                            to the RFC, as best we can determine */
1917                         rtp->lastdigitts++; /* or else the SPA3000 will click instead of beeping... */
1918                         rtpheader[1] = htonl(rtp->lastdigitts);
1919 #endif                  
1920                         /* Make duration 800 (100ms) */
1921                         rtpheader[3] |= htonl((800));
1922                         /* Set the End bit */
1923                         rtpheader[3] |= htonl((1 << 23));
1924                 }
1925         }
1926         /*! \note Increment the digit timestamp by 120ms, to ensure that digits
1927            sent sequentially with no intervening non-digit packets do not
1928            get sent with the same timestamp, and that sequential digits
1929            have some 'dead air' in between them
1930         */
1931         rtp->lastdigitts += 960;
1932         /* Increment the sequence number to reflect the last packet
1933            that was sent
1934         */
1935         rtp->seqno++;
1936         return 0;
1937 }
1938
1939 /* \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
1940 int ast_rtcp_send_h261fur(void *data)
1941 {
1942         struct ast_rtp *rtp = data;
1943         int res;
1944
1945         rtp->rtcp->sendfur = 1;
1946         res = ast_rtcp_write(data);
1947         
1948         return res;
1949 }
1950
1951 /*! \brief Send RTCP sender's report */
1952 static int ast_rtcp_write_sr(void *data)
1953 {
1954         struct ast_rtp *rtp = data;
1955         int res;
1956         int len = 0;
1957         struct timeval now;
1958         unsigned int now_lsw;
1959         unsigned int now_msw;
1960         unsigned int *rtcpheader;
1961         unsigned int lost;
1962         unsigned int extended;
1963         unsigned int expected;
1964         unsigned int expected_interval;
1965         unsigned int received_interval;
1966         int lost_interval;
1967         int fraction;
1968         struct timeval dlsr;
1969         char bdata[512];
1970         char iabuf[INET_ADDRSTRLEN];
1971
1972         if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
1973                 return 0;
1974         
1975         if (!rtp->rtcp->them.sin_addr.s_addr) {  /* This'll stop rtcp for this rtp session */
1976                 ast_verbose("RTCP SR transmission error, rtcp halted %s\n",strerror(errno));
1977                 if (rtp->rtcp->schedid > 0)
1978                         ast_sched_del(rtp->sched, rtp->rtcp->schedid);
1979                 rtp->rtcp->schedid = -1;
1980                 return 0;
1981         }
1982
1983         gettimeofday(&now, NULL);
1984         timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
1985         rtcpheader = (unsigned int *)bdata;
1986         rtcpheader[1] = htonl(rtp->ssrc);               /* Our SSRC */
1987         rtcpheader[2] = htonl(now_msw);                 /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
1988         rtcpheader[3] = htonl(now_lsw);                 /* now, LSW */
1989         rtcpheader[4] = htonl(rtp->lastts);             /* FIXME shouldn't be that, it should be now */
1990         rtcpheader[5] = htonl(rtp->txcount);            /* No. packets sent */
1991         rtcpheader[6] = htonl(rtp->txoctetcount);       /* No. bytes sent */
1992         len += 28;
1993         
1994         extended = rtp->cycles + rtp->lastrxseqno;
1995         expected = extended - rtp->seedrxseqno + 1;
1996         if (rtp->rxcount > expected) 
1997                 expected += rtp->rxcount - expected;
1998         lost = expected - rtp->rxcount;
1999         expected_interval = expected - rtp->rtcp->expected_prior;
2000         rtp->rtcp->expected_prior = expected;
2001         received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2002         rtp->rtcp->received_prior = rtp->rxcount;
2003         lost_interval = expected_interval - received_interval;
2004         if (expected_interval == 0 || lost_interval <= 0)
2005                 fraction = 0;
2006         else
2007                 fraction = (lost_interval << 8) / expected_interval;
2008         timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2009         rtcpheader[7] = htonl(rtp->themssrc);
2010         rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2011         rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2012         rtcpheader[10] = htonl((unsigned int)rtp->rxjitter);
2013         rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2014         rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2015         len += 24;
2016         
2017         rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2018
2019         if (rtp->rtcp->sendfur) {
2020                 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2021                 rtcpheader[14] = htonl(rtp->ssrc);               /* Our SSRC */
2022                 len += 8;
2023                 rtp->rtcp->sendfur = 0;
2024         }
2025         
2026         /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */ 
2027         /* it can change mid call, and SDES can't) */
2028         rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2029         rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
2030         rtcpheader[(len/4)+2] = htonl(0x01 << 24);                    /* Empty for the moment */
2031         len += 12;
2032         
2033         res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2034         if (res < 0) {
2035                 ast_log(LOG_ERROR, "RTCP SR transmission error to %s:%d, rtcp halted %s\n",ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port), strerror(errno));
2036                 if (rtp->rtcp->schedid > 0)
2037                         ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2038                 rtp->rtcp->schedid = -1;
2039                 return 0;
2040         }
2041         
2042         /* FIXME Don't need to get a new one */
2043         gettimeofday(&rtp->rtcp->txlsr, NULL);
2044         rtp->rtcp->sr_count++;
2045
2046         rtp->rtcp->lastsrtxcount = rtp->txcount;        
2047         
2048         if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2049                 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2050                 ast_verbose("  Our SSRC: %u\n", rtp->ssrc);
2051                 ast_verbose("  Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2052                 ast_verbose("  Sent(RTP): %u\n", rtp->lastts);
2053                 ast_verbose("  Sent packets: %u\n", rtp->txcount);
2054                 ast_verbose("  Sent octets: %u\n", rtp->txoctetcount);
2055                 ast_verbose("  Report block:\n");
2056                 ast_verbose("  Fraction lost: %u\n", fraction);
2057                 ast_verbose("  Cumulative loss: %u\n", lost);
2058                 ast_verbose("  IA jitter: %.4f\n", rtp->rxjitter);
2059                 ast_verbose("  Their last SR: %u\n", rtp->rtcp->themrxlsr);
2060                 ast_verbose("  DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2061         }
2062         return res;
2063 }
2064
2065 /*! \brief Send RTCP recepient's report */
2066 static int ast_rtcp_write_rr(void *data)
2067 {
2068         struct ast_rtp *rtp = data;
2069         int res;
2070         int len = 32;
2071         unsigned int lost;
2072         unsigned int extended;
2073         unsigned int expected;
2074         unsigned int expected_interval;
2075         unsigned int received_interval;
2076         int lost_interval;
2077         struct timeval now;
2078         unsigned int *rtcpheader;
2079         char bdata[1024];
2080         char iabuf[INET_ADDRSTRLEN];
2081         struct timeval dlsr;
2082         int fraction;
2083
2084         if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2085                 return 0;
2086           
2087         if (!rtp->rtcp->them.sin_addr.s_addr) {
2088                 ast_log(LOG_ERROR, "RTCP RR transmission error to, rtcp halted %s\n",strerror(errno));
2089                 if (rtp->rtcp->schedid > 0)
2090                         ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2091                 rtp->rtcp->schedid = -1;
2092                 return 0;
2093         }
2094
2095         extended = rtp->cycles + rtp->lastrxseqno;
2096         expected = extended - rtp->seedrxseqno + 1;
2097         lost = expected - rtp->rxcount;
2098         expected_interval = expected - rtp->rtcp->expected_prior;
2099         rtp->rtcp->expected_prior = expected;
2100         received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2101         rtp->rtcp->received_prior = rtp->rxcount;
2102         lost_interval = expected_interval - received_interval;
2103         if (expected_interval == 0 || lost_interval <= 0)
2104                 fraction = 0;
2105         else
2106                 fraction = (lost_interval << 8) / expected_interval;
2107         gettimeofday(&now, NULL);
2108         timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2109         rtcpheader = (unsigned int *)bdata;
2110         rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2111         rtcpheader[1] = htonl(rtp->ssrc);
2112         rtcpheader[2] = htonl(rtp->themssrc);
2113         rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2114         rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2115         rtcpheader[5] = htonl((unsigned int)rtp->rxjitter);
2116         rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2117         rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2118
2119         if (rtp->rtcp->sendfur) {
2120                 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2121                 rtcpheader[9] = htonl(rtp->ssrc);               /* Our SSRC */
2122                 len += 8;
2123                 rtp->rtcp->sendfur = 0;
2124         }
2125
2126         /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos 
2127         it can change mid call, and SDES can't) */
2128         rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2129         rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
2130         rtcpheader[(len/4)+2] = htonl(0x01 << 24);              /* Empty for the moment */
2131         len += 12;
2132         
2133         res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2134
2135         if (res < 0) {
2136                 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2137                 /* Remove the scheduler */
2138                 if (rtp->rtcp->schedid > 0)
2139                         ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2140                 rtp->rtcp->schedid = -1;
2141                 return 0;
2142         }
2143
2144         rtp->rtcp->rr_count++;
2145
2146         if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2147                 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2148                         "  Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n" 
2149                         "  IA jitter: %.4f\n" 
2150                         "  Their last SR: %u\n" 
2151                         "  DLSR: %4.4f (sec)\n\n",
2152                         ast_inet_ntoa(iabuf, sizeof(iabuf),
2153                         rtp->rtcp->them.sin_addr),
2154                         ntohs(rtp->rtcp->them.sin_port),
2155                         rtp->ssrc, rtp->themssrc, fraction, lost,
2156                         rtp->rxjitter,
2157                         rtp->rtcp->themrxlsr,
2158                         (double)(ntohl(rtcpheader[7])/65536.0));
2159         }
2160
2161         return res;
2162 }
2163
2164 /*! \brief Write and RTCP packet to the far end
2165  * \note Decide if we are going to send an SR (with Reception Block) or RR 
2166  * RR is sent if we have not sent any rtp packets in the previous interval */
2167 static int ast_rtcp_write(void *data)
2168 {
2169         struct ast_rtp *rtp = data;
2170         int res;
2171         
2172         if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2173                 res = ast_rtcp_write_sr(data);
2174         else
2175                 res = ast_rtcp_write_rr(data);
2176         
2177         return res;
2178 }
2179
2180 /*! \brief generate comfort noice (CNG) */
2181 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2182 {
2183         unsigned int *rtpheader;
2184         int hdrlen = 12;
2185         int res;
2186         int payload;
2187         char data[256];
2188         char iabuf[INET_ADDRSTRLEN];
2189         level = 127 - (level & 0x7f);
2190         payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2191
2192         /* If we have no peer, return immediately */    
2193         if (!rtp->them.sin_addr.s_addr)
2194                 return 0;
2195
2196         rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2197
2198         /* Get a pointer to the header */
2199         rtpheader = (unsigned int *)data;
2200         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2201         rtpheader[1] = htonl(rtp->lastts);
2202         rtpheader[2] = htonl(rtp->ssrc); 
2203         data[12] = level;
2204         if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2205                 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2206                 if (res <0) 
2207                         ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s:%d: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
2208                 if (rtp_debug_test_addr(&rtp->them))
2209                         ast_verbose("Sent Comfort Noise RTP packet to %s:%d (type %d, seq %d, ts %u, len %d)\n"
2210                                         , ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);              
2211                    
2212         }
2213         return 0;
2214 }
2215
2216 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2217 {
2218         unsigned char *rtpheader;
2219         char iabuf[INET_ADDRSTRLEN];
2220         int hdrlen = 12;
2221         int res;
2222         unsigned int ms;
2223         int pred;
2224         int mark = 0;
2225
2226         ms = calc_txstamp(rtp, &f->delivery);
2227         /* Default prediction */
2228         if (f->subclass < AST_FORMAT_MAX_AUDIO) {
2229                 pred = rtp->lastts + f->samples;
2230
2231                 /* Re-calculate last TS */
2232                 rtp->lastts = rtp->lastts + ms * 8;
2233                 if (ast_tvzero(f->delivery)) {
2234                         /* If this isn't an absolute delivery time, Check if it is close to our prediction, 
2235                            and if so, go with our prediction */
2236                         if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
2237                                 rtp->lastts = pred;
2238                         else {
2239                                 if (option_debug > 2)
2240                                         ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2241                                 mark = 1;
2242                         }
2243                 }
2244         } else {
2245                 mark = f->subclass & 0x1;
2246                 pred = rtp->lastovidtimestamp + f->samples;
2247                 /* Re-calculate last TS */
2248                 rtp->lastts = rtp->lastts + ms * 90;
2249                 /* If it's close to our prediction, go for it */
2250                 if (ast_tvzero(f->delivery)) {
2251                         if (abs(rtp->lastts - pred) < 7200) {
2252                                 rtp->lastts = pred;
2253                                 rtp->lastovidtimestamp += f->samples;
2254                         } else {
2255                                 if (option_debug > 2)
2256                                         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);
2257                                 rtp->lastovidtimestamp = rtp->lastts;
2258                         }
2259                 }
2260         }
2261         /* If the timestamp for non-digit packets has moved beyond the timestamp
2262            for digits, update the digit timestamp.
2263         */
2264         if (rtp->lastts > rtp->lastdigitts)
2265                 rtp->lastdigitts = rtp->lastts;
2266
2267         if (f->has_timing_info)
2268                 rtp->lastts = f->ts * 8;
2269
2270         /* Get a pointer to the header */
2271         rtpheader = (unsigned char *)(f->data - hdrlen);
2272
2273         put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
2274         put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
2275         put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc)); 
2276
2277         if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2278                 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2279                 if (res <0) {
2280                         if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
2281                                 ast_log(LOG_DEBUG, "RTP Transmission error of packet %d to %s:%d: %s\n", rtp->seqno, ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
2282                         } else if ((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) {
2283                                 /* Only give this error message once if we are not RTP debugging */
2284                                 if (option_debug || rtpdebug)
2285                                         ast_log(LOG_DEBUG, "RTP NAT: Can't write RTP to private address %s:%d, waiting for other end to send audio...\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port));
2286                                 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
2287                         }
2288                 } else {
2289                         rtp->txcount++;
2290                         rtp->txoctetcount +=(res - hdrlen);
2291                         
2292                         if (rtp->rtcp->schedid < 1) 
2293                             rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
2294                 }
2295                                 
2296                 if (rtp_debug_test_addr(&rtp->them))
2297                         ast_verbose("Sent RTP packet to      %s:%d (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2298                                         ast_inet_ntoa(iabuf, sizeof(iabuf), rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
2299         }
2300
2301         rtp->seqno++;
2302
2303         return 0;
2304 }
2305
2306 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
2307 {
2308         struct ast_frame *f;
2309         int codec;
2310         int hdrlen = 12;
2311         int subclass;
2312         
2313
2314         /* If we have no peer, return immediately */    
2315         if (!rtp->them.sin_addr.s_addr)
2316                 return 0;
2317
2318         /* If there is no data length, return immediately */
2319         if (!_f->datalen) 
2320                 return 0;
2321         
2322         /* Make sure we have enough space for RTP header */
2323         if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
2324                 ast_log(LOG_WARNING, "RTP can only send voice and video\n");
2325                 return -1;
2326         }
2327
2328         subclass = _f->subclass;
2329         if (_f->frametype == AST_FRAME_VIDEO)
2330                 subclass &= ~0x1;
2331
2332         codec = ast_rtp_lookup_code(rtp, 1, subclass);
2333         if (codec < 0) {
2334                 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
2335                 return -1;
2336         }
2337
2338         if (rtp->lasttxformat != subclass) {
2339                 /* New format, reset the smoother */
2340                 if (option_debug)
2341                         ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
2342                 rtp->lasttxformat = subclass;
2343                 if (rtp->smoother)
2344                         ast_smoother_free(rtp->smoother);
2345                 rtp->smoother = NULL;
2346         }
2347
2348
2349         switch(subclass) {
2350         case AST_FORMAT_SLINEAR:
2351                 if (!rtp->smoother) {
2352                         rtp->smoother = ast_smoother_new(320);
2353                 }
2354                 if (!rtp->smoother) {
2355                         ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2356                         return -1;
2357                 }
2358                 ast_smoother_feed_be(rtp->smoother, _f);
2359                 
2360                 while((f = ast_smoother_read(rtp->smoother)))
2361                         ast_rtp_raw_write(rtp, f, codec);
2362                 break;
2363         case AST_FORMAT_ULAW:
2364         case AST_FORMAT_ALAW:
2365                 if (!rtp->smoother) {
2366                         rtp->smoother = ast_smoother_new(160);
2367                 }
2368                 if (!rtp->smoother) {
2369                         ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2370                         return -1;
2371                 }
2372                 ast_smoother_feed(rtp->smoother, _f);
2373                 
2374                 while((f = ast_smoother_read(rtp->smoother)))
2375                         ast_rtp_raw_write(rtp, f, codec);
2376                 break;
2377         case AST_FORMAT_ADPCM:
2378         case AST_FORMAT_G726:
2379                 if (!rtp->smoother) {
2380                         rtp->smoother = ast_smoother_new(80);
2381                 }
2382                 if (!rtp->smoother) {
2383                         ast_log(LOG_WARNING, "Unable to create smoother :(\n");
2384                         return -1;
2385                 }
2386                 ast_smoother_feed(rtp->smoother, _f);
2387                 
2388                 while((f = ast_smoother_read(rtp->smoother)))
2389                         ast_rtp_raw_write(rtp, f, codec);
2390                 break;
2391         case AST_FORMAT_G729A:
2392                 if (!rtp->smoother) {
2393                         rtp->smoother = ast_smoother_new(20);
2394                         if (rtp->smoother)
2395                                 ast_smoother_set_flags(rtp->smoother, AST_SMOOTHER_FLAG_G729);
2396                 }
2397                 if (!rtp->smoother) {
2398                         ast_log(LOG_WARNING, "Unable to create g729 smoother :(\n");
2399                         return -1;
2400                 }
2401                 ast_smoother_feed(rtp->smoother, _f);
2402                 
2403                 while((f = ast_smoother_read(rtp->smoother)))
2404                         ast_rtp_raw_write(rtp, f, codec);
2405                 break;
2406         case AST_FORMAT_GSM:
2407                 if (!rtp->smoother) {
2408                         rtp->smoother = ast_smoother_new(33);
2409                 }
2410                 if (!rtp->smoother) {
2411                         ast_log(LOG_WARNING, "Unable to create GSM smoother :(\n");
2412                         return -1;
2413                 }
2414                 ast_smoother_feed(rtp->smoother, _f);
2415                 while((f = ast_smoother_read(rtp->smoother)))
2416                         ast_rtp_raw_write(rtp, f, codec);
2417                 break;
2418         case AST_FORMAT_ILBC:
2419                 if (!rtp->smoother) {
2420                         rtp->smoother = ast_smoother_new(50);
2421                 }
2422                 if (!rtp->smoother) {
2423                         ast_log(LOG_WARNING, "Unable to create ILBC smoother :(\n");
2424                         return -1;
2425                 }
2426                 ast_smoother_feed(rtp->smoother, _f);
2427                 while((f = ast_smoother_read(rtp->smoother)))
2428                         ast_rtp_raw_write(rtp, f, codec);
2429                 break;
2430         default:        
2431                 ast_log(LOG_WARNING, "Not sure about sending format %s packets\n", ast_getformatname(subclass));
2432                 /* fall through to... */
2433         case AST_FORMAT_H261:
2434         case AST_FORMAT_H263:
2435         case AST_FORMAT_H263_PLUS:
2436         case AST_FORMAT_H264:
2437         case AST_FORMAT_G723_1:
2438         case AST_FORMAT_LPC10:
2439         case AST_FORMAT_SPEEX:
2440                 /* Don't buffer outgoing frames; send them one-per-packet: */
2441                 if (_f->offset < hdrlen) {
2442                         f = ast_frdup(_f);
2443                 } else {
2444                         f = _f;
2445                 }
2446                 ast_rtp_raw_write(rtp, f, codec);
2447         }
2448                 
2449         return 0;
2450 }
2451
2452 /*! \brief Unregister interface to channel driver */
2453 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
2454 {
2455         AST_LIST_LOCK(&protos);
2456         AST_LIST_REMOVE(&protos, proto, list);
2457         AST_LIST_UNLOCK(&protos);
2458 }
2459
2460 /*! \brief Register interface to channel driver */
2461 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
2462 {
2463         struct ast_rtp_protocol *cur;
2464
2465         AST_LIST_LOCK(&protos);
2466         AST_LIST_TRAVERSE(&protos, cur, list) { 
2467                 if (!strcmp(cur->type, proto->type)) {
2468                         ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
2469                         AST_LIST_UNLOCK(&protos);
2470                         return -1;
2471                 }
2472         }
2473         AST_LIST_INSERT_HEAD(&protos, proto, list);
2474         AST_LIST_UNLOCK(&protos);
2475         
2476         return 0;
2477 }
2478
2479 /*! \brief Bridge calls. If possible and allowed, initiate
2480         re-invite so the peers exchange media directly outside 
2481         of Asterisk. */
2482 enum ast_bridge_result ast_rtp_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
2483 {
2484         struct ast_frame *f;
2485         struct ast_channel *who, *other, *cs[3];
2486         struct ast_rtp *p0, *p1;                /* Audio RTP Channels */
2487         struct ast_rtp *vp0, *vp1;              /* Video RTP channels */
2488         struct ast_rtp_protocol *pr0, *pr1;
2489         struct sockaddr_in ac0, ac1;
2490         struct sockaddr_in vac0, vac1;
2491         struct sockaddr_in t0, t1;
2492         struct sockaddr_in vt0, vt1;
2493         char iabuf[INET_ADDRSTRLEN];
2494         
2495         void *pvt0, *pvt1;
2496         int codec0,codec1, oldcodec0, oldcodec1;
2497         
2498         memset(&vt0, 0, sizeof(vt0));
2499         memset(&vt1, 0, sizeof(vt1));
2500         memset(&vac0, 0, sizeof(vac0));
2501         memset(&vac1, 0, sizeof(vac1));
2502
2503         /* Lock channels */
2504         ast_channel_lock(c0);
2505         while(ast_channel_trylock(c1)) {
2506                 ast_channel_unlock(c0);
2507                 usleep(1);
2508                 ast_channel_lock(c0);
2509         }
2510
2511         /* Find channel driver interfaces */
2512         pr0 = get_proto(c0);
2513         pr1 = get_proto(c1);
2514         if (!pr0) {
2515                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
2516                 ast_channel_unlock(c0);
2517                 ast_channel_unlock(c1);
2518                 return AST_BRIDGE_FAILED;
2519         }
2520         if (!pr1) {
2521                 ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
2522                 ast_channel_unlock(c0);
2523                 ast_channel_unlock(c1);
2524                 return AST_BRIDGE_FAILED;
2525         }
2526
2527         /* Get channel specific interface structures */
2528         pvt0 = c0->tech_pvt;
2529         pvt1 = c1->tech_pvt;
2530
2531         /* Get audio and video interface (if native bridge is possible) */
2532         p0 = pr0->get_rtp_info(c0);
2533         vp0 = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0) : NULL;
2534         p1 = pr1->get_rtp_info(c1);
2535         vp1 = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1) : NULL;
2536
2537         /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
2538         if (!p0 || !p1) {
2539                 /* Somebody doesn't want to play... */
2540                 ast_channel_unlock(c0);
2541                 ast_channel_unlock(c1);
2542                 return AST_BRIDGE_FAILED_NOWARN;
2543         }
2544
2545         if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2546                 /* can't bridge, we are carrying DTMF for this channel and the bridge
2547                    needs it
2548                 */
2549                 ast_channel_unlock(c0);
2550                 ast_channel_unlock(c1);
2551                 return AST_BRIDGE_FAILED_NOWARN;
2552         }
2553
2554         if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
2555                 /* can't bridge, we are carrying DTMF for this channel and the bridge
2556                    needs it
2557                 */
2558                 ast_channel_unlock(c0);
2559                 ast_channel_unlock(c1);
2560                 return AST_BRIDGE_FAILED_NOWARN;
2561         }
2562
2563         /* Get codecs from both sides */
2564         codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
2565         codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
2566         if (pr0->get_codec && pr1->get_codec) {
2567                 /* Hey, we can't do reinvite if both parties speak different codecs */
2568                 if (!(codec0 & codec1)) {
2569                         if (option_debug)
2570                                 ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
2571                         ast_channel_unlock(c0);
2572                         ast_channel_unlock(c1);
2573                         return AST_BRIDGE_FAILED_NOWARN;
2574                 }
2575         }
2576
2577         if (option_verbose > 2) 
2578                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
2579
2580         /* Ok, we should be able to redirect the media. Start with one channel */
2581         if (pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE))) 
2582                 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
2583         else {
2584                 /* Store RTP peer */
2585                 ast_rtp_get_peer(p1, &ac1);
2586                 if (vp1)
2587                         ast_rtp_get_peer(vp1, &vac1);
2588         }
2589         /* Then test the other channel */
2590         if (pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
2591                 ast_log(LOG_WARNING, "Channel '%s' failed to talk back to '%s'\n", c1->name, c0->name);
2592         else {
2593                 /* Store RTP peer */
2594                 ast_rtp_get_peer(p0, &ac0);
2595                 if (vp0)
2596                         ast_rtp_get_peer(vp0, &vac0);
2597         }
2598         ast_channel_unlock(c0);
2599         ast_channel_unlock(c1);
2600         /* External RTP Bridge up, now loop and see if something happes that force us to take the
2601                 media back to Asterisk */
2602         cs[0] = c0;
2603         cs[1] = c1;
2604         cs[2] = NULL;
2605         oldcodec0 = codec0;
2606         oldcodec1 = codec1;
2607         for (;;) {
2608                 /* Check if something changed... */
2609                 if ((c0->tech_pvt != pvt0)  ||
2610                         (c1->tech_pvt != pvt1) ||
2611                         (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
2612                                 ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
2613                                 if (c0->tech_pvt == pvt0) {
2614                                         if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0)) 
2615                                                 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2616                                 }
2617                                 if (c1->tech_pvt == pvt1) {
2618                                         if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0)) 
2619                                                 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2620                                 }
2621                                 return AST_BRIDGE_RETRY;
2622                 }
2623                 /* Now check if they have changed address */
2624                 ast_rtp_get_peer(p1, &t1);
2625                 ast_rtp_get_peer(p0, &t0);
2626                 if (pr0->get_codec)
2627                         codec0 = pr0->get_codec(c0);
2628                 if (pr1->get_codec)
2629                         codec1 = pr1->get_codec(c1);
2630                 if (vp1)
2631                         ast_rtp_get_peer(vp1, &vt1);
2632                 if (vp0)
2633                         ast_rtp_get_peer(vp0, &vt0);
2634                 if (inaddrcmp(&t1, &ac1) || (vp1 && inaddrcmp(&vt1, &vac1)) || (codec1 != oldcodec1)) {
2635                         if (option_debug > 1) {
2636                                 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n", 
2637                                         c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t1.sin_addr), ntohs(t1.sin_port), codec1);
2638                                 ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n", 
2639                                         c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vt1.sin_addr), ntohs(vt1.sin_port), codec1);
2640                                 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n", 
2641                                         c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
2642                                 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n", 
2643                                         c1->name, ast_inet_ntoa(iabuf, sizeof(iabuf), vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
2644                         }
2645                         if (pr0->set_rtp_peer(c0, t1.sin_addr.s_addr ? p1 : NULL, vt1.sin_addr.s_addr ? vp1 : NULL, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE))) 
2646                                 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
2647                         memcpy(&ac1, &t1, sizeof(ac1));
2648                         memcpy(&vac1, &vt1, sizeof(vac1));
2649                         oldcodec1 = codec1;
2650                 }
2651                 if (inaddrcmp(&t0, &ac0) || (vp0 && inaddrcmp(&vt0, &vac0))) {
2652                         if (option_debug) {
2653                                 ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n", 
2654                                         c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), t0.sin_addr), ntohs(t0.sin_port), codec0);
2655                                 ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n", 
2656                                         c0->name, ast_inet_ntoa(iabuf, sizeof(iabuf), ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
2657                         }
2658                         if (pr1->set_rtp_peer(c1, t0.sin_addr.s_addr ? p0 : NULL, vt0.sin_addr.s_addr ? vp0 : NULL, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
2659                                 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
2660                         memcpy(&ac0, &t0, sizeof(ac0));
2661                         memcpy(&vac0, &vt0, sizeof(vac0));
2662                         oldcodec0 = codec0;
2663                 }
2664                 who = ast_waitfor_n(cs, 2, &timeoutms);
2665                 if (!who) {
2666                         if (!timeoutms) 
2667                                 return AST_BRIDGE_RETRY;
2668                         if (option_debug)
2669                                 ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2670                         /* check for hangup / whentohangup */
2671                         if (ast_check_hangup(c0) || ast_check_hangup(c1))
2672                                 break;
2673                         continue;
2674                 }
2675                 f = ast_read(who);
2676                 other = (who == c0) ? c1 : c0; /* the other channel */
2677                 if (!f || ((f->frametype == AST_FRAME_DTMF) &&
2678                                    (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2679                                ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
2680                         /* breaking out of the bridge. */
2681                         *fo = f;
2682                         *rc = who;
2683                         if (option_debug)
2684                                 ast_log(LOG_DEBUG, "Oooh, got a %s\n", f ? "digit" : "hangup");
2685                         if ((c0->tech_pvt == pvt0)) {
2686                                 if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0)) 
2687                                         ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
2688                         }
2689                         if ((c1->tech_pvt == pvt1)) {
2690                                 if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0)) 
2691                                         ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
2692                         }
2693                         return AST_BRIDGE_COMPLETE;
2694                 } else if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2695                         if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
2696                             (f->subclass == AST_CONTROL_VIDUPDATE)) {
2697                                 ast_indicate(other, f->subclass);
2698                                 ast_frfree(f);
2699                         } else {
2700                                 *fo = f;
2701                                 *rc = who;
2702                                 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2703                                 return AST_BRIDGE_COMPLETE;
2704                         }
2705                 } else {
2706                         if ((f->frametype == AST_FRAME_DTMF) || 
2707                                 (f->frametype == AST_FRAME_VOICE) || 
2708                                 (f->frametype == AST_FRAME_VIDEO)) {
2709                                 /* Forward voice or DTMF frames if they happen upon us */
2710                                 ast_write(other, f);
2711                         }
2712                         ast_frfree(f);
2713                 }
2714                 /* Swap priority not that it's a big deal at this point */
2715                 cs[2] = cs[0];
2716                 cs[0] = cs[1];
2717                 cs[1] = cs[2];
2718                 
2719         }
2720         return AST_BRIDGE_FAILED;
2721 }
2722
2723 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
2724 {
2725         struct hostent *hp;
2726         struct ast_hostent ahp;
2727         char iabuf[INET_ADDRSTRLEN];
2728         int port = 0;
2729         char *p, *arg;
2730
2731         if (argc != 4)
2732                 return RESULT_SHOWUSAGE;
2733         arg = argv[3];
2734         p = strstr(arg, ":");
2735         if (p) {
2736                 *p = '\0';
2737                 p++;
2738                 port = atoi(p);
2739         }
2740         hp = ast_gethostbyname(arg, &ahp);
2741         if (hp == NULL)
2742                 return RESULT_SHOWUSAGE;
2743         rtpdebugaddr.sin_family = AF_INET;
2744         memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
2745         rtpdebugaddr.sin_port = htons(port);
2746         if (port == 0)
2747                 ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr));
2748         else
2749                 ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtpdebugaddr.sin_addr), port);
2750         rtpdebug = 1;
2751         return RESULT_SUCCESS;
2752 }
2753
2754 static int rtcp_do_debug_ip(int fd, int argc, char *argv[])
2755 {
2756         struct hostent *hp;
2757         struct ast_hostent ahp;
2758         char iabuf[INET_ADDRSTRLEN];
2759         int port = 0;
2760         char *p, *arg;
2761         if (argc != 5)
2762                 return RESULT_SHOWUSAGE;
2763
2764         arg = argv[4];
2765         p = strstr(arg, ":");
2766         if (p) {
2767                 *p = '\0';
2768                 p++;
2769                 port = atoi(p);
2770         }
2771         hp = ast_gethostbyname(arg, &ahp);
2772         if (hp == NULL)
2773                 return RESULT_SHOWUSAGE;
2774         rtcpdebugaddr.sin_family = AF_INET;
2775         memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
2776         rtcpdebugaddr.sin_port = htons(port);
2777         if (port == 0)
2778                 ast_cli(fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtcpdebugaddr.sin_addr));
2779         else
2780                 ast_cli(fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(iabuf, sizeof(iabuf), rtcpdebugaddr.sin_addr), port);
2781         rtcpdebug = 1;
2782         return RESULT_SUCCESS;
2783 }
2784
2785 static int rtp_do_debug(int fd, int argc, char *argv[])
2786 {
2787         if (argc != 2) {
2788                 if (argc != 4)
2789                         return RESULT_SHOWUSAGE;
2790                 return rtp_do_debug_ip(fd, argc, argv);
2791         }
2792         rtpdebug = 1;
2793         memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
2794         ast_cli(fd, "RTP Debugging Enabled\n");
2795         return RESULT_SUCCESS;
2796 }
2797    
2798 static int rtcp_do_debug(int fd, int argc, char *argv[]) {
2799         if (argc != 3) {
2800                 if (argc != 5)
2801                         return RESULT_SHOWUSAGE;
2802                 return rtcp_do_debug_ip(fd, argc, argv);
2803         }
2804         rtcpdebug = 1;
2805         memset(&rtcpdebugaddr,0,sizeof(rtcpdebugaddr));
2806         ast_cli(fd, "RTCP Debugging Enabled\n");
2807         return RESULT_SUCCESS;
2808 }
2809
2810 static int rtcp_do_stats(int fd, int argc, char *argv[]) {
2811         if (argc != 3) {
2812                 return RESULT_SHOWUSAGE;
2813         }
2814         rtcpstats = 1;
2815         ast_cli(fd, "RTCP Stats Enabled\n");
2816         return RESULT_SUCCESS;
2817 }
2818
2819 static int rtp_no_debug(int fd, int argc, char *argv[])
2820 {
2821         if (argc != 3)
2822                 return RESULT_SHOWUSAGE;
2823         rtpdebug = 0;
2824         ast_cli(fd,"RTP Debugging Disabled\n");
2825         return RESULT_SUCCESS;
2826 }
2827
2828 static int rtcp_no_debug(int fd, int argc, char *argv[])
2829 {
2830         if (argc != 4)
2831                 return RESULT_SHOWUSAGE;
2832         rtcpdebug = 0;
2833         ast_cli(fd,"RTCP Debugging Disabled\n");
2834         return RESULT_SUCCESS;
2835 }
2836
2837 static int rtcp_no_stats(int fd, int argc, char *argv[])
2838 {
2839         if (argc != 4)
2840                 return RESULT_SHOWUSAGE;
2841         rtcpstats = 0;
2842         ast_cli(fd,"RTCP Stats Disabled\n");
2843         return RESULT_SUCCESS;
2844 }
2845
2846
2847 static int stun_do_debug(int fd, int argc, char *argv[])
2848 {
2849         if (argc != 2) {
2850                 return RESULT_SHOWUSAGE;
2851         }
2852         stundebug = 1;
2853         ast_cli(fd, "STUN Debugging Enabled\n");
2854         return RESULT_SUCCESS;
2855 }
2856    
2857 static int stun_no_debug(int fd, int argc, char *argv[])
2858 {
2859         if (argc != 3)
2860                 return RESULT_SHOWUSAGE;
2861         stundebug = 0;
2862         ast_cli(fd,"STUN Debugging Disabled\n");
2863         return RESULT_SUCCESS;
2864 }
2865
2866
2867 static char debug_usage[] =
2868   "Usage: rtp debug [ip host[:port]]\n"
2869   "       Enable dumping of all RTP packets to and from host.\n";
2870
2871 static char no_debug_usage[] =
2872   "Usage: rtp no debug\n"
2873   "       Disable all RTP debugging\n";
2874
2875 static char stun_debug_usage[] =
2876   "Usage: stun debug\n"
2877   "       Enable STUN (Simple Traversal of UDP through NATs) debugging\n";
2878
2879 static char stun_no_debug_usage[] =
2880   "Usage: stun no debug\n"
2881   "       Disable STUN debugging\n";
2882
2883
2884 static struct ast_cli_entry  cli_debug_ip =
2885 {{ "rtp", "debug", "ip", NULL } , rtp_do_debug, "Enable RTP debugging on IP", debug_usage };
2886
2887 static struct ast_cli_entry  cli_debug =
2888 {{ "rtp", "debug", NULL } , rtp_do_debug, "Enable RTP debugging", debug_usage };
2889
2890 static struct ast_cli_entry  cli_no_debug =
2891 {{ "rtp", "no", "debug", NULL } , rtp_no_debug, "Disable RTP debugging", no_debug_usage };
2892
2893 static char rtcp_debug_usage[] =
2894   "Usage: rtp rtcp debug [ip host[:port]]\n"
2895   "       Enable dumping of all RTCP packets to and from host.\n";
2896   
2897 static char rtcp_no_debug_usage[] =
2898   "Usage: rtp rtcp no debug\n"
2899   "       Disable all RTCP debugging\n";
2900
2901 static char rtcp_stats_usage[] =
2902   "Usage: rtp rtcp stats\n"
2903   "       Enable dumping of RTCP stats.\n";
2904   
2905 static char rtcp_no_stats_usage[] =
2906   "Usage: rtp rtcp no stats\n"
2907   "       Disable all RTCP stats\n";
2908
2909 static struct ast_cli_entry  cli_debug_ip_rtcp =
2910 {{ "rtp", "rtcp", "debug", "ip", NULL } , rtcp_do_debug, "Enable RTCP debugging on IP", rtcp_debug_usage };
2911
2912 static struct ast_cli_entry  cli_debug_rtcp =
2913 {{ "rtp", "rtcp", "debug", NULL } , rtcp_do_debug, "Enable RTCP debugging", rtcp_debug_usage };
2914
2915 static struct ast_cli_entry  cli_no_debug_rtcp =
2916 {{ "rtp", "rtcp", "no", "debug", NULL } , rtcp_no_debug, "Disable RTCP debugging", rtcp_no_debug_usage };
2917
2918 static struct ast_cli_entry  cli_stats_rtcp =
2919 {{ "rtp", "rtcp", "stats", NULL } , rtcp_do_stats, "Enable RTCP stats", rtcp_stats_usage };
2920
2921 static struct ast_cli_entry  cli_no_stats_rtcp =
2922 {{ "rtp", "rtcp", "no", "stats", NULL } , rtcp_no_stats, "Disable RTCP stats", rtcp_no_stats_usage };
2923
2924 static struct ast_cli_entry  cli_stun_debug =
2925 {{ "stun", "debug", NULL } , stun_do_debug, "Enable STUN debugging", stun_debug_usage };
2926
2927 static struct ast_cli_entry  cli_stun_no_debug =
2928 {{ "stun", "no", "debug", NULL } , stun_no_debug, "Disable STUN debugging", stun_no_debug_usage };
2929
2930 int ast_rtp_reload(void)
2931 {
2932         struct ast_config *cfg;
2933         char *s;
2934
2935         rtpstart = 5000;
2936         rtpend = 31000;
2937         dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2938         cfg = ast_config_load("rtp.conf");
2939         if (cfg) {
2940                 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
2941                         rtpstart = atoi(s);
2942                         if (rtpstart < 1024)
2943                                 rtpstart = 1024;
2944                         if (rtpstart > 65535)
2945                                 rtpstart = 65535;
2946                 }
2947                 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
2948                         rtpend = atoi(s);
2949                         if (rtpend < 1024)
2950                                 rtpend = 1024;
2951                         if (rtpend > 65535)
2952                                 rtpend = 65535;
2953                 }
2954                 if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
2955                         rtcpinterval = atoi(s);
2956                         if (rtcpinterval == 0)
2957                                 rtcpinterval = 0; /* Just so we're clear... it's zero */
2958                         if (rtcpinterval < RTCP_MIN_INTERVALMS)
2959                                 rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
2960                         if (rtcpinterval > RTCP_MAX_INTERVALMS)
2961                                 rtcpinterval = RTCP_MAX_INTERVALMS;
2962                 }
2963                 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
2964 #ifdef SO_NO_CHECK
2965                         if (ast_false(s))
2966                                 nochecksums = 1;
2967                         else
2968                                 nochecksums = 0;
2969 #else
2970                         if (ast_false(s))
2971                                 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
2972 #endif
2973                 }
2974                 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
2975                         dtmftimeout = atoi(s);
2976                         if ((dtmftimeout < 0) || (dtmftimeout > 20000)) {
2977                                 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
2978                                         dtmftimeout, DEFAULT_DTMF_TIMEOUT);
2979                                 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2980                         };
2981                 }
2982                 ast_config_destroy(cfg);
2983         }
2984         if (rtpstart >= rtpend) {
2985                 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
2986                 rtpstart = 5000;
2987                 rtpend = 31000;
2988         }
2989         if (option_verbose > 1)
2990                 ast_verbose(VERBOSE_PREFIX_2 "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
2991         return 0;
2992 }
2993
2994 /*! \brief Initialize the RTP system in Asterisk */
2995 void ast_rtp_init(void)
2996 {
2997         ast_cli_register(&cli_debug);
2998         ast_cli_register(&cli_debug_ip);
2999         ast_cli_register(&cli_no_debug);
3000
3001         ast_cli_register(&cli_debug_rtcp);
3002         ast_cli_register(&cli_debug_ip_rtcp);
3003         ast_cli_register(&cli_no_debug_rtcp);
3004
3005         ast_cli_register(&cli_stats_rtcp);
3006         ast_cli_register(&cli_no_stats_rtcp);
3007         
3008         ast_cli_register(&cli_stun_debug);
3009         ast_cli_register(&cli_stun_no_debug);
3010         ast_rtp_reload();
3011 }
3012