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