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