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