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