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