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