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