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