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