Gracefully handle malformed RTP text packets.
[asterisk/asterisk.git] / res / res_rtp_asterisk.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, 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/stun.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 #include "asterisk/module.h"
51 #include "asterisk/rtp_engine.h"
52
53 #define MAX_TIMESTAMP_SKEW      640
54
55 #define RTP_SEQ_MOD     (1<<16) /*!< A sequence number can't be more than 16 bits */
56 #define RTCP_DEFAULT_INTERVALMS   5000  /*!< Default milli-seconds between RTCP reports we send */
57 #define RTCP_MIN_INTERVALMS       500   /*!< Min milli-seconds between RTCP reports we send */
58 #define RTCP_MAX_INTERVALMS       60000 /*!< Max milli-seconds between RTCP reports we send */
59
60 #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
61 #define DEFAULT_RTP_END 31000  /*!< Default maximum port number to end allocating RTP ports at */
62
63 #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
64 #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
65
66 #define RTCP_PT_FUR     192
67 #define RTCP_PT_SR      200
68 #define RTCP_PT_RR      201
69 #define RTCP_PT_SDES    202
70 #define RTCP_PT_BYE     203
71 #define RTCP_PT_APP     204
72
73 #define RTP_MTU         1200
74
75 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000))      /*!< samples */
76
77 #define ZFONE_PROFILE_ID 0x505a
78
79 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
80
81 static int rtpstart = DEFAULT_RTP_START;                        /*!< First port for RTP sessions (set in rtp.conf) */
82 static int rtpend = DEFAULT_RTP_END;                    /*!< Last port for RTP sessions (set in rtp.conf) */
83 static int rtpdebug;                    /*!< Are we debugging? */
84 static int rtcpdebug;                   /*!< Are we debugging RTCP? */
85 static int rtcpstats;                   /*!< Are we debugging RTCP? */
86 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
87 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
88 static struct sockaddr_in rtcpdebugaddr;        /*!< Debug RTCP packets to/from this host */
89 #ifdef SO_NO_CHECK
90 static int nochecksums;
91 #endif
92 static int strictrtp;
93
94 enum strict_rtp_state {
95         STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
96         STRICT_RTP_LEARN,    /*! Accept next packet as source */
97         STRICT_RTP_CLOSED,   /*! Drop all RTP packets not coming from source that was learned */
98 };
99
100 #define FLAG_3389_WARNING               (1 << 0)
101 #define FLAG_NAT_ACTIVE                 (3 << 1)
102 #define FLAG_NAT_INACTIVE               (0 << 1)
103 #define FLAG_NAT_INACTIVE_NOWARN        (1 << 1)
104 #define FLAG_NEED_MARKER_BIT            (1 << 3)
105 #define FLAG_DTMF_COMPENSATE            (1 << 4)
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         unsigned int dtmf_duration;     /*!< Total duration in samples since the digit start event */
143         unsigned int dtmf_timeout;      /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
144         unsigned int dtmfsamples;
145         /* DTMF Transmission Variables */
146         unsigned int lastdigitts;
147         char sending_digit;     /*!< boolean - are we sending digits */
148         char send_digit;        /*!< digit we are sending */
149         int send_payload;
150         int send_duration;
151         unsigned int flags;
152         struct timeval rxcore;
153         struct timeval txcore;
154         double drxcore;                 /*!< The double representation of the first received packet */
155         struct timeval lastrx;          /*!< timeval when we last received a packet */
156         struct timeval dtmfmute;
157         struct ast_smoother *smoother;
158         int *ioid;
159         unsigned short seqno;           /*!< Sequence number, RFC 3550, page 13. */
160         unsigned short rxseqno;
161         struct sched_context *sched;
162         struct io_context *io;
163         void *data;
164         struct ast_rtcp *rtcp;
165         struct ast_rtp *bridged;        /*!< Who we are Packet bridged to */
166
167         enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
168         struct sockaddr_in strict_rtp_address;  /*!< Remote address information for strict RTP purposes */
169         struct sockaddr_in alt_rtp_address; /*!<Alternate remote address information */
170
171         struct rtp_red *red;
172 };
173
174 /*!
175  * \brief Structure defining an RTCP session.
176  *
177  * The concept "RTCP session" is not defined in RFC 3550, but since
178  * this structure is analogous to ast_rtp, which tracks a RTP session,
179  * it is logical to think of this as a RTCP session.
180  *
181  * RTCP packet is defined on page 9 of RFC 3550.
182  *
183  */
184 struct ast_rtcp {
185         int rtcp_info;
186         int s;                          /*!< Socket */
187         struct sockaddr_in us;          /*!< Socket representation of the local endpoint. */
188         struct sockaddr_in them;        /*!< Socket representation of the remote endpoint. */
189         unsigned int soc;               /*!< What they told us */
190         unsigned int spc;               /*!< What they told us */
191         unsigned int themrxlsr;         /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
192         struct timeval rxlsr;           /*!< Time when we got their last SR */
193         struct timeval txlsr;           /*!< Time when we sent or last SR*/
194         unsigned int expected_prior;    /*!< no. packets in previous interval */
195         unsigned int received_prior;    /*!< no. packets received in previous interval */
196         int schedid;                    /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
197         unsigned int rr_count;          /*!< number of RRs we've sent, not including report blocks in SR's */
198         unsigned int sr_count;          /*!< number of SRs we've sent */
199         unsigned int lastsrtxcount;     /*!< Transmit packet count when last SR sent */
200         double accumulated_transit;     /*!< accumulated a-dlsr-lsr */
201         double rtt;                     /*!< Last reported rtt */
202         unsigned int reported_jitter;   /*!< The contents of their last jitter entry in the RR */
203         unsigned int reported_lost;     /*!< Reported lost packets in their RR */
204
205         double reported_maxjitter;
206         double reported_minjitter;
207         double reported_normdev_jitter;
208         double reported_stdev_jitter;
209         unsigned int reported_jitter_count;
210
211         double reported_maxlost;
212         double reported_minlost;
213         double reported_normdev_lost;
214         double reported_stdev_lost;
215
216         double rxlost;
217         double maxrxlost;
218         double minrxlost;
219         double normdev_rxlost;
220         double stdev_rxlost;
221         unsigned int rxlost_count;
222
223         double maxrxjitter;
224         double minrxjitter;
225         double normdev_rxjitter;
226         double stdev_rxjitter;
227         unsigned int rxjitter_count;
228         double maxrtt;
229         double minrtt;
230         double normdevrtt;
231         double stdevrtt;
232         unsigned int rtt_count;
233 };
234
235 struct rtp_red {
236         struct ast_frame t140;  /*!< Primary data  */
237         struct ast_frame t140red;   /*!< Redundant t140*/
238         unsigned char pt[AST_RED_MAX_GENERATION];  /*!< Payload types for redundancy data */
239         unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
240         unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
241         int num_gen; /*!< Number of generations */
242         int schedid; /*!< Timer id */
243         int ti; /*!< How long to buffer data before send */
244         unsigned char t140red_data[64000];
245         unsigned char buf_data[64000]; /*!< buffered primary data */
246         int hdrlen;
247         long int prev_ts;
248 };
249
250 /* Forward Declarations */
251 static int ast_rtp_new(struct ast_rtp_instance *instance, struct sched_context *sched, struct sockaddr_in *sin, void *data);
252 static int ast_rtp_destroy(struct ast_rtp_instance *instance);
253 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
254 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
255 static void ast_rtp_new_source(struct ast_rtp_instance *instance);
256 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
257 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
258 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
259 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
260 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct sockaddr_in *sin);
261 static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct sockaddr_in *sin);
262 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
263 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
264 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
265 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
266 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
267 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct sockaddr_in *suggestion, const char *username);
268 static void ast_rtp_stop(struct ast_rtp_instance *instance);
269
270 /* RTP Engine Declaration */
271 static struct ast_rtp_engine asterisk_rtp_engine = {
272         .name = "asterisk",
273         .new = ast_rtp_new,
274         .destroy = ast_rtp_destroy,
275         .dtmf_begin = ast_rtp_dtmf_begin,
276         .dtmf_end = ast_rtp_dtmf_end,
277         .new_source = ast_rtp_new_source,
278         .write = ast_rtp_write,
279         .read = ast_rtp_read,
280         .prop_set = ast_rtp_prop_set,
281         .fd = ast_rtp_fd,
282         .remote_address_set = ast_rtp_remote_address_set,
283         .alt_remote_address_set = ast_rtp_alt_remote_address_set,
284         .red_init = rtp_red_init,
285         .red_buffer = rtp_red_buffer,
286         .local_bridge = ast_rtp_local_bridge,
287         .get_stat = ast_rtp_get_stat,
288         .dtmf_compatible = ast_rtp_dtmf_compatible,
289         .stun_request = ast_rtp_stun_request,
290         .stop = ast_rtp_stop,
291 };
292
293 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
294 {
295         if (!rtpdebug) {
296                 return 0;
297         }
298
299         if (rtpdebugaddr.sin_addr.s_addr) {
300                 if (((ntohs(rtpdebugaddr.sin_port) != 0)
301                      && (rtpdebugaddr.sin_port != addr->sin_port))
302                     || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
303                         return 0;
304         }
305
306         return 1;
307 }
308
309 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
310 {
311         if (!rtcpdebug) {
312                 return 0;
313         }
314
315         if (rtcpdebugaddr.sin_addr.s_addr) {
316                 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
317                      && (rtcpdebugaddr.sin_port != addr->sin_port))
318                     || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
319                         return 0;
320         }
321
322         return 1;
323 }
324
325 static int rtp_get_rate(int subclass)
326 {
327         return (subclass == AST_FORMAT_G722) ? 8000 : ast_format_rate(subclass);
328 }
329
330 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
331 {
332         unsigned int interval;
333         /*! \todo XXX Do a more reasonable calculation on this one
334          * Look in RFC 3550 Section A.7 for an example*/
335         interval = rtcpinterval;
336         return interval;
337 }
338
339 /*! \brief Calculate normal deviation */
340 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
341 {
342         normdev = normdev * sample_count + sample;
343         sample_count++;
344
345         return normdev / sample_count;
346 }
347
348 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
349 {
350 /*
351                 for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
352                 return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
353                 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
354                 optimized formula
355 */
356 #define SQUARE(x) ((x) * (x))
357
358         stddev = sample_count * stddev;
359         sample_count++;
360
361         return stddev +
362                 ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
363                 ( SQUARE(sample - normdev_curent) / sample_count );
364
365 #undef SQUARE
366 }
367
368 static int create_new_socket(const char *type)
369 {
370         int sock = socket(AF_INET, SOCK_DGRAM, 0);
371
372         if (sock < 0) {
373                 if (!type) {
374                         type = "RTP/RTCP";
375                 }
376                 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
377         } else {
378                 long flags = fcntl(sock, F_GETFL);
379                 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
380 #ifdef SO_NO_CHECK
381                 if (nochecksums) {
382                         setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
383                 }
384 #endif
385         }
386
387         return sock;
388 }
389
390 static int ast_rtp_new(struct ast_rtp_instance *instance, struct sched_context *sched, struct sockaddr_in *sin, void *data)
391 {
392         struct ast_rtp *rtp = NULL;
393         int x, startplace;
394
395         /* Create a new RTP structure to hold all of our data */
396         if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
397                 return -1;
398         }
399
400         /* Set default parameters on the newly created RTP structure */
401         rtp->ssrc = ast_random();
402         rtp->seqno = ast_random() & 0xffff;
403         rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
404
405         /* Create a new socket for us to listen on and use */
406         if ((rtp->s = create_new_socket("RTP")) < 0) {
407                 ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
408                 ast_free(rtp);
409                 return -1;
410         }
411
412         /* Now actually find a free RTP port to use */
413         x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
414         x = x & ~1;
415         startplace = x;
416
417         for (;;) {
418                 sin->sin_port = htons(x);
419                 /* Try to bind, this will tell us whether the port is available or not */
420                 if (!bind(rtp->s, (struct sockaddr *)sin, sizeof(*sin))) {
421                         ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
422                         ast_rtp_instance_set_local_address(instance, sin);
423                         break;
424                 }
425
426                 x += 2;
427                 if (x > rtpend) {
428                         x = (rtpstart + 1) & ~1;
429                 }
430
431                 /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
432                 if (x == startplace || errno != EADDRINUSE) {
433                         ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
434                         return -1;
435                 }
436         }
437
438         /* Record any information we may need */
439         rtp->sched = sched;
440
441         /* Associate the RTP structure with the RTP instance and be done */
442         ast_rtp_instance_set_data(instance, rtp);
443
444         return 0;
445 }
446
447 static int ast_rtp_destroy(struct ast_rtp_instance *instance)
448 {
449         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
450
451         /* Destroy the smoother that was smoothing out audio if present */
452         if (rtp->smoother) {
453                 ast_smoother_free(rtp->smoother);
454         }
455
456         /* Close our own socket so we no longer get packets */
457         if (rtp->s > -1) {
458                 close(rtp->s);
459         }
460
461         /* Destroy RTCP if it was being used */
462         if (rtp->rtcp) {
463                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
464                 close(rtp->rtcp->s);
465                 ast_free(rtp->rtcp);
466         }
467
468         /* Destroy RED if it was being used */
469         if (rtp->red) {
470                 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
471                 ast_free(rtp->red);
472         }
473
474         /* Finally destroy ourselves */
475         ast_free(rtp);
476
477         return 0;
478 }
479
480 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
481 {
482         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
483         struct sockaddr_in remote_address = { 0, };
484         int hdrlen = 12, res = 0, i = 0, payload = 101;
485         char data[256];
486         unsigned int *rtpheader = (unsigned int*)data;
487
488         ast_rtp_instance_get_remote_address(instance, &remote_address);
489
490         /* If we have no remote address information bail out now */
491         if (!remote_address.sin_addr.s_addr || !remote_address.sin_port) {
492                 return -1;
493         }
494
495         /* Convert given digit into what we want to transmit */
496         if ((digit <= '9') && (digit >= '0')) {
497                 digit -= '0';
498         } else if (digit == '*') {
499                 digit = 10;
500         } else if (digit == '#') {
501                 digit = 11;
502         } else if ((digit >= 'A') && (digit <= 'D')) {
503                 digit = digit - 'A' + 12;
504         } else if ((digit >= 'a') && (digit <= 'd')) {
505                 digit = digit - 'a' + 12;
506         } else {
507                 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
508                 return -1;
509         }
510
511         /* Grab the payload that they expect the RFC2833 packet to be received in */
512         payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, AST_RTP_DTMF);
513
514         rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
515         rtp->send_duration = 160;
516         rtp->lastdigitts = rtp->lastts + rtp->send_duration;
517
518         /* Create the actual packet that we will be sending */
519         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
520         rtpheader[1] = htonl(rtp->lastdigitts);
521         rtpheader[2] = htonl(rtp->ssrc);
522
523         /* Actually send the packet */
524         for (i = 0; i < 2; i++) {
525                 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
526                 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &remote_address, sizeof(remote_address));
527                 if (res < 0) {
528                         ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
529                                 ast_inet_ntoa(remote_address.sin_addr), ntohs(remote_address.sin_port), strerror(errno));
530                 }
531                 if (rtp_debug_test_addr(&remote_address)) {
532                         ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
533                                     ast_inet_ntoa(remote_address.sin_addr),
534                                     ntohs(remote_address.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
535                 }
536                 rtp->seqno++;
537                 rtp->send_duration += 160;
538                 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
539         }
540
541         /* Record that we are in the process of sending a digit and information needed to continue doing so */
542         rtp->sending_digit = 1;
543         rtp->send_digit = digit;
544         rtp->send_payload = payload;
545
546         return 0;
547 }
548
549 static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
550 {
551         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
552         struct sockaddr_in remote_address = { 0, };
553         int hdrlen = 12, res = 0;
554         char data[256];
555         unsigned int *rtpheader = (unsigned int*)data;
556
557         ast_rtp_instance_get_remote_address(instance, &remote_address);
558
559         /* Make sure we know where the other side is so we can send them the packet */
560         if (!remote_address.sin_addr.s_addr || !remote_address.sin_port) {
561                 return -1;
562         }
563
564         /* Actually create the packet we will be sending */
565         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
566         rtpheader[1] = htonl(rtp->lastdigitts);
567         rtpheader[2] = htonl(rtp->ssrc);
568         rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
569         rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
570
571         /* Boom, send it on out */
572         res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &remote_address, sizeof(remote_address));
573         if (res < 0) {
574                 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
575                         ast_inet_ntoa(remote_address.sin_addr),
576                         ntohs(remote_address.sin_port), strerror(errno));
577         }
578
579         if (rtp_debug_test_addr(&remote_address)) {
580                 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
581                             ast_inet_ntoa(remote_address.sin_addr),
582                             ntohs(remote_address.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
583         }
584
585         /* And now we increment some values for the next time we swing by */
586         rtp->seqno++;
587         rtp->send_duration += 160;
588
589         return 0;
590 }
591
592 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
593 {
594         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
595         struct sockaddr_in remote_address = { 0, };
596         int hdrlen = 12, res = 0, i = 0;
597         char data[256];
598         unsigned int *rtpheader = (unsigned int*)data;
599
600         ast_rtp_instance_get_remote_address(instance, &remote_address);
601
602         /* Make sure we know where the remote side is so we can send them the packet we construct */
603         if (!remote_address.sin_addr.s_addr || !remote_address.sin_port) {
604                 return -1;
605         }
606
607         /* Convert the given digit to the one we are going to send */
608         if ((digit <= '9') && (digit >= '0')) {
609                 digit -= '0';
610         } else if (digit == '*') {
611                 digit = 10;
612         } else if (digit == '#') {
613                 digit = 11;
614         } else if ((digit >= 'A') && (digit <= 'D')) {
615                 digit = digit - 'A' + 12;
616         } else if ((digit >= 'a') && (digit <= 'd')) {
617                 digit = digit - 'a' + 12;
618         } else {
619                 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
620                 return -1;
621         }
622
623         rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
624
625         /* Construct the packet we are going to send */
626         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
627         rtpheader[1] = htonl(rtp->lastdigitts);
628         rtpheader[2] = htonl(rtp->ssrc);
629         rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
630         rtpheader[3] |= htonl((1 << 23));
631         rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
632
633         /* Send it 3 times, that's the magical number */
634         for (i = 0; i < 3; i++) {
635                 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &remote_address, sizeof(remote_address));
636                 if (res < 0) {
637                         ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
638                                 ast_inet_ntoa(remote_address.sin_addr),
639                                 ntohs(remote_address.sin_port), strerror(errno));
640                 }
641                 if (rtp_debug_test_addr(&remote_address)) {
642                         ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
643                                     ast_inet_ntoa(remote_address.sin_addr),
644                                     ntohs(remote_address.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
645                 }
646         }
647
648         /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
649         rtp->lastts += rtp->send_duration;
650         rtp->sending_digit = 0;
651         rtp->send_digit = 0;
652
653         return 0;
654 }
655
656 static void ast_rtp_new_source(struct ast_rtp_instance *instance)
657 {
658         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
659
660         /* We simply set this bit so that the next packet sent will have the marker bit turned on */
661         ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
662
663         return;
664 }
665
666 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
667 {
668         struct timeval t;
669         long ms;
670
671         if (ast_tvzero(rtp->txcore)) {
672                 rtp->txcore = ast_tvnow();
673                 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
674         }
675
676         t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
677         if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
678                 ms = 0;
679         }
680         rtp->txcore = t;
681
682         return (unsigned int) ms;
683 }
684
685 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
686 {
687         unsigned int sec, usec, frac;
688         sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
689         usec = tv.tv_usec;
690         frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
691         *msw = sec;
692         *lsw = frac;
693 }
694
695 /*! \brief Send RTCP recipient's report */
696 static int ast_rtcp_write_rr(const void *data)
697 {
698         struct ast_rtp *rtp = (struct ast_rtp *)data;
699         int res;
700         int len = 32;
701         unsigned int lost;
702         unsigned int extended;
703         unsigned int expected;
704         unsigned int expected_interval;
705         unsigned int received_interval;
706         int lost_interval;
707         struct timeval now;
708         unsigned int *rtcpheader;
709         char bdata[1024];
710         struct timeval dlsr;
711         int fraction;
712
713         double rxlost_current;
714
715         if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
716                 return 0;
717
718         if (!rtp->rtcp->them.sin_addr.s_addr) {
719                 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
720                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
721                 return 0;
722         }
723
724         extended = rtp->cycles + rtp->lastrxseqno;
725         expected = extended - rtp->seedrxseqno + 1;
726         lost = expected - rtp->rxcount;
727         expected_interval = expected - rtp->rtcp->expected_prior;
728         rtp->rtcp->expected_prior = expected;
729         received_interval = rtp->rxcount - rtp->rtcp->received_prior;
730         rtp->rtcp->received_prior = rtp->rxcount;
731         lost_interval = expected_interval - received_interval;
732
733         if (lost_interval <= 0)
734                 rtp->rtcp->rxlost = 0;
735         else rtp->rtcp->rxlost = rtp->rtcp->rxlost;
736         if (rtp->rtcp->rxlost_count == 0)
737                 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
738         if (lost_interval < rtp->rtcp->minrxlost)
739                 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
740         if (lost_interval > rtp->rtcp->maxrxlost)
741                 rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
742
743         rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->rxlost_count);
744         rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->normdev_rxlost, rxlost_current, rtp->rtcp->rxlost_count);
745         rtp->rtcp->normdev_rxlost = rxlost_current;
746         rtp->rtcp->rxlost_count++;
747
748         if (expected_interval == 0 || lost_interval <= 0)
749                 fraction = 0;
750         else
751                 fraction = (lost_interval << 8) / expected_interval;
752         gettimeofday(&now, NULL);
753         timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
754         rtcpheader = (unsigned int *)bdata;
755         rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
756         rtcpheader[1] = htonl(rtp->ssrc);
757         rtcpheader[2] = htonl(rtp->themssrc);
758         rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
759         rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
760         rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
761         rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
762         rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
763
764         /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
765           it can change mid call, and SDES can't) */
766         rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
767         rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
768         rtcpheader[(len/4)+2] = htonl(0x01 << 24);              /* Empty for the moment */
769         len += 12;
770
771         res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
772
773         if (res < 0) {
774                 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
775                 /* Remove the scheduler */
776                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
777                 return 0;
778         }
779
780         rtp->rtcp->rr_count++;
781         if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
782                 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
783                         "  Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
784                         "  IA jitter: %.4f\n"
785                         "  Their last SR: %u\n"
786                             "  DLSR: %4.4f (sec)\n\n",
787                             ast_inet_ntoa(rtp->rtcp->them.sin_addr),
788                             ntohs(rtp->rtcp->them.sin_port),
789                             rtp->ssrc, rtp->themssrc, fraction, lost,
790                             rtp->rxjitter,
791                             rtp->rtcp->themrxlsr,
792                             (double)(ntohl(rtcpheader[7])/65536.0));
793         }
794
795         return res;
796 }
797
798 /*! \brief Send RTCP sender's report */
799 static int ast_rtcp_write_sr(const void *data)
800 {
801         struct ast_rtp *rtp = (struct ast_rtp *)data;
802         int res;
803         int len = 0;
804         struct timeval now;
805         unsigned int now_lsw;
806         unsigned int now_msw;
807         unsigned int *rtcpheader;
808         unsigned int lost;
809         unsigned int extended;
810         unsigned int expected;
811         unsigned int expected_interval;
812         unsigned int received_interval;
813         int lost_interval;
814         int fraction;
815         struct timeval dlsr;
816         char bdata[512];
817
818         /* Commented condition is always not NULL if rtp->rtcp is not NULL */
819         if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
820                 return 0;
821
822         if (!rtp->rtcp->them.sin_addr.s_addr) {  /* This'll stop rtcp for this rtp session */
823                 ast_verbose("RTCP SR transmission error, rtcp halted\n");
824                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
825                 return 0;
826         }
827
828         gettimeofday(&now, NULL);
829         timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
830         rtcpheader = (unsigned int *)bdata;
831         rtcpheader[1] = htonl(rtp->ssrc);               /* Our SSRC */
832         rtcpheader[2] = htonl(now_msw);                 /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
833         rtcpheader[3] = htonl(now_lsw);                 /* now, LSW */
834         rtcpheader[4] = htonl(rtp->lastts);             /* FIXME shouldn't be that, it should be now */
835         rtcpheader[5] = htonl(rtp->txcount);            /* No. packets sent */
836         rtcpheader[6] = htonl(rtp->txoctetcount);       /* No. bytes sent */
837         len += 28;
838
839         extended = rtp->cycles + rtp->lastrxseqno;
840         expected = extended - rtp->seedrxseqno + 1;
841         if (rtp->rxcount > expected)
842                 expected += rtp->rxcount - expected;
843         lost = expected - rtp->rxcount;
844         expected_interval = expected - rtp->rtcp->expected_prior;
845         rtp->rtcp->expected_prior = expected;
846         received_interval = rtp->rxcount - rtp->rtcp->received_prior;
847         rtp->rtcp->received_prior = rtp->rxcount;
848         lost_interval = expected_interval - received_interval;
849         if (expected_interval == 0 || lost_interval <= 0)
850                 fraction = 0;
851         else
852                 fraction = (lost_interval << 8) / expected_interval;
853         timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
854         rtcpheader[7] = htonl(rtp->themssrc);
855         rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
856         rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
857         rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
858         rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
859         rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
860         len += 24;
861
862         rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
863
864         /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
865         /* it can change mid call, and SDES can't) */
866         rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
867         rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
868         rtcpheader[(len/4)+2] = htonl(0x01 << 24);                    /* Empty for the moment */
869         len += 12;
870
871         res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
872         if (res < 0) {
873                 ast_log(LOG_ERROR, "RTCP SR transmission error to %s:%d, rtcp halted %s\n",ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port), strerror(errno));
874                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
875                 return 0;
876         }
877
878         /* FIXME Don't need to get a new one */
879         gettimeofday(&rtp->rtcp->txlsr, NULL);
880         rtp->rtcp->sr_count++;
881
882         rtp->rtcp->lastsrtxcount = rtp->txcount;
883
884         if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
885                 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
886                 ast_verbose("  Our SSRC: %u\n", rtp->ssrc);
887                 ast_verbose("  Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
888                 ast_verbose("  Sent(RTP): %u\n", rtp->lastts);
889                 ast_verbose("  Sent packets: %u\n", rtp->txcount);
890                 ast_verbose("  Sent octets: %u\n", rtp->txoctetcount);
891                 ast_verbose("  Report block:\n");
892                 ast_verbose("  Fraction lost: %u\n", fraction);
893                 ast_verbose("  Cumulative loss: %u\n", lost);
894                 ast_verbose("  IA jitter: %.4f\n", rtp->rxjitter);
895                 ast_verbose("  Their last SR: %u\n", rtp->rtcp->themrxlsr);
896                 ast_verbose("  DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
897         }
898         manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To %s:%d\r\n"
899                                             "OurSSRC: %u\r\n"
900                                             "SentNTP: %u.%010u\r\n"
901                                             "SentRTP: %u\r\n"
902                                             "SentPackets: %u\r\n"
903                                             "SentOctets: %u\r\n"
904                                             "ReportBlock:\r\n"
905                                             "FractionLost: %u\r\n"
906                                             "CumulativeLoss: %u\r\n"
907                                             "IAJitter: %.4f\r\n"
908                                             "TheirLastSR: %u\r\n"
909                       "DLSR: %4.4f (sec)\r\n",
910                       ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port),
911                       rtp->ssrc,
912                       (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
913                       rtp->lastts,
914                       rtp->txcount,
915                       rtp->txoctetcount,
916                       fraction,
917                       lost,
918                       rtp->rxjitter,
919                       rtp->rtcp->themrxlsr,
920                       (double)(ntohl(rtcpheader[12])/65536.0));
921         return res;
922 }
923
924 /*! \brief Write and RTCP packet to the far end
925  * \note Decide if we are going to send an SR (with Reception Block) or RR
926  * RR is sent if we have not sent any rtp packets in the previous interval */
927 static int ast_rtcp_write(const void *data)
928 {
929         struct ast_rtp *rtp = (struct ast_rtp *)data;
930         int res;
931
932         if (!rtp || !rtp->rtcp)
933                 return 0;
934
935         if (rtp->txcount > rtp->rtcp->lastsrtxcount)
936                 res = ast_rtcp_write_sr(data);
937         else
938                 res = ast_rtcp_write_rr(data);
939
940         return res;
941 }
942
943 static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
944 {
945         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
946         int pred, mark = 0;
947         unsigned int ms = calc_txstamp(rtp, &frame->delivery);
948         struct sockaddr_in remote_address = { 0, };
949         int rate = rtp_get_rate(frame->subclass) / 1000;
950
951         if (frame->subclass == AST_FORMAT_G722) {
952                 frame->samples /= 2;
953         }
954
955         if (rtp->sending_digit) {
956                 return 0;
957         }
958
959         if (frame->frametype == AST_FRAME_VOICE) {
960                 pred = rtp->lastts + frame->samples;
961
962                 /* Re-calculate last TS */
963                 rtp->lastts = rtp->lastts + ms * rate;
964                 if (ast_tvzero(frame->delivery)) {
965                         /* If this isn't an absolute delivery time, Check if it is close to our prediction,
966                            and if so, go with our prediction */
967                         if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
968                                 rtp->lastts = pred;
969                         } else {
970                                 ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
971                                 mark = 1;
972                         }
973                 }
974         } else if (frame->frametype == AST_FRAME_VIDEO) {
975                 mark = frame->subclass & 0x1;
976                 pred = rtp->lastovidtimestamp + frame->samples;
977                 /* Re-calculate last TS */
978                 rtp->lastts = rtp->lastts + ms * 90;
979                 /* If it's close to our prediction, go for it */
980                 if (ast_tvzero(frame->delivery)) {
981                         if (abs(rtp->lastts - pred) < 7200) {
982                                 rtp->lastts = pred;
983                                 rtp->lastovidtimestamp += frame->samples;
984                         } else {
985                                 ast_debug(3, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
986                                 rtp->lastovidtimestamp = rtp->lastts;
987                         }
988                 }
989         } else {
990                 pred = rtp->lastotexttimestamp + frame->samples;
991                 /* Re-calculate last TS */
992                 rtp->lastts = rtp->lastts + ms;
993                 /* If it's close to our prediction, go for it */
994                 if (ast_tvzero(frame->delivery)) {
995                         if (abs(rtp->lastts - pred) < 7200) {
996                                 rtp->lastts = pred;
997                                 rtp->lastotexttimestamp += frame->samples;
998                         } else {
999                                 ast_debug(3, "Difference is %d, ms is %d, pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
1000                                 rtp->lastotexttimestamp = rtp->lastts;
1001                         }
1002                 }
1003         }
1004
1005         /* If we have been explicitly told to set the marker bit then do so */
1006         if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
1007                 mark = 1;
1008                 ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
1009         }
1010
1011         /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
1012         if (rtp->lastts > rtp->lastdigitts) {
1013                 rtp->lastdigitts = rtp->lastts;
1014         }
1015
1016         if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
1017                 rtp->lastts = frame->ts * rate;
1018         }
1019
1020         ast_rtp_instance_get_remote_address(instance, &remote_address);
1021
1022         /* If we know the remote address construct a packet and send it out */
1023         if (remote_address.sin_port && remote_address.sin_addr.s_addr) {
1024                 int hdrlen = 12, res;
1025                 unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
1026
1027                 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
1028                 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
1029                 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
1030
1031                 if ((res = sendto(rtp->s, (void *)rtpheader, frame->datalen + hdrlen, 0, (struct sockaddr *)&remote_address, sizeof(remote_address))) < 0) {
1032                         if (!ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1033                                 ast_debug(1, "RTP Transmission error of packet %d to %s:%d: %s\n", rtp->seqno, ast_inet_ntoa(remote_address.sin_addr), ntohs(remote_address.sin_port), strerror(errno));
1034                         } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
1035                                 /* Only give this error message once if we are not RTP debugging */
1036                                 if (option_debug || rtpdebug)
1037                                         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(remote_address.sin_addr), ntohs(remote_address.sin_port));
1038                                 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
1039                         }
1040                 } else {
1041                         rtp->txcount++;
1042                         rtp->txoctetcount += (res - hdrlen);
1043
1044                         if (rtp->rtcp && rtp->rtcp->schedid < 1) {
1045                                 ast_debug(1, "Starting RTCP transmission on RTP instance '%p'\n", instance);
1046                                 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1047                         }
1048                 }
1049
1050                 if (rtp_debug_test_addr(&remote_address)) {
1051                         ast_verbose("Sent RTP packet to      %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1052                                     ast_inet_ntoa(remote_address.sin_addr), ntohs(remote_address.sin_port), codec, rtp->seqno, rtp->lastts, res - hdrlen);
1053                 }
1054         }
1055
1056         rtp->seqno++;
1057
1058         return 0;
1059 }
1060
1061 static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
1062         unsigned char *data = red->t140red.data.ptr;
1063         int len = 0;
1064         int i;
1065
1066         /* replace most aged generation */
1067         if (red->len[0]) {
1068                 for (i = 1; i < red->num_gen+1; i++)
1069                         len += red->len[i];
1070
1071                 memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
1072         }
1073
1074         /* Store length of each generation and primary data length*/
1075         for (i = 0; i < red->num_gen; i++)
1076                 red->len[i] = red->len[i+1];
1077         red->len[i] = red->t140.datalen;
1078
1079         /* write each generation length in red header */
1080         len = red->hdrlen;
1081         for (i = 0; i < red->num_gen; i++)
1082                 len += data[i*4+3] = red->len[i];
1083
1084         /* add primary data to buffer */
1085         memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
1086         red->t140red.datalen = len + red->t140.datalen;
1087
1088         /* no primary data and no generations to send */
1089         if (len == red->hdrlen && !red->t140.datalen)
1090                 return NULL;
1091
1092         /* reset t.140 buffer */
1093         red->t140.datalen = 0;
1094
1095         return &red->t140red;
1096 }
1097
1098 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
1099 {
1100         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1101         struct sockaddr_in remote_address = { 0, };
1102         int codec, subclass;
1103
1104         ast_rtp_instance_get_remote_address(instance, &remote_address);
1105
1106         /* If we don't actually know the remote address don't even bother doing anything */
1107         if (!remote_address.sin_addr.s_addr) {
1108                 ast_debug(1, "No remote address on RTP instance '%p' so dropping frame\n", instance);
1109                 return 0;
1110         }
1111
1112         /* If there is no data length we can't very well send the packet */
1113         if (!frame->datalen) {
1114                 ast_debug(1, "Received frame with no data for RTP instance '%p' so dropping frame\n", instance);
1115                 return 0;
1116         }
1117
1118         /* If the packet is not one our RTP stack supports bail out */
1119         if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
1120                 ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
1121                 return -1;
1122         }
1123
1124         if (rtp->red) {
1125                 /* return 0; */
1126                 /* no primary data or generations to send */
1127                 if ((frame = red_t140_to_red(rtp->red)) == NULL)
1128                         return 0;
1129         }
1130
1131         /* Grab the subclass and look up the payload we are going to use */
1132         subclass = frame->subclass;
1133         if (frame->frametype == AST_FRAME_VIDEO) {
1134                 subclass &= ~0x1;
1135         }
1136         if ((codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 1, subclass)) < 0) {
1137                 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(frame->subclass));
1138                 return -1;
1139         }
1140
1141         /* Oh dear, if the format changed we will have to set up a new smoother */
1142         if (rtp->lasttxformat != subclass) {
1143                 ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
1144                 rtp->lasttxformat = subclass;
1145                 if (rtp->smoother) {
1146                         ast_smoother_free(rtp->smoother);
1147                         rtp->smoother = NULL;
1148                 }
1149         }
1150
1151         /* If no smoother is present see if we have to set one up */
1152         if (!rtp->smoother) {
1153                 struct ast_format_list fmt = ast_codec_pref_getsize(&ast_rtp_instance_get_codecs(instance)->pref, subclass);
1154
1155                 switch (subclass) {
1156                 case AST_FORMAT_SPEEX:
1157                 case AST_FORMAT_G723_1:
1158                 case AST_FORMAT_SIREN7:
1159                 case AST_FORMAT_SIREN14:
1160                         /* these are all frame-based codecs and cannot be safely run through
1161                            a smoother */
1162                         break;
1163                 default:
1164                         if (fmt.inc_ms) {
1165                                 if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
1166                                         ast_log(LOG_WARNING, "Unable to create smoother: format %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
1167                                         return -1;
1168                                 }
1169                                 if (fmt.flags) {
1170                                         ast_smoother_set_flags(rtp->smoother, fmt.flags);
1171                                 }
1172                                 ast_debug(1, "Created smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
1173                         }
1174                 }
1175         }
1176
1177         /* Feed audio frames into the actual function that will create a frame and send it */
1178         if (rtp->smoother) {
1179                 struct ast_frame *f;
1180
1181                 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
1182                         ast_smoother_feed_be(rtp->smoother, frame);
1183                 } else {
1184                         ast_smoother_feed(rtp->smoother, frame);
1185                 }
1186
1187                 while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
1188                                 ast_rtp_raw_write(instance, f, codec);
1189                 }
1190         } else {
1191                 int hdrlen = 12;
1192                 struct ast_frame *f = NULL;
1193
1194                 if (frame->offset < hdrlen) {
1195                         f = ast_frdup(frame);
1196                 } else {
1197                         f = frame;
1198                 }
1199                 if (f->data.ptr) {
1200                         ast_rtp_raw_write(instance, f, codec);
1201                 }
1202                 if (f != frame) {
1203                         ast_frfree(f);
1204                 }
1205
1206         }
1207
1208         return 0;
1209 }
1210
1211 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
1212 {
1213         struct timeval now;
1214         double transit;
1215         double current_time;
1216         double d;
1217         double dtv;
1218         double prog;
1219         int rate = rtp_get_rate(rtp->f.subclass);
1220
1221         double normdev_rxjitter_current;
1222         if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
1223                 gettimeofday(&rtp->rxcore, NULL);
1224                 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
1225                 /* map timestamp to a real time */
1226                 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
1227                 rtp->rxcore.tv_sec -= timestamp / rate;
1228                 rtp->rxcore.tv_usec -= (timestamp % rate) * 125;
1229                 /* Round to 0.1ms for nice, pretty timestamps */
1230                 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
1231                 if (rtp->rxcore.tv_usec < 0) {
1232                         /* Adjust appropriately if necessary */
1233                         rtp->rxcore.tv_usec += 1000000;
1234                         rtp->rxcore.tv_sec -= 1;
1235                 }
1236         }
1237
1238         gettimeofday(&now,NULL);
1239         /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
1240         tv->tv_sec = rtp->rxcore.tv_sec + timestamp / rate;
1241         tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % rate) * 125;
1242         if (tv->tv_usec >= 1000000) {
1243                 tv->tv_usec -= 1000000;
1244                 tv->tv_sec += 1;
1245         }
1246         prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
1247         dtv = (double)rtp->drxcore + (double)(prog);
1248         current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
1249         transit = current_time - dtv;
1250         d = transit - rtp->rxtransit;
1251         rtp->rxtransit = transit;
1252         if (d<0)
1253                 d=-d;
1254         rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1255
1256         if (rtp->rtcp) {
1257                 if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
1258                         rtp->rtcp->maxrxjitter = rtp->rxjitter;
1259                 if (rtp->rtcp->rxjitter_count == 1)
1260                         rtp->rtcp->minrxjitter = rtp->rxjitter;
1261                 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1262                         rtp->rtcp->minrxjitter = rtp->rxjitter;
1263
1264                 normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
1265                 rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
1266
1267                 rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
1268                 rtp->rtcp->rxjitter_count++;
1269         }
1270 }
1271
1272 static struct ast_frame *send_dtmf(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
1273 {
1274         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1275         struct sockaddr_in remote_address = { 0, };
1276
1277         ast_rtp_instance_get_remote_address(instance, &remote_address);
1278
1279         if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
1280                 ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(remote_address.sin_addr));
1281                 rtp->resp = 0;
1282                 rtp->dtmfsamples = 0;
1283                 return &ast_null_frame;
1284         }
1285         ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(remote_address.sin_addr));
1286         if (rtp->resp == 'X') {
1287                 rtp->f.frametype = AST_FRAME_CONTROL;
1288                 rtp->f.subclass = AST_CONTROL_FLASH;
1289         } else {
1290                 rtp->f.frametype = type;
1291                 rtp->f.subclass = rtp->resp;
1292         }
1293         rtp->f.datalen = 0;
1294         rtp->f.samples = 0;
1295         rtp->f.mallocd = 0;
1296         rtp->f.src = "RTP";
1297
1298         return &rtp->f;
1299 }
1300
1301 static struct ast_frame *process_dtmf_rfc2833(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct sockaddr_in *sin, int payloadtype, int mark)
1302 {
1303         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1304         struct sockaddr_in remote_address = { 0, };
1305         unsigned int event, event_end, samples;
1306         char resp = 0;
1307         struct ast_frame *f = NULL;
1308
1309         ast_rtp_instance_get_remote_address(instance, &remote_address);
1310
1311         /* Figure out event, event end, and samples */
1312         event = ntohl(*((unsigned int *)(data)));
1313         event >>= 24;
1314         event_end = ntohl(*((unsigned int *)(data)));
1315         event_end <<= 8;
1316         event_end >>= 24;
1317         samples = ntohl(*((unsigned int *)(data)));
1318         samples &= 0xFFFF;
1319
1320         if (rtp_debug_test_addr(&remote_address)) {
1321                 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(remote_address.sin_addr),
1322                             ntohs(remote_address.sin_port), payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
1323         }
1324
1325         /* Print out debug if turned on */
1326         if (rtpdebug || option_debug > 2)
1327                 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
1328
1329         /* Figure out what digit was pressed */
1330         if (event < 10) {
1331                 resp = '0' + event;
1332         } else if (event < 11) {
1333                 resp = '*';
1334         } else if (event < 12) {
1335                 resp = '#';
1336         } else if (event < 16) {
1337                 resp = 'A' + (event - 12);
1338         } else if (event < 17) {        /* Event 16: Hook flash */
1339                 resp = 'X';
1340         } else {
1341                 /* Not a supported event */
1342                 ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
1343                 return &ast_null_frame;
1344         }
1345
1346         if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
1347                 if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
1348                         rtp->resp = resp;
1349                         rtp->dtmf_timeout = 0;
1350                         f = send_dtmf(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE));
1351                         f->len = 0;
1352                         rtp->lastevent = timestamp;
1353                 }
1354         } else {
1355                 /*  The duration parameter measures the complete
1356                     duration of the event (from the beginning) - RFC2833.
1357                     Account for the fact that duration is only 16 bits long
1358                     (about 8 seconds at 8000 Hz) and can wrap is digit
1359                     is hold for too long. */
1360                 unsigned int new_duration = rtp->dtmf_duration;
1361                 unsigned int last_duration = new_duration & 0xFFFF;
1362
1363                 if (last_duration > 64000 && samples < last_duration) {
1364                         new_duration += 0xFFFF + 1;
1365                 }
1366                 new_duration = (new_duration & ~0xFFFF) | samples;
1367
1368                 if (event_end & 0x80) {
1369                         /* End event */
1370                         if ((rtp->lastevent != seqno) && rtp->resp) {
1371                                 rtp->dtmf_duration = new_duration;
1372                                 f = send_dtmf(instance, AST_FRAME_DTMF_END, 0);
1373                                 f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
1374                                 rtp->resp = 0;
1375                                 rtp->dtmf_duration = rtp->dtmf_timeout = 0;
1376                         }
1377                 } else {
1378                         /* Begin/continuation */
1379
1380                         if (rtp->resp && rtp->resp != resp) {
1381                                 /* Another digit already began. End it */
1382                                 f = send_dtmf(instance, AST_FRAME_DTMF_END, 0);
1383                                 f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
1384                                 rtp->resp = 0;
1385                                 rtp->dtmf_duration = rtp->dtmf_timeout = 0;
1386                         }
1387
1388                         if (rtp->resp) {
1389                                 /* Digit continues */
1390                                 rtp->dtmf_duration = new_duration;
1391                         } else {
1392                                 /* New digit began */
1393                                 rtp->resp = resp;
1394                                 f = send_dtmf(instance, AST_FRAME_DTMF_BEGIN, 0);
1395                                 rtp->dtmf_duration = samples;
1396                         }
1397
1398                         rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
1399                 }
1400
1401                 rtp->lastevent = seqno;
1402         }
1403
1404         rtp->dtmfsamples = samples;
1405
1406         return f;
1407 }
1408
1409 static struct ast_frame *process_dtmf_cisco(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct sockaddr_in *sin, int payloadtype, int mark)
1410 {
1411         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1412         unsigned int event, flags, power;
1413         char resp = 0;
1414         unsigned char seq;
1415         struct ast_frame *f = NULL;
1416
1417         if (len < 4) {
1418                 return NULL;
1419         }
1420
1421         /*      The format of Cisco RTP DTMF packet looks like next:
1422                 +0                              - sequence number of DTMF RTP packet (begins from 1,
1423                                                   wrapped to 0)
1424                 +1                              - set of flags
1425                 +1 (bit 0)              - flaps by different DTMF digits delimited by audio
1426                                                   or repeated digit without audio???
1427                 +2 (+4,+6,...)  - power level? (rises from 0 to 32 at begin of tone
1428                                                   then falls to 0 at its end)
1429                 +3 (+5,+7,...)  - detected DTMF digit (0..9,*,#,A-D,...)
1430                 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
1431                 by each new packet and thus provides some redudancy.
1432
1433                 Sample of Cisco RTP DTMF packet is (all data in hex):
1434                         19 07 00 02 12 02 20 02
1435                 showing end of DTMF digit '2'.
1436
1437                 The packets
1438                         27 07 00 02 0A 02 20 02
1439                         28 06 20 02 00 02 0A 02
1440                 shows begin of new digit '2' with very short pause (20 ms) after
1441                 previous digit '2'. Bit +1.0 flips at begin of new digit.
1442
1443                 Cisco RTP DTMF packets comes as replacement of audio RTP packets
1444                 so its uses the same sequencing and timestamping rules as replaced
1445                 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
1446                 on audio framing parameters. Marker bit isn't used within stream of
1447                 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
1448                 are not sequential at borders between DTMF and audio streams,
1449         */
1450
1451         seq = data[0];
1452         flags = data[1];
1453         power = data[2];
1454         event = data[3] & 0x1f;
1455
1456         if (option_debug > 2 || rtpdebug)
1457                 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);
1458         if (event < 10) {
1459                 resp = '0' + event;
1460         } else if (event < 11) {
1461                 resp = '*';
1462         } else if (event < 12) {
1463                 resp = '#';
1464         } else if (event < 16) {
1465                 resp = 'A' + (event - 12);
1466         } else if (event < 17) {
1467                 resp = 'X';
1468         }
1469         if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
1470                 rtp->resp = resp;
1471                 /* Why we should care on DTMF compensation at reception? */
1472                 if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
1473                         f = send_dtmf(instance, AST_FRAME_DTMF_BEGIN, 0);
1474                         rtp->dtmfsamples = 0;
1475                 }
1476         } else if ((rtp->resp == resp) && !power) {
1477                 f = send_dtmf(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE));
1478                 f->samples = rtp->dtmfsamples * (rtp_get_rate(f->subclass) / 1000);
1479                 rtp->resp = 0;
1480         } else if (rtp->resp == resp)
1481                 rtp->dtmfsamples += 20 * (rtp_get_rate(f->subclass) / 1000);
1482         rtp->dtmf_timeout = 0;
1483
1484         return f;
1485 }
1486
1487 static struct ast_frame *process_cn_rfc3389(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct sockaddr_in *sin, int payloadtype, int mark)
1488 {
1489         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1490
1491         /* Convert comfort noise into audio with various codecs.  Unfortunately this doesn't
1492            totally help us out becuase we don't have an engine to keep it going and we are not
1493            guaranteed to have it every 20ms or anything */
1494         if (rtpdebug)
1495                 ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
1496
1497         if (ast_test_flag(rtp, FLAG_3389_WARNING)) {
1498                 struct sockaddr_in remote_address = { 0, };
1499
1500                 ast_rtp_instance_get_remote_address(instance, &remote_address);
1501
1502                 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
1503                         ast_inet_ntoa(remote_address.sin_addr));
1504                 ast_set_flag(rtp, FLAG_3389_WARNING);
1505         }
1506
1507         /* Must have at least one byte */
1508         if (!len)
1509                 return NULL;
1510         if (len < 24) {
1511                 rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
1512                 rtp->f.datalen = len - 1;
1513                 rtp->f.offset = AST_FRIENDLY_OFFSET;
1514                 memcpy(rtp->f.data.ptr, data + 1, len - 1);
1515         } else {
1516                 rtp->f.data.ptr = NULL;
1517                 rtp->f.offset = 0;
1518                 rtp->f.datalen = 0;
1519         }
1520         rtp->f.frametype = AST_FRAME_CNG;
1521         rtp->f.subclass = data[0] & 0x7f;
1522         rtp->f.datalen = len - 1;
1523         rtp->f.samples = 0;
1524         rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
1525
1526         return &rtp->f;
1527 }
1528
1529 static struct ast_frame *ast_rtcp_read(struct ast_rtp_instance *instance)
1530 {
1531         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1532         struct sockaddr_in sin;
1533         socklen_t len = sizeof(sin);
1534         unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
1535         unsigned int *rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
1536         int res, packetwords, position = 0;
1537         struct ast_frame *f = &ast_null_frame;
1538
1539         /* Read in RTCP data from the socket */
1540         if ((res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0) {
1541                 ast_assert(errno != EBADF);
1542                 if (errno != EAGAIN) {
1543                         ast_log(LOG_WARNING, "RTCP Read error: %s.  Hanging up.\n", strerror(errno));
1544                         return NULL;
1545                 }
1546                 return &ast_null_frame;
1547         }
1548
1549         packetwords = res / 4;
1550
1551         if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
1552                 /* Send to whoever sent to us */
1553                 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1554                     (rtp->rtcp->them.sin_port != sin.sin_port)) {
1555                         memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1556                         if (option_debug || rtpdebug)
1557                                 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));
1558                 }
1559         }
1560
1561         ast_debug(1, "Got RTCP report of %d bytes\n", res);
1562
1563         while (position < packetwords) {
1564                 int i, pt, rc;
1565                 unsigned int length, dlsr, lsr, msw, lsw, comp;
1566                 struct timeval now;
1567                 double rttsec, reported_jitter, reported_normdev_jitter_current, normdevrtt_current, reported_lost, reported_normdev_lost_current;
1568                 uint64_t rtt = 0;
1569
1570                 i = position;
1571                 length = ntohl(rtcpheader[i]);
1572                 pt = (length & 0xff0000) >> 16;
1573                 rc = (length & 0x1f000000) >> 24;
1574                 length &= 0xffff;
1575
1576                 if ((i + length) > packetwords) {
1577                         if (option_debug || rtpdebug)
1578                                 ast_log(LOG_DEBUG, "RTCP Read too short\n");
1579                         return &ast_null_frame;
1580                 }
1581
1582                 if (rtcp_debug_test_addr(&sin)) {
1583                         ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1584                         ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
1585                         ast_verbose("Reception reports: %d\n", rc);
1586                         ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
1587                 }
1588
1589                 i += 2; /* Advance past header and ssrc */
1590
1591                 switch (pt) {
1592                 case RTCP_PT_SR:
1593                         gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
1594                         rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
1595                         rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
1596                         rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
1597
1598                         if (rtcp_debug_test_addr(&sin)) {
1599                                 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
1600                                 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
1601                                 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
1602                         }
1603                         i += 5;
1604                         if (rc < 1)
1605                                 break;
1606                         /* Intentional fall through */
1607                 case RTCP_PT_RR:
1608                         /* Don't handle multiple reception reports (rc > 1) yet */
1609                         /* Calculate RTT per RFC */
1610                         gettimeofday(&now, NULL);
1611                         timeval2ntp(now, &msw, &lsw);
1612                         if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
1613                                 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
1614                                 lsr = ntohl(rtcpheader[i + 4]);
1615                                 dlsr = ntohl(rtcpheader[i + 5]);
1616                                 rtt = comp - lsr - dlsr;
1617
1618                                 /* Convert end to end delay to usec (keeping the calculation in 64bit space)
1619                                    sess->ee_delay = (eedelay * 1000) / 65536; */
1620                                 if (rtt < 4294) {
1621                                         rtt = (rtt * 1000000) >> 16;
1622                                 } else {
1623                                         rtt = (rtt * 1000) >> 16;
1624                                         rtt *= 1000;
1625                                 }
1626                                 rtt = rtt / 1000.;
1627                                 rttsec = rtt / 1000.;
1628                                 rtp->rtcp->rtt = rttsec;
1629
1630                                 if (comp - dlsr >= lsr) {
1631                                         rtp->rtcp->accumulated_transit += rttsec;
1632
1633                                         if (rtp->rtcp->rtt_count == 0)
1634                                                 rtp->rtcp->minrtt = rttsec;
1635
1636                                         if (rtp->rtcp->maxrtt<rttsec)
1637                                                 rtp->rtcp->maxrtt = rttsec;
1638                                         if (rtp->rtcp->minrtt>rttsec)
1639                                                 rtp->rtcp->minrtt = rttsec;
1640
1641                                         normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt, rttsec, rtp->rtcp->rtt_count);
1642
1643                                         rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt, rttsec, rtp->rtcp->normdevrtt, normdevrtt_current, rtp->rtcp->rtt_count);
1644
1645                                         rtp->rtcp->normdevrtt = normdevrtt_current;
1646
1647                                         rtp->rtcp->rtt_count++;
1648                                 } else if (rtcp_debug_test_addr(&sin)) {
1649                                         ast_verbose("Internal RTCP NTP clock skew detected: "
1650                                                            "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
1651                                                     "diff=%d\n",
1652                                                     lsr, comp, dlsr, dlsr / 65536,
1653                                                     (dlsr % 65536) * 1000 / 65536,
1654                                                     dlsr - (comp - lsr));
1655                                 }
1656                         }
1657
1658                         rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
1659                         reported_jitter = (double) rtp->rtcp->reported_jitter;
1660
1661                         if (rtp->rtcp->reported_jitter_count == 0)
1662                                 rtp->rtcp->reported_minjitter = reported_jitter;
1663
1664                         if (reported_jitter < rtp->rtcp->reported_minjitter)
1665                                 rtp->rtcp->reported_minjitter = reported_jitter;
1666
1667                         if (reported_jitter > rtp->rtcp->reported_maxjitter)
1668                                 rtp->rtcp->reported_maxjitter = reported_jitter;
1669
1670                         reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);
1671
1672                         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);
1673
1674                         rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;
1675
1676                         rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
1677
1678                         reported_lost = (double) rtp->rtcp->reported_lost;
1679
1680                         /* using same counter as for jitter */
1681                         if (rtp->rtcp->reported_jitter_count == 0)
1682                                 rtp->rtcp->reported_minlost = reported_lost;
1683
1684                         if (reported_lost < rtp->rtcp->reported_minlost)
1685                                 rtp->rtcp->reported_minlost = reported_lost;
1686
1687                         if (reported_lost > rtp->rtcp->reported_maxlost)
1688                                 rtp->rtcp->reported_maxlost = reported_lost;
1689                         reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);
1690
1691                         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);
1692
1693                         rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;
1694
1695                         rtp->rtcp->reported_jitter_count++;
1696
1697                         if (rtcp_debug_test_addr(&sin)) {
1698                                 ast_verbose("  Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
1699                                 ast_verbose("  Packets lost so far: %d\n", rtp->rtcp->reported_lost);
1700                                 ast_verbose("  Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
1701                                 ast_verbose("  Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
1702                                 ast_verbose("  Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
1703                                 ast_verbose("  Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
1704                                 ast_verbose("  DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
1705                                 if (rtt)
1706                                         ast_verbose("  RTT: %lu(sec)\n", (unsigned long) rtt);
1707                         }
1708                         if (rtt) {
1709                                 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From %s:%d\r\n"
1710                                                                     "PT: %d(%s)\r\n"
1711                                                                     "ReceptionReports: %d\r\n"
1712                                                                     "SenderSSRC: %u\r\n"
1713                                                                     "FractionLost: %ld\r\n"
1714                                                                     "PacketsLost: %d\r\n"
1715                                                                     "HighestSequence: %ld\r\n"
1716                                                                     "SequenceNumberCycles: %ld\r\n"
1717                                                                     "IAJitter: %u\r\n"
1718                                                                     "LastSR: %lu.%010lu\r\n"
1719                                                                     "DLSR: %4.4f(sec)\r\n"
1720                                               "RTT: %llu(sec)\r\n",
1721                                               ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
1722                                               pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1723                                               rc,
1724                                               rtcpheader[i + 1],
1725                                               (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1726                                               rtp->rtcp->reported_lost,
1727                                               (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1728                                               (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1729                                               rtp->rtcp->reported_jitter,
1730                                               (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1731                                               ntohl(rtcpheader[i + 5])/65536.0,
1732                                               (unsigned long long)rtt);
1733                         } else {
1734                                 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From %s:%d\r\n"
1735                                                                     "PT: %d(%s)\r\n"
1736                                                                     "ReceptionReports: %d\r\n"
1737                                                                     "SenderSSRC: %u\r\n"
1738                                                                     "FractionLost: %ld\r\n"
1739                                                                     "PacketsLost: %d\r\n"
1740                                                                     "HighestSequence: %ld\r\n"
1741                                                                     "SequenceNumberCycles: %ld\r\n"
1742                                                                     "IAJitter: %u\r\n"
1743                                                                     "LastSR: %lu.%010lu\r\n"
1744                                               "DLSR: %4.4f(sec)\r\n",
1745                                               ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
1746                                               pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1747                                               rc,
1748                                               rtcpheader[i + 1],
1749                                               (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1750                                               rtp->rtcp->reported_lost,
1751                                               (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1752                                               (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1753                                               rtp->rtcp->reported_jitter,
1754                                               (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
1755                                               ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1756                                               ntohl(rtcpheader[i + 5])/65536.0);
1757                         }
1758                         break;
1759                 case RTCP_PT_FUR:
1760                         if (rtcp_debug_test_addr(&sin))
1761                                 ast_verbose("Received an RTCP Fast Update Request\n");
1762                         rtp->f.frametype = AST_FRAME_CONTROL;
1763                         rtp->f.subclass = AST_CONTROL_VIDUPDATE;
1764                         rtp->f.datalen = 0;
1765                         rtp->f.samples = 0;
1766                         rtp->f.mallocd = 0;
1767                         rtp->f.src = "RTP";
1768                         f = &rtp->f;
1769                         break;
1770                 case RTCP_PT_SDES:
1771                         if (rtcp_debug_test_addr(&sin))
1772                                 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1773                         break;
1774                 case RTCP_PT_BYE:
1775                         if (rtcp_debug_test_addr(&sin))
1776                                 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1777                         break;
1778                 default:
1779                         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));
1780                         break;
1781                 }
1782                 position += (length + 1);
1783         }
1784
1785         rtp->rtcp->rtcp_info = 1;
1786
1787         return f;
1788 }
1789
1790 static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance, unsigned int *rtpheader, int len, int hdrlen)
1791 {
1792         struct ast_rtp_instance *instance1 = ast_rtp_instance_get_bridged(instance);
1793         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance), *bridged = ast_rtp_instance_get_data(instance1);
1794         int res = 0, payload = 0, bridged_payload = 0, mark;
1795         struct ast_rtp_payload_type payload_type;
1796         int reconstruct = ntohl(rtpheader[0]);
1797         struct sockaddr_in remote_address = { 0, };
1798
1799         /* Get fields from packet */
1800         payload = (reconstruct & 0x7f0000) >> 16;
1801         mark = (((reconstruct & 0x800000) >> 23) != 0);
1802
1803         /* Check what the payload value should be */
1804         payload_type = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), payload);
1805
1806         /* Otherwise adjust bridged payload to match */
1807         bridged_payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance1), payload_type.asterisk_format, payload_type.code);
1808
1809         /* 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 */
1810         if (!(ast_rtp_instance_get_codecs(instance1)->payloads[bridged_payload].code)) {
1811                 return -1;
1812         }
1813
1814         /* If the marker bit has been explicitly set turn it on */
1815         if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
1816                 mark = 1;
1817                 ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
1818         }
1819
1820         /* Reconstruct part of the packet */
1821         reconstruct &= 0xFF80FFFF;
1822         reconstruct |= (bridged_payload << 16);
1823         reconstruct |= (mark << 23);
1824         rtpheader[0] = htonl(reconstruct);
1825
1826         ast_rtp_instance_get_remote_address(instance1, &remote_address);
1827
1828         /* Send the packet back out */
1829         res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&remote_address, sizeof(remote_address));
1830         if (res < 0) {
1831                 if (!ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_NAT) && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1832                         ast_debug(1, "RTP Transmission error of packet to %s:%d: %s\n", ast_inet_ntoa(remote_address.sin_addr), ntohs(remote_address.sin_port), strerror(errno));
1833                 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1834                         if (option_debug || rtpdebug)
1835                                 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(remote_address.sin_addr), ntohs(remote_address.sin_port));
1836                         ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1837                 }
1838                 return 0;
1839         } else if (rtp_debug_test_addr(&remote_address)) {
1840                 ast_verbose("Sent RTP P2P packet to %s:%u (type %-2.2d, len %-6.6u)\n", ast_inet_ntoa(remote_address.sin_addr), ntohs(remote_address.sin_port), bridged_payload, len - hdrlen);
1841         }
1842
1843         return 0;
1844 }
1845
1846 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
1847 {
1848         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1849         struct sockaddr_in sin;
1850         socklen_t len = sizeof(sin);
1851         int res, hdrlen = 12, version, payloadtype, padding, mark, ext, cc, prev_seqno;
1852         unsigned int *rtpheader = (unsigned int*)(rtp->rawdata + AST_FRIENDLY_OFFSET), seqno, ssrc, timestamp;
1853         struct ast_rtp_payload_type payload;
1854         struct sockaddr_in remote_address = { 0, };
1855
1856         /* If this is actually RTCP let's hop on over and handle it */
1857         if (rtcp) {
1858                 if (rtp->rtcp) {
1859                         return ast_rtcp_read(instance);
1860                 }
1861                 return &ast_null_frame;
1862         }
1863
1864         /* If we are currently sending DTMF to the remote party send a continuation packet */
1865         if (rtp->sending_digit) {
1866                 ast_rtp_dtmf_continuation(instance);
1867         }
1868
1869         /* Actually read in the data from the socket */
1870         if ((res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr*)&sin, &len)) < 0) {
1871                 ast_assert(errno != EBADF);
1872                 if (errno != EAGAIN) {
1873                         ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
1874                         return NULL;
1875                 }
1876                 return &ast_null_frame;
1877         }
1878
1879         /* Make sure the data that was read in is actually enough to make up an RTP packet */
1880         if (res < hdrlen) {
1881                 ast_log(LOG_WARNING, "RTP Read too short\n");
1882                 return &ast_null_frame;
1883         }
1884
1885         /* If strict RTP protection is enabled see if we need to learn the remote address or if we need to drop the packet */
1886         if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
1887                 memcpy(&rtp->strict_rtp_address, &sin, sizeof(rtp->strict_rtp_address));
1888                 rtp->strict_rtp_state = STRICT_RTP_CLOSED;
1889         } else if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
1890                 if ((rtp->strict_rtp_address.sin_addr.s_addr != sin.sin_addr.s_addr) || (rtp->strict_rtp_address.sin_port != sin.sin_port)) {
1891                         /* Hmm, not the strict addres. Perhaps we're getting audio from the alternate? */
1892                         if ((rtp->alt_rtp_address.sin_addr.s_addr == sin.sin_addr.s_addr) && (rtp->alt_rtp_address.sin_port == sin.sin_port)) {
1893                                 /* ooh, we did! You're now the new expected address, son! */
1894                                 rtp->strict_rtp_address = sin;
1895                         } else  {
1896                                 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));
1897                                 return &ast_null_frame;
1898                         }
1899                 }
1900         }
1901
1902         /* Get fields and verify this is an RTP packet */
1903         seqno = ntohl(rtpheader[0]);
1904
1905         ast_rtp_instance_get_remote_address(instance, &remote_address);
1906
1907         if (!(version = (seqno & 0xC0000000) >> 30)) {
1908                 if ((ast_stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == AST_STUN_ACCEPT) &&
1909                     (!remote_address.sin_port && !remote_address.sin_addr.s_addr)) {
1910                         ast_rtp_instance_set_remote_address(instance, &sin);
1911                 }
1912                 return &ast_null_frame;
1913         }
1914
1915         /* If symmetric RTP is enabled see if the remote side is not what we expected and change where we are sending audio */
1916         if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
1917                 if ((remote_address.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1918                     (remote_address.sin_port != sin.sin_port)) {
1919                         ast_rtp_instance_set_remote_address(instance, &sin);
1920                         memcpy(&remote_address, &sin, sizeof(remote_address));
1921                         if (rtp->rtcp) {
1922                                 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1923                                 rtp->rtcp->them.sin_port = htons(ntohs(sin.sin_port)+1);
1924                         }
1925                         rtp->rxseqno = 0;
1926                         ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1927                         if (option_debug || rtpdebug)
1928                                 ast_debug(0, "RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(remote_address.sin_addr), ntohs(remote_address.sin_port));
1929                 }
1930         }
1931
1932         /* If we are directly bridged to another instance send the audio directly out */
1933         if (ast_rtp_instance_get_bridged(instance) && !bridge_p2p_rtp_write(instance, rtpheader, res, hdrlen)) {
1934                 return &ast_null_frame;
1935         }
1936
1937         /* If the version is not what we expected by this point then just drop the packet */
1938         if (version != 2) {
1939                 return &ast_null_frame;
1940         }
1941
1942         /* Pull out the various other fields we will need */
1943         payloadtype = (seqno & 0x7f0000) >> 16;
1944         padding = seqno & (1 << 29);
1945         mark = seqno & (1 << 23);
1946         ext = seqno & (1 << 28);
1947         cc = (seqno & 0xF000000) >> 24;
1948         seqno &= 0xffff;
1949         timestamp = ntohl(rtpheader[1]);
1950         ssrc = ntohl(rtpheader[2]);
1951
1952         /* Force a marker bit if the SSRC changes */
1953         if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1954                 if (option_debug || rtpdebug) {
1955                         ast_debug(1, "Forcing Marker bit, because SSRC has changed\n");
1956                 }
1957                 mark = 1;
1958         }
1959
1960         /* Remove any padding bytes that may be present */
1961         if (padding) {
1962                 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1963         }
1964
1965         /* Skip over any CSRC fields */
1966         if (cc) {
1967                 hdrlen += cc * 4;
1968         }
1969
1970         /* Look for any RTP extensions, currently we do not support any */
1971         if (ext) {
1972                 hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
1973                 hdrlen += 4;
1974                 if (option_debug) {
1975                         int profile;
1976                         profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
1977                         if (profile == 0x505a)
1978                                 ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
1979                         else
1980                                 ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
1981                 }
1982         }
1983
1984         /* Make sure after we potentially mucked with the header length that it is once again valid */
1985         if (res < hdrlen) {
1986                 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d\n", res, hdrlen);
1987                 return &ast_null_frame;
1988         }
1989
1990         rtp->rxcount++;
1991         if (rtp->rxcount == 1) {
1992                 rtp->seedrxseqno = seqno;
1993         }
1994
1995         /* Do not schedule RR if RTCP isn't run */
1996         if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
1997                 /* Schedule transmission of Receiver Report */
1998                 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1999         }
2000         if ((int)rtp->lastrxseqno - (int)seqno  > 100) /* if so it would indicate that the sender cycled; allow for misordering */
2001                 rtp->cycles += RTP_SEQ_MOD;
2002
2003         prev_seqno = rtp->lastrxseqno;
2004         rtp->lastrxseqno = seqno;
2005
2006         if (!rtp->themssrc) {
2007                 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
2008         }
2009
2010         if (rtp_debug_test_addr(&sin)) {
2011                 ast_verbose("Got  RTP packet from    %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2012                             ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
2013         }
2014
2015         payload = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), payloadtype);
2016
2017         /* If the payload is not actually an Asterisk one but a special one pass it off to the respective handler */
2018         if (!payload.asterisk_format) {
2019                 struct ast_frame *f = NULL;
2020                 if (payload.code == AST_RTP_DTMF) {
2021                         f = process_dtmf_rfc2833(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &sin, payloadtype, mark);
2022                 } else if (payload.code == AST_RTP_CISCO_DTMF) {
2023                         f = process_dtmf_cisco(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &sin, payloadtype, mark);
2024                 } else if (payload.code == AST_RTP_CN) {
2025                         f = process_cn_rfc3389(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &sin, payloadtype, mark);
2026                 } else {
2027                         ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(remote_address.sin_addr));
2028                 }
2029
2030                 return f ? f : &ast_null_frame;
2031         }
2032
2033         rtp->lastrxformat = rtp->f.subclass = payload.code;
2034         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;
2035
2036         rtp->rxseqno = seqno;
2037
2038         if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
2039                 rtp->dtmf_timeout = 0;
2040
2041                 if (rtp->resp) {
2042                         struct ast_frame *f;
2043                         f = send_dtmf(instance, AST_FRAME_DTMF_END, 0);
2044                         f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
2045                         rtp->resp = 0;
2046                         rtp->dtmf_timeout = rtp->dtmf_duration = 0;
2047                         return f;
2048                 }
2049         }
2050
2051         rtp->lastrxts = timestamp;
2052
2053         rtp->f.src = "RTP";
2054         rtp->f.mallocd = 0;
2055         rtp->f.datalen = res - hdrlen;
2056         rtp->f.data.ptr = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
2057         rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
2058         rtp->f.seqno = seqno;
2059
2060         if (rtp->f.subclass == AST_FORMAT_T140 && (int)seqno - (prev_seqno+1) > 0 && (int)seqno - (prev_seqno+1) < 10) {
2061                 unsigned char *data = rtp->f.data.ptr;
2062
2063                 memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
2064                 rtp->f.datalen +=3;
2065                 *data++ = 0xEF;
2066                 *data++ = 0xBF;
2067                 *data = 0xBD;
2068         }
2069
2070         if (rtp->f.subclass == AST_FORMAT_T140RED) {
2071                 unsigned char *data = rtp->f.data.ptr;
2072                 unsigned char *header_end;
2073                 int num_generations;
2074                 int header_length;
2075                 int len;
2076                 int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
2077                 int x;
2078
2079                 rtp->f.subclass = AST_FORMAT_T140;
2080                 header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
2081                 if (header_end == NULL) {
2082                         return &ast_null_frame;
2083                 }
2084                 header_end++;
2085
2086                 header_length = header_end - data;
2087                 num_generations = header_length / 4;
2088                 len = header_length;
2089
2090                 if (!diff) {
2091                         for (x = 0; x < num_generations; x++)
2092                                 len += data[x * 4 + 3];
2093
2094                         if (!(rtp->f.datalen - len))
2095                                 return &ast_null_frame;
2096
2097                         rtp->f.data.ptr += len;
2098                         rtp->f.datalen -= len;
2099                 } else if (diff > num_generations && diff < 10) {
2100                         len -= 3;
2101                         rtp->f.data.ptr += len;
2102                         rtp->f.datalen -= len;
2103
2104                         data = rtp->f.data.ptr;
2105                         *data++ = 0xEF;
2106                         *data++ = 0xBF;
2107                         *data = 0xBD;
2108                 } else {
2109                         for ( x = 0; x < num_generations - diff; x++)
2110                                 len += data[x * 4 + 3];
2111
2112                         rtp->f.data.ptr += len;
2113                         rtp->f.datalen -= len;
2114                 }
2115         }
2116
2117         if (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) {
2118                 rtp->f.samples = ast_codec_get_samples(&rtp->f);
2119                 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
2120                         ast_frame_byteswap_be(&rtp->f);
2121                 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
2122                 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
2123                 ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
2124                 rtp->f.ts = timestamp / (rtp_get_rate(rtp->f.subclass) / 1000);
2125                 rtp->f.len = rtp->f.samples / ((ast_format_rate(rtp->f.subclass) / 1000));
2126         } else if (rtp->f.subclass & AST_FORMAT_VIDEO_MASK) {
2127                 /* Video -- samples is # of samples vs. 90000 */
2128                 if (!rtp->lastividtimestamp)
2129                         rtp->lastividtimestamp = timestamp;
2130                 rtp->f.samples = timestamp - rtp->lastividtimestamp;
2131                 rtp->lastividtimestamp = timestamp;
2132                 rtp->f.delivery.tv_sec = 0;
2133                 rtp->f.delivery.tv_usec = 0;
2134                 /* Pass the RTP marker bit as bit 0 in the subclass field.
2135                  * This is ok because subclass is actually a bitmask, and
2136                  * the low bits represent audio formats, that are not
2137                  * involved here since we deal with video.
2138                  */
2139                 if (mark)
2140                         rtp->f.subclass |= 0x1;
2141         } else {
2142                 /* TEXT -- samples is # of samples vs. 1000 */
2143                 if (!rtp->lastitexttimestamp)
2144                         rtp->lastitexttimestamp = timestamp;
2145                 rtp->f.samples = timestamp - rtp->lastitexttimestamp;
2146                 rtp->lastitexttimestamp = timestamp;
2147                 rtp->f.delivery.tv_sec = 0;
2148                 rtp->f.delivery.tv_usec = 0;
2149         }
2150
2151         return &rtp->f;
2152 }
2153
2154 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
2155 {
2156         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2157
2158         if (property == AST_RTP_PROPERTY_RTCP) {
2159                 if (rtp->rtcp) {
2160                         ast_debug(1, "Ignoring duplicate RTCP property on RTP instance '%p'\n", instance);
2161                         return;
2162                 }
2163                 if (!(rtp->rtcp = ast_calloc(1, sizeof(*rtp->rtcp)))) {
2164                         return;
2165                 }
2166                 if ((rtp->rtcp->s = create_new_socket("RTCP")) < 0) {
2167                         ast_debug(1, "Failed to create a new socket for RTCP on instance '%p'\n", instance);
2168                         ast_free(rtp->rtcp);
2169                         rtp->rtcp = NULL;
2170                         return;
2171                 }
2172
2173                 /* Grab the IP address and port we are going to use */
2174                 ast_rtp_instance_get_local_address(instance, &rtp->rtcp->us);
2175                 rtp->rtcp->us.sin_port = htons(ntohs(rtp->rtcp->us.sin_port) + 1);
2176
2177                 /* Try to actually bind to the IP address and port we are going to use for RTCP, if this fails we have to bail out */
2178                 if (bind(rtp->rtcp->s, (struct sockaddr*)&rtp->rtcp->us, sizeof(rtp->rtcp->us))) {
2179                         ast_debug(1, "Failed to setup RTCP on RTP instance '%p'\n", instance);
2180                         close(rtp->rtcp->s);
2181                         ast_free(rtp->rtcp);
2182                         rtp->rtcp = NULL;
2183                         return;
2184                 }
2185
2186                 ast_debug(1, "Setup RTCP on RTP instance '%p'\n", instance);
2187                 rtp->rtcp->schedid = -1;
2188
2189                 return;
2190         }
2191
2192         return;
2193 }
2194
2195 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp)
2196 {
2197         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2198
2199         return rtcp ? (rtp->rtcp ? rtp->rtcp->s : -1) : rtp->s;
2200 }
2201
2202 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct sockaddr_in *sin)
2203 {
2204         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2205
2206         if (rtp->rtcp) {
2207                 ast_debug(1, "Setting RTCP address on RTP instance '%p'\n", instance);
2208                 memcpy(&rtp->rtcp->them, sin, sizeof(rtp->rtcp->them));
2209                 rtp->rtcp->them.sin_port = htons(ntohs(sin->sin_port) + 1);
2210         }
2211
2212         rtp->rxseqno = 0;
2213
2214         if (strictrtp) {
2215                 rtp->strict_rtp_state = STRICT_RTP_LEARN;
2216         }
2217
2218         return;
2219 }
2220
2221 static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct sockaddr_in *sin)
2222 {
2223         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2224
2225         /* No need to futz with rtp->rtcp here because ast_rtcp_read is already able to adjust if receiving
2226          * RTCP from an "unexpected" source
2227          */
2228         rtp->alt_rtp_address = *sin;
2229
2230         return;
2231 }
2232
2233 /*! \brief Write t140 redundacy frame
2234  * \param data primary data to be buffered
2235  */
2236 static int red_write(const void *data)
2237 {
2238         struct ast_rtp_instance *instance = (struct ast_rtp_instance*) data;
2239         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2240
2241         ast_rtp_write(instance, &rtp->red->t140);
2242
2243         return 1;
2244 }
2245
2246 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
2247 {
2248         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2249         int x;
2250
2251         if (!(rtp->red = ast_calloc(1, sizeof(*rtp->red)))) {
2252                 return -1;
2253         }
2254
2255         rtp->red->t140.frametype = AST_FRAME_TEXT;
2256         rtp->red->t140.subclass = AST_FORMAT_T140RED;
2257         rtp->red->t140.data.ptr = &rtp->red->buf_data;
2258
2259         rtp->red->t140.ts = 0;
2260         rtp->red->t140red = rtp->red->t140;
2261         rtp->red->t140red.data.ptr = &rtp->red->t140red_data;
2262         rtp->red->t140red.datalen = 0;
2263         rtp->red->ti = buffer_time;
2264         rtp->red->num_gen = generations;
2265         rtp->red->hdrlen = generations * 4 + 1;
2266         rtp->red->prev_ts = 0;
2267
2268         for (x = 0; x < generations; x++) {
2269                 rtp->red->pt[x] = payloads[x];
2270                 rtp->red->pt[x] |= 1 << 7; /* mark redundant generations pt */
2271                 rtp->red->t140red_data[x*4] = rtp->red->pt[x];
2272         }
2273         rtp->red->t140red_data[x*4] = rtp->red->pt[x] = payloads[x]; /* primary pt */
2274         rtp->red->schedid = ast_sched_add(rtp->sched, generations, red_write, instance);
2275
2276         rtp->red->t140.datalen = 0;
2277
2278         return 0;
2279 }
2280
2281 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
2282 {
2283         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2284
2285         if (frame->datalen > -1) {
2286                 struct rtp_red *red = rtp->red;
2287                 memcpy(&red->buf_data[red->t140.datalen], frame->data.ptr, frame->datalen);
2288                 red->t140.datalen += frame->datalen;
2289                 red->t140.ts = frame->ts;
2290         }
2291
2292         return 0;
2293 }
2294
2295 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1)
2296 {
2297         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance0);
2298
2299         ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2300
2301         return 0;
2302 }
2303
2304 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
2305 {
2306         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2307
2308         if (!rtp->rtcp) {
2309                 return -1;
2310         }
2311
2312         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXCOUNT, -1, stats->txcount, rtp->txcount);
2313         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXCOUNT, -1, stats->rxcount, rtp->rxcount);
2314
2315         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->txploss, rtp->rtcp->reported_lost);
2316         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->rxploss, rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
2317         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_maxrxploss, rtp->rtcp->reported_maxlost);
2318         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_minrxploss, rtp->rtcp->reported_minlost);
2319         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_normdevrxploss, rtp->rtcp->reported_normdev_lost);
2320         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_stdevrxploss, rtp->rtcp->reported_stdev_lost);
2321         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_maxrxploss, rtp->rtcp->maxrxlost);
2322         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_minrxploss, rtp->rtcp->minrxlost);
2323         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_normdevrxploss, rtp->rtcp->normdev_rxlost);
2324         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_stdevrxploss, rtp->rtcp->stdev_rxlost);
2325         AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_LOSS);
2326
2327         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->txjitter, rtp->rxjitter);
2328         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->rxjitter, rtp->rtcp->reported_jitter / (unsigned int) 65536.0);
2329         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_maxjitter, rtp->rtcp->reported_maxjitter);
2330         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_minjitter, rtp->rtcp->reported_minjitter);
2331         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_normdevjitter, rtp->rtcp->reported_normdev_jitter);
2332         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_stdevjitter, rtp->rtcp->reported_stdev_jitter);
2333         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_maxjitter, rtp->rtcp->maxrxjitter);
2334         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_minjitter, rtp->rtcp->minrxjitter);
2335         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_normdevjitter, rtp->rtcp->normdev_rxjitter);
2336         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_stdevjitter, rtp->rtcp->stdev_rxjitter);
2337         AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_JITTER);
2338
2339         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->rtt, rtp->rtcp->rtt);
2340         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MAX_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->maxrtt, rtp->rtcp->maxrtt);
2341         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MIN_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->minrtt, rtp->rtcp->minrtt);
2342         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_NORMDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->normdevrtt, rtp->rtcp->normdevrtt);
2343         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_STDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->stdevrtt, rtp->rtcp->stdevrtt);
2344         AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_RTT);
2345
2346         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_SSRC, -1, stats->local_ssrc, rtp->ssrc);
2347         AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_SSRC, -1, stats->remote_ssrc, rtp->themssrc);
2348
2349         return 0;
2350 }
2351
2352 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1)
2353 {
2354         /* If both sides are not using the same method of DTMF transmission
2355          * (ie: one is RFC2833, other is INFO... then we can not do direct media.
2356          * --------------------------------------------------
2357          * | DTMF Mode |  HAS_DTMF  |  Accepts Begin Frames |
2358          * |-----------|------------|-----------------------|
2359          * | Inband    | False      | True                  |
2360          * | RFC2833   | True       | True                  |
2361          * | SIP INFO  | False      | False                 |
2362          * --------------------------------------------------
2363          */
2364         return (((ast_rtp_instance_get_prop(instance0, AST_RTP_PROPERTY_DTMF) != ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_DTMF)) ||
2365                  (!chan0->tech->send_digit_begin != !chan1->tech->send_digit_begin)) ? 0 : 1);
2366 }
2367
2368 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct sockaddr_in *suggestion, const char *username)
2369 {
2370         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2371
2372         ast_stun_request(rtp->s, suggestion, username, NULL);
2373 }
2374
2375 static void ast_rtp_stop(struct ast_rtp_instance *instance)
2376 {
2377         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2378         struct sockaddr_in sin = { 0, };
2379
2380         if (rtp->rtcp) {
2381                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2382         }
2383         if (rtp->red) {
2384                 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
2385                 free(rtp->red);
2386                 rtp->red = NULL;
2387         }
2388
2389         ast_rtp_instance_set_remote_address(instance, &sin);
2390         if (rtp->rtcp) {
2391                 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
2392                 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
2393         }
2394
2395         ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2396 }
2397
2398 static char *rtp_do_debug_ip(struct ast_cli_args *a)
2399 {
2400         struct hostent *hp;
2401         struct ast_hostent ahp;
2402         int port = 0;
2403         char *p, *arg = ast_strdupa(a->argv[3]);
2404
2405         p = strstr(arg, ":");
2406         if (p) {
2407                 *p = '\0';
2408                 p++;
2409                 port = atoi(p);
2410         }
2411         hp = ast_gethostbyname(arg, &ahp);
2412         if (hp == NULL) {
2413                 ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
2414                 return CLI_FAILURE;
2415         }
2416         rtpdebugaddr.sin_family = AF_INET;
2417         memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
2418         rtpdebugaddr.sin_port = htons(port);
2419         if (port == 0)
2420                 ast_cli(a->fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr.sin_addr));
2421         else
2422                 ast_cli(a->fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr.sin_addr), port);
2423         rtpdebug = 1;
2424         return CLI_SUCCESS;
2425 }
2426
2427 static char *rtcp_do_debug_ip(struct ast_cli_args *a)
2428 {
2429         struct hostent *hp;
2430         struct ast_hostent ahp;
2431         int port = 0;
2432         char *p, *arg = ast_strdupa(a->argv[3]);
2433
2434         p = strstr(arg, ":");
2435         if (p) {
2436                 *p = '\0';
2437                 p++;
2438                 port = atoi(p);
2439         }
2440         hp = ast_gethostbyname(arg, &ahp);
2441         if (hp == NULL) {
2442                 ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
2443                 return CLI_FAILURE;
2444         }
2445         rtcpdebugaddr.sin_family = AF_INET;
2446         memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
2447         rtcpdebugaddr.sin_port = htons(port);
2448         if (port == 0)
2449                 ast_cli(a->fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
2450         else
2451                 ast_cli(a->fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
2452         rtcpdebug = 1;
2453         return CLI_SUCCESS;
2454 }
2455
2456 static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2457 {
2458         switch (cmd) {
2459         case CLI_INIT:
2460                 e->command = "rtp set debug {on|off|ip}";
2461                 e->usage =
2462                         "Usage: rtp set debug {on|off|ip host[:port]}\n"
2463                         "       Enable/Disable dumping of all RTP packets. If 'ip' is\n"
2464                         "       specified, limit the dumped packets to those to and from\n"
2465                         "       the specified 'host' with optional port.\n";
2466                 return NULL;
2467         case CLI_GENERATE:
2468                 return NULL;
2469         }
2470
2471         if (a->argc == e->args) { /* set on or off */
2472                 if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
2473                         rtpdebug = 1;
2474                         memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
2475                         ast_cli(a->fd, "RTP Debugging Enabled\n");
2476                         return CLI_SUCCESS;
2477                 } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
2478                         rtpdebug = 0;
2479                         ast_cli(a->fd, "RTP Debugging Disabled\n");
2480                         return CLI_SUCCESS;
2481                 }
2482         } else if (a->argc == e->args +1) { /* ip */
2483                 return rtp_do_debug_ip(a);
2484         }
2485
2486         return CLI_SHOWUSAGE;   /* default, failure */
2487 }
2488
2489 static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2490 {
2491         switch (cmd) {
2492         case CLI_INIT:
2493                 e->command = "rtcp set debug {on|off|ip}";
2494                 e->usage =
2495                         "Usage: rtcp set debug {on|off|ip host[:port]}\n"
2496                         "       Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
2497                         "       specified, limit the dumped packets to those to and from\n"
2498                         "       the specified 'host' with optional port.\n";
2499                 return NULL;
2500         case CLI_GENERATE:
2501                 return NULL;
2502         }
2503
2504         if (a->argc == e->args) { /* set on or off */
2505                 if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
2506                         rtcpdebug = 1;
2507                         memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
2508                         ast_cli(a->fd, "RTCP Debugging Enabled\n");
2509                         return CLI_SUCCESS;
2510                 } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
2511                         rtcpdebug = 0;
2512                         ast_cli(a->fd, "RTCP Debugging Disabled\n");
2513                         return CLI_SUCCESS;
2514                 }
2515         } else if (a->argc == e->args +1) { /* ip */
2516                 return rtcp_do_debug_ip(a);
2517         }
2518
2519         return CLI_SHOWUSAGE;   /* default, failure */
2520 }
2521
2522 static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2523 {
2524         switch (cmd) {
2525         case CLI_INIT:
2526                 e->command = "rtcp set stats {on|off}";
2527                 e->usage =
2528                         "Usage: rtcp set stats {on|off}\n"
2529                         "       Enable/Disable dumping of RTCP stats.\n";
2530                 return NULL;
2531         case CLI_GENERATE:
2532                 return NULL;
2533         }
2534
2535         if (a->argc != e->args)
2536                 return CLI_SHOWUSAGE;
2537
2538         if (!strncasecmp(a->argv[e->args-1], "on", 2))
2539                 rtcpstats = 1;
2540         else if (!strncasecmp(a->argv[e->args-1], "off", 3))
2541                 rtcpstats = 0;
2542         else
2543                 return CLI_SHOWUSAGE;
2544
2545         ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
2546         return CLI_SUCCESS;
2547 }
2548
2549 static struct ast_cli_entry cli_rtp[] = {
2550         AST_CLI_DEFINE(handle_cli_rtp_set_debug,  "Enable/Disable RTP debugging"),
2551         AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging"),
2552         AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats"),
2553 };
2554
2555 static int rtp_reload(int reload)
2556 {
2557         struct ast_config *cfg;
2558         const char *s;
2559         struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2560
2561         cfg = ast_config_load2("rtp.conf", "rtp", config_flags);
2562         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
2563                 return 0;
2564         }
2565
2566         rtpstart = DEFAULT_RTP_START;
2567         rtpend = DEFAULT_RTP_END;
2568         dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2569         strictrtp = STRICT_RTP_OPEN;
2570         if (cfg) {
2571                 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
2572                         rtpstart = atoi(s);
2573                         if (rtpstart < MINIMUM_RTP_PORT)
2574                                 rtpstart = MINIMUM_RTP_PORT;
2575                         if (rtpstart > MAXIMUM_RTP_PORT)
2576                                 rtpstart = MAXIMUM_RTP_PORT;
2577                 }
2578                 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
2579                         rtpend = atoi(s);
2580                         if (rtpend < MINIMUM_RTP_PORT)
2581                                 rtpend = MINIMUM_RTP_PORT;
2582                         if (rtpend > MAXIMUM_RTP_PORT)
2583                                 rtpend = MAXIMUM_RTP_PORT;
2584                 }
2585                 if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
2586                         rtcpinterval = atoi(s);
2587                         if (rtcpinterval == 0)
2588                                 rtcpinterval = 0; /* Just so we're clear... it's zero */
2589                         if (rtcpinterval < RTCP_MIN_INTERVALMS)
2590                                 rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
2591                         if (rtcpinterval > RTCP_MAX_INTERVALMS)
2592                                 rtcpinterval = RTCP_MAX_INTERVALMS;
2593                 }
2594                 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
2595 #ifdef SO_NO_CHECK
2596                         nochecksums = ast_false(s) ? 1 : 0;
2597 #else
2598                         if (ast_false(s))
2599                                 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
2600 #endif
2601                 }
2602                 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
2603                         dtmftimeout = atoi(s);
2604                         if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
2605                                 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
2606                                         dtmftimeout, DEFAULT_DTMF_TIMEOUT);
2607                                 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2608                         };
2609                 }
2610                 if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
2611                         strictrtp = ast_true(s);
2612                 }
2613                 ast_config_destroy(cfg);
2614         }
2615         if (rtpstart >= rtpend) {
2616                 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
2617                 rtpstart = DEFAULT_RTP_START;
2618                 rtpend = DEFAULT_RTP_END;
2619         }
2620         ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
2621         return 0;
2622 }
2623
2624 static int reload_module(void)
2625 {
2626         rtp_reload(1);
2627         return 0;
2628 }
2629
2630 static int load_module(void)
2631 {
2632         if (ast_rtp_engine_register(&asterisk_rtp_engine)) {
2633                 return AST_MODULE_LOAD_DECLINE;
2634         }
2635
2636         if (ast_cli_register_multiple(cli_rtp, ARRAY_LEN(cli_rtp))) {
2637                 ast_rtp_engine_unregister(&asterisk_rtp_engine);
2638                 return AST_MODULE_LOAD_DECLINE;
2639         }
2640
2641         rtp_reload(0);
2642
2643         return AST_MODULE_LOAD_SUCCESS;
2644 }
2645
2646 static int unload_module(void)
2647 {
2648         ast_rtp_engine_unregister(&asterisk_rtp_engine);
2649         ast_cli_unregister_multiple(cli_rtp, ARRAY_LEN(cli_rtp));
2650
2651         return 0;
2652 }
2653
2654 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Asterisk RTP Stack",
2655                 .load = load_module,
2656                 .unload = unload_module,
2657                 .reload = reload_module,
2658                 );