This commit introduces COLP/CONP and Redirecting party information into Asterisk.
[asterisk/asterisk.git] / res / res_rtp_asterisk.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!
20  * \file
21  *
22  * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
23  *
24  * \author Mark Spencer <markster@digium.com>
25  *
26  * \note RTP is defined in RFC 3550.
27  */
28
29 #include "asterisk.h"
30
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
32
33 #include <sys/time.h>
34 #include <signal.h>
35 #include <fcntl.h>
36 #include <math.h>
37
38 #include "asterisk/stun.h"
39 #include "asterisk/pbx.h"
40 #include "asterisk/frame.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/acl.h"
43 #include "asterisk/config.h"
44 #include "asterisk/lock.h"
45 #include "asterisk/utils.h"
46 #include "asterisk/netsock.h"
47 #include "asterisk/cli.h"
48 #include "asterisk/manager.h"
49 #include "asterisk/unaligned.h"
50 #include "asterisk/module.h"
51 #include "asterisk/rtp_engine.h"
52
53 #define MAX_TIMESTAMP_SKEW      640
54
55 #define RTP_SEQ_MOD     (1<<16) /*!< A sequence number can't be more than 16 bits */
56 #define RTCP_DEFAULT_INTERVALMS   5000  /*!< Default milli-seconds between RTCP reports we send */
57 #define RTCP_MIN_INTERVALMS       500   /*!< Min milli-seconds between RTCP reports we send */
58 #define RTCP_MAX_INTERVALMS       60000 /*!< Max milli-seconds between RTCP reports we send */
59
60 #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
61 #define DEFAULT_RTP_END 31000  /*!< Default maximum port number to end allocating RTP ports at */
62
63 #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
64 #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
65
66 #define RTCP_PT_FUR     192
67 #define RTCP_PT_SR      200
68 #define RTCP_PT_RR      201
69 #define RTCP_PT_SDES    202
70 #define RTCP_PT_BYE     203
71 #define RTCP_PT_APP     204
72
73 #define RTP_MTU         1200
74
75 #define DEFAULT_DTMF_TIMEOUT 3000       /*!< samples */
76
77 #define ZFONE_PROFILE_ID 0x505a
78
79 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
80
81 static int rtpstart = DEFAULT_RTP_START;                        /*!< First port for RTP sessions (set in rtp.conf) */
82 static int rtpend = DEFAULT_RTP_END;                    /*!< Last port for RTP sessions (set in rtp.conf) */
83 static int rtpdebug;                    /*!< Are we debugging? */
84 static int rtcpdebug;                   /*!< Are we debugging RTCP? */
85 static int rtcpstats;                   /*!< Are we debugging RTCP? */
86 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
87 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
88 static struct sockaddr_in rtcpdebugaddr;        /*!< Debug RTCP packets to/from this host */
89 #ifdef SO_NO_CHECK
90 static int nochecksums;
91 #endif
92 static int strictrtp;
93
94 enum strict_rtp_state {
95         STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
96         STRICT_RTP_LEARN,    /*! Accept next packet as source */
97         STRICT_RTP_CLOSED,   /*! Drop all RTP packets not coming from source that was learned */
98 };
99
100 #define FLAG_3389_WARNING               (1 << 0)
101 #define FLAG_NAT_ACTIVE                 (3 << 1)
102 #define FLAG_NAT_INACTIVE               (0 << 1)
103 #define FLAG_NAT_INACTIVE_NOWARN        (1 << 1)
104 #define FLAG_NEED_MARKER_BIT            (1 << 3)
105 #define FLAG_DTMF_COMPENSATE            (1 << 4)
106
107 /*! \brief RTP session description */
108 struct ast_rtp {
109         int s;
110         struct ast_frame f;
111         unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
112         unsigned int ssrc;              /*!< Synchronization source, RFC 3550, page 10. */
113         unsigned int themssrc;          /*!< Their SSRC */
114         unsigned int rxssrc;
115         unsigned int lastts;
116         unsigned int lastrxts;
117         unsigned int lastividtimestamp;
118         unsigned int lastovidtimestamp;
119         unsigned int lastitexttimestamp;
120         unsigned int lastotexttimestamp;
121         unsigned int lasteventseqn;
122         int lastrxseqno;                /*!< Last received sequence number */
123         unsigned short seedrxseqno;     /*!< What sequence number did they start with?*/
124         unsigned int seedrxts;          /*!< What RTP timestamp did they start with? */
125         unsigned int rxcount;           /*!< How many packets have we received? */
126         unsigned int rxoctetcount;      /*!< How many octets have we received? should be rxcount *160*/
127         unsigned int txcount;           /*!< How many packets have we sent? */
128         unsigned int txoctetcount;      /*!< How many octets have we sent? (txcount*160)*/
129         unsigned int cycles;            /*!< Shifted count of sequence number cycles */
130         double rxjitter;                /*!< Interarrival jitter at the moment */
131         double rxtransit;               /*!< Relative transit time for previous packet */
132         int lasttxformat;
133         int lastrxformat;
134
135         int rtptimeout;                 /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
136         int rtpholdtimeout;             /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
137         int rtpkeepalive;               /*!< Send RTP comfort noice packets for keepalive */
138
139         /* DTMF Reception Variables */
140         char resp;
141         unsigned int lastevent;
142         int dtmfcount;
143         unsigned int dtmfsamples;
144         /* DTMF Transmission Variables */
145         unsigned int lastdigitts;
146         char sending_digit;     /*!< boolean - are we sending digits */
147         char send_digit;        /*!< digit we are sending */
148         int send_payload;
149         int send_duration;
150         unsigned int flags;
151         struct timeval rxcore;
152         struct timeval txcore;
153         double drxcore;                 /*!< The double representation of the first received packet */
154         struct timeval lastrx;          /*!< timeval when we last received a packet */
155         struct timeval dtmfmute;
156         struct ast_smoother *smoother;
157         int *ioid;
158         unsigned short seqno;           /*!< Sequence number, RFC 3550, page 13. */
159         unsigned short rxseqno;
160         struct sched_context *sched;
161         struct io_context *io;
162         void *data;
163         struct ast_rtcp *rtcp;
164         struct ast_rtp *bridged;        /*!< Who we are Packet bridged to */
165
166         enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
167         struct sockaddr_in strict_rtp_address;  /*!< Remote address information for strict RTP purposes */
168
169         struct rtp_red *red;
170 };
171
172 /*!
173  * \brief Structure defining an RTCP session.
174  *
175  * The concept "RTCP session" is not defined in RFC 3550, but since
176  * this structure is analogous to ast_rtp, which tracks a RTP session,
177  * it is logical to think of this as a RTCP session.
178  *
179  * RTCP packet is defined on page 9 of RFC 3550.
180  *
181  */
182 struct ast_rtcp {
183         int rtcp_info;
184         int s;                          /*!< Socket */
185         struct sockaddr_in us;          /*!< Socket representation of the local endpoint. */
186         struct sockaddr_in them;        /*!< Socket representation of the remote endpoint. */
187         unsigned int soc;               /*!< What they told us */
188         unsigned int spc;               /*!< What they told us */
189         unsigned int themrxlsr;         /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
190         struct timeval rxlsr;           /*!< Time when we got their last SR */
191         struct timeval txlsr;           /*!< Time when we sent or last SR*/
192         unsigned int expected_prior;    /*!< no. packets in previous interval */
193         unsigned int received_prior;    /*!< no. packets received in previous interval */
194         int schedid;                    /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
195         unsigned int rr_count;          /*!< number of RRs we've sent, not including report blocks in SR's */
196         unsigned int sr_count;          /*!< number of SRs we've sent */
197         unsigned int lastsrtxcount;     /*!< Transmit packet count when last SR sent */
198         double accumulated_transit;     /*!< accumulated a-dlsr-lsr */
199         double rtt;                     /*!< Last reported rtt */
200         unsigned int reported_jitter;   /*!< The contents of their last jitter entry in the RR */
201         unsigned int reported_lost;     /*!< Reported lost packets in their RR */
202
203         double reported_maxjitter;
204         double reported_minjitter;
205         double reported_normdev_jitter;
206         double reported_stdev_jitter;
207         unsigned int reported_jitter_count;
208
209         double reported_maxlost;
210         double reported_minlost;
211         double reported_normdev_lost;
212         double reported_stdev_lost;
213
214         double rxlost;
215         double maxrxlost;
216         double minrxlost;
217         double normdev_rxlost;
218         double stdev_rxlost;
219         unsigned int rxlost_count;
220
221         double maxrxjitter;
222         double minrxjitter;
223         double normdev_rxjitter;
224         double stdev_rxjitter;
225         unsigned int rxjitter_count;
226         double maxrtt;
227         double minrtt;
228         double normdevrtt;
229         double stdevrtt;
230         unsigned int rtt_count;
231 };
232
233 struct rtp_red {
234         struct ast_frame t140;  /*!< Primary data  */
235         struct ast_frame t140red;   /*!< Redundant t140*/
236         unsigned char pt[AST_RED_MAX_GENERATION];  /*!< Payload types for redundancy data */
237         unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
238         unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
239         int num_gen; /*!< Number of generations */
240         int schedid; /*!< Timer id */
241         int ti; /*!< How long to buffer data before send */
242         unsigned char t140red_data[64000];
243         unsigned char buf_data[64000]; /*!< buffered primary data */
244         int hdrlen;
245         long int prev_ts;
246 };
247
248 /* Forward Declarations */
249 static int ast_rtp_new(struct ast_rtp_instance *instance, struct sched_context *sched, struct sockaddr_in *sin, void *data);
250 static int ast_rtp_destroy(struct ast_rtp_instance *instance);
251 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
252 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
253 static void ast_rtp_new_source(struct ast_rtp_instance *instance);
254 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
255 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
256 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
257 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
258 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct sockaddr_in *sin);
259 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
260 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
261 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
262 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
263 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
264 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct sockaddr_in *suggestion, const char *username);
265 static void ast_rtp_stop(struct ast_rtp_instance *instance);
266
267 /* RTP Engine Declaration */
268 static struct ast_rtp_engine asterisk_rtp_engine = {
269         .name = "asterisk",
270         .new = ast_rtp_new,
271         .destroy = ast_rtp_destroy,
272         .dtmf_begin = ast_rtp_dtmf_begin,
273         .dtmf_end = ast_rtp_dtmf_end,
274         .new_source = ast_rtp_new_source,
275         .write = ast_rtp_write,
276         .read = ast_rtp_read,
277         .prop_set = ast_rtp_prop_set,
278         .fd = ast_rtp_fd,
279         .remote_address_set = ast_rtp_remote_address_set,
280         .red_init = rtp_red_init,
281         .red_buffer = rtp_red_buffer,
282         .local_bridge = ast_rtp_local_bridge,
283         .get_stat = ast_rtp_get_stat,
284         .dtmf_compatible = ast_rtp_dtmf_compatible,
285         .stun_request = ast_rtp_stun_request,
286         .stop = ast_rtp_stop,
287 };
288
289 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
290 {
291         if (!rtpdebug) {
292                 return 0;
293         }
294
295         if (rtpdebugaddr.sin_addr.s_addr) {
296                 if (((ntohs(rtpdebugaddr.sin_port) != 0)
297                      && (rtpdebugaddr.sin_port != addr->sin_port))
298                     || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
299                         return 0;
300         }
301
302         return 1;
303 }
304
305 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
306 {
307         if (!rtcpdebug) {
308                 return 0;
309         }
310
311         if (rtcpdebugaddr.sin_addr.s_addr) {
312                 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
313                      && (rtcpdebugaddr.sin_port != addr->sin_port))
314                     || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
315                         return 0;
316         }
317
318         return 1;
319 }
320
321 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
322 {
323         unsigned int interval;
324         /*! \todo XXX Do a more reasonable calculation on this one
325          * Look in RFC 3550 Section A.7 for an example*/
326         interval = rtcpinterval;
327         return interval;
328 }
329
330 /*! \brief Calculate normal deviation */
331 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
332 {
333         normdev = normdev * sample_count + sample;
334         sample_count++;
335
336         return normdev / sample_count;
337 }
338
339 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
340 {
341 /*
342                 for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
343                 return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
344                 we can compute the sigma^2 and that way we would have to do the sqrt only 1 time at the end and would save another pow 2 compute
345                 optimized formula
346 */
347 #define SQUARE(x) ((x) * (x))
348
349         stddev = sample_count * stddev;
350         sample_count++;
351
352         return stddev +
353                 ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
354                 ( SQUARE(sample - normdev_curent) / sample_count );
355
356 #undef SQUARE
357 }
358
359 static int create_new_socket(const char *type)
360 {
361         int sock = socket(AF_INET, SOCK_DGRAM, 0);
362
363         if (sock < 0) {
364                 if (!type) {
365                         type = "RTP/RTCP";
366                 }
367                 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
368         } else {
369                 long flags = fcntl(sock, F_GETFL);
370                 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
371 #ifdef SO_NO_CHECK
372                 if (nochecksums) {
373                         setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
374                 }
375 #endif
376         }
377
378         return sock;
379 }
380
381 static int ast_rtp_new(struct ast_rtp_instance *instance, struct sched_context *sched, struct sockaddr_in *sin, void *data)
382 {
383         struct ast_rtp *rtp = NULL;
384         int x, startplace;
385
386         /* Create a new RTP structure to hold all of our data */
387         if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
388                 return -1;
389         }
390
391         /* Set default parameters on the newly created RTP structure */
392         rtp->ssrc = ast_random();
393         rtp->seqno = ast_random() & 0xffff;
394         rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
395
396         /* Create a new socket for us to listen on and use */
397         if ((rtp->s = create_new_socket("RTP")) < 0) {
398                 ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
399                 ast_free(rtp);
400                 return -1;
401         }
402
403         /* Now actually find a free RTP port to use */
404         x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
405         x = x & ~1;
406         startplace = x;
407
408         for (;;) {
409                 struct sockaddr_in local_address = { 0, };
410
411                 local_address.sin_port = htons(x);
412                 /* Try to bind, this will tell us whether the port is available or not */
413                 if (!bind(rtp->s, (struct sockaddr*)&local_address, sizeof(local_address))) {
414                         ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
415                         ast_rtp_instance_set_local_address(instance, &local_address);
416                         break;
417                 }
418
419                 x += 2;
420                 if (x > rtpend) {
421                         x = (rtpstart + 1) & ~1;
422                 }
423
424                 /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
425                 if (x == startplace || errno != EADDRINUSE) {
426                         ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
427                         return -1;
428                 }
429         }
430
431         /* Record any information we may need */
432         rtp->sched = sched;
433
434         /* Associate the RTP structure with the RTP instance and be done */
435         ast_rtp_instance_set_data(instance, rtp);
436
437         return 0;
438 }
439
440 static int ast_rtp_destroy(struct ast_rtp_instance *instance)
441 {
442         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
443
444         /* Destroy the smoother that was smoothing out audio if present */
445         if (rtp->smoother) {
446                 ast_smoother_free(rtp->smoother);
447         }
448
449         /* Close our own socket so we no longer get packets */
450         if (rtp->s > -1) {
451                 close(rtp->s);
452         }
453
454         /* Destroy RTCP if it was being used */
455         if (rtp->rtcp) {
456                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
457                 close(rtp->rtcp->s);
458                 ast_free(rtp->rtcp);
459         }
460
461         /* Destroy RED if it was being used */
462         if (rtp->red) {
463                 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
464                 ast_free(rtp->red);
465         }
466
467         /* Finally destroy ourselves */
468         ast_free(rtp);
469
470         return 0;
471 }
472
473 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
474 {
475         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
476         struct sockaddr_in remote_address;
477         int hdrlen = 12, res = 0, i = 0, payload = 101;
478         char data[256];
479         unsigned int *rtpheader = (unsigned int*)data;
480
481         ast_rtp_instance_get_remote_address(instance, &remote_address);
482
483         /* If we have no remote address information bail out now */
484         if (!remote_address.sin_addr.s_addr || !remote_address.sin_port) {
485                 return -1;
486         }
487
488         /* Convert given digit into what we want to transmit */
489         if ((digit <= '9') && (digit >= '0')) {
490                 digit -= '0';
491         } else if (digit == '*') {
492                 digit = 10;
493         } else if (digit == '#') {
494                 digit = 11;
495         } else if ((digit >= 'A') && (digit <= 'D')) {
496                 digit = digit - 'A' + 12;
497         } else if ((digit >= 'a') && (digit <= 'd')) {
498                 digit = digit - 'a' + 12;
499         } else {
500                 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
501                 return -1;
502         }
503
504         /* Grab the payload that they expect the RFC2833 packet to be received in */
505         payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, AST_RTP_DTMF);
506
507         rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
508         rtp->send_duration = 160;
509         rtp->lastdigitts = rtp->lastts + rtp->send_duration;
510
511         /* Create the actual packet that we will be sending */
512         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
513         rtpheader[1] = htonl(rtp->lastdigitts);
514         rtpheader[2] = htonl(rtp->ssrc);
515
516         /* Actually send the packet */
517         for (i = 0; i < 2; i++) {
518                 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
519                 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &remote_address, sizeof(remote_address));
520                 if (res < 0) {
521                         ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
522                                 ast_inet_ntoa(remote_address.sin_addr), ntohs(remote_address.sin_port), strerror(errno));
523                 }
524                 if (rtp_debug_test_addr(&remote_address)) {
525                         ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
526                                     ast_inet_ntoa(remote_address.sin_addr),
527                                     ntohs(remote_address.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
528                 }
529                 rtp->seqno++;
530                 rtp->send_duration += 160;
531                 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
532         }
533
534         /* Record that we are in the process of sending a digit and information needed to continue doing so */
535         rtp->sending_digit = 1;
536         rtp->send_digit = digit;
537         rtp->send_payload = payload;
538
539         return 0;
540 }
541
542 static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
543 {
544         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
545         struct sockaddr_in remote_address;
546         int hdrlen = 12, res = 0;
547         char data[256];
548         unsigned int *rtpheader = (unsigned int*)data;
549
550         ast_rtp_instance_get_remote_address(instance, &remote_address);
551
552         /* Make sure we know where the other side is so we can send them the packet */
553         if (!remote_address.sin_addr.s_addr || !remote_address.sin_port) {
554                 return -1;
555         }
556
557         /* Actually create the packet we will be sending */
558         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
559         rtpheader[1] = htonl(rtp->lastdigitts);
560         rtpheader[2] = htonl(rtp->ssrc);
561         rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
562         rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
563
564         /* Boom, send it on out */
565         res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &remote_address, sizeof(remote_address));
566         if (res < 0) {
567                 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
568                         ast_inet_ntoa(remote_address.sin_addr),
569                         ntohs(remote_address.sin_port), strerror(errno));
570         }
571
572         if (rtp_debug_test_addr(&remote_address)) {
573                 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
574                             ast_inet_ntoa(remote_address.sin_addr),
575                             ntohs(remote_address.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
576         }
577
578         /* And now we increment some values for the next time we swing by */
579         rtp->seqno++;
580         rtp->send_duration += 160;
581
582         return 0;
583 }
584
585 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
586 {
587         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
588         struct sockaddr_in remote_address;
589         int hdrlen = 12, res = 0, i = 0;
590         char data[256];
591         unsigned int *rtpheader = (unsigned int*)data;
592
593         ast_rtp_instance_get_remote_address(instance, &remote_address);
594
595         /* Make sure we know where the remote side is so we can send them the packet we construct */
596         if (!remote_address.sin_addr.s_addr || !remote_address.sin_port) {
597                 return -1;
598         }
599
600         /* Convert the given digit to the one we are going to send */
601         if ((digit <= '9') && (digit >= '0')) {
602                 digit -= '0';
603         } else if (digit == '*') {
604                 digit = 10;
605         } else if (digit == '#') {
606                 digit = 11;
607         } else if ((digit >= 'A') && (digit <= 'D')) {
608                 digit = digit - 'A' + 12;
609         } else if ((digit >= 'a') && (digit <= 'd')) {
610                 digit = digit - 'a' + 12;
611         } else {
612                 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
613                 return -1;
614         }
615
616         rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
617
618         /* Construct the packet we are going to send */
619         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
620         rtpheader[1] = htonl(rtp->lastdigitts);
621         rtpheader[2] = htonl(rtp->ssrc);
622         rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
623         rtpheader[3] |= htonl((1 << 23));
624         rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
625
626         /* Send it 3 times, that's the magical number */
627         for (i = 0; i < 3; i++) {
628                 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &remote_address, sizeof(remote_address));
629                 if (res < 0) {
630                         ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
631                                 ast_inet_ntoa(remote_address.sin_addr),
632                                 ntohs(remote_address.sin_port), strerror(errno));
633                 }
634                 if (rtp_debug_test_addr(&remote_address)) {
635                         ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
636                                     ast_inet_ntoa(remote_address.sin_addr),
637                                     ntohs(remote_address.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
638                 }
639         }
640
641         /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
642         rtp->lastts += rtp->send_duration;
643         rtp->sending_digit = 0;
644         rtp->send_digit = 0;
645
646         return 0;
647 }
648
649 static void ast_rtp_new_source(struct ast_rtp_instance *instance)
650 {
651         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
652
653         /* We simply set this bit so that the next packet sent will have the marker bit turned on */
654         ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
655
656         return;
657 }
658
659 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
660 {
661         struct timeval t;
662         long ms;
663
664         if (ast_tvzero(rtp->txcore)) {
665                 rtp->txcore = ast_tvnow();
666                 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
667         }
668
669         t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
670         if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
671                 ms = 0;
672         }
673         rtp->txcore = t;
674
675         return (unsigned int) ms;
676 }
677
678 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
679 {
680         unsigned int sec, usec, frac;
681         sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
682         usec = tv.tv_usec;
683         frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
684         *msw = sec;
685         *lsw = frac;
686 }
687
688 /*! \brief Send RTCP recipient's report */
689 static int ast_rtcp_write_rr(const void *data)
690 {
691         struct ast_rtp *rtp = (struct ast_rtp *)data;
692         int res;
693         int len = 32;
694         unsigned int lost;
695         unsigned int extended;
696         unsigned int expected;
697         unsigned int expected_interval;
698         unsigned int received_interval;
699         int lost_interval;
700         struct timeval now;
701         unsigned int *rtcpheader;
702         char bdata[1024];
703         struct timeval dlsr;
704         int fraction;
705
706         double rxlost_current;
707
708         if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
709                 return 0;
710
711         if (!rtp->rtcp->them.sin_addr.s_addr) {
712                 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
713                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
714                 return 0;
715         }
716
717         extended = rtp->cycles + rtp->lastrxseqno;
718         expected = extended - rtp->seedrxseqno + 1;
719         lost = expected - rtp->rxcount;
720         expected_interval = expected - rtp->rtcp->expected_prior;
721         rtp->rtcp->expected_prior = expected;
722         received_interval = rtp->rxcount - rtp->rtcp->received_prior;
723         rtp->rtcp->received_prior = rtp->rxcount;
724         lost_interval = expected_interval - received_interval;
725
726         if (lost_interval <= 0)
727                 rtp->rtcp->rxlost = 0;
728         else rtp->rtcp->rxlost = rtp->rtcp->rxlost;
729         if (rtp->rtcp->rxlost_count == 0)
730                 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
731         if (lost_interval < rtp->rtcp->minrxlost)
732                 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
733         if (lost_interval > rtp->rtcp->maxrxlost)
734                 rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
735
736         rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->rxlost_count);
737         rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->normdev_rxlost, rxlost_current, rtp->rtcp->rxlost_count);
738         rtp->rtcp->normdev_rxlost = rxlost_current;
739         rtp->rtcp->rxlost_count++;
740
741         if (expected_interval == 0 || lost_interval <= 0)
742                 fraction = 0;
743         else
744                 fraction = (lost_interval << 8) / expected_interval;
745         gettimeofday(&now, NULL);
746         timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
747         rtcpheader = (unsigned int *)bdata;
748         rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
749         rtcpheader[1] = htonl(rtp->ssrc);
750         rtcpheader[2] = htonl(rtp->themssrc);
751         rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
752         rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
753         rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
754         rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
755         rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
756
757         /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
758           it can change mid call, and SDES can't) */
759         rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
760         rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
761         rtcpheader[(len/4)+2] = htonl(0x01 << 24);              /* Empty for the moment */
762         len += 12;
763
764         res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
765
766         if (res < 0) {
767                 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
768                 /* Remove the scheduler */
769                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
770                 return 0;
771         }
772
773         rtp->rtcp->rr_count++;
774         if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
775                 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
776                         "  Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
777                         "  IA jitter: %.4f\n"
778                         "  Their last SR: %u\n"
779                             "  DLSR: %4.4f (sec)\n\n",
780                             ast_inet_ntoa(rtp->rtcp->them.sin_addr),
781                             ntohs(rtp->rtcp->them.sin_port),
782                             rtp->ssrc, rtp->themssrc, fraction, lost,
783                             rtp->rxjitter,
784                             rtp->rtcp->themrxlsr,
785                             (double)(ntohl(rtcpheader[7])/65536.0));
786         }
787
788         return res;
789 }
790
791 /*! \brief Send RTCP sender's report */
792 static int ast_rtcp_write_sr(const void *data)
793 {
794         struct ast_rtp *rtp = (struct ast_rtp *)data;
795         int res;
796         int len = 0;
797         struct timeval now;
798         unsigned int now_lsw;
799         unsigned int now_msw;
800         unsigned int *rtcpheader;
801         unsigned int lost;
802         unsigned int extended;
803         unsigned int expected;
804         unsigned int expected_interval;
805         unsigned int received_interval;
806         int lost_interval;
807         int fraction;
808         struct timeval dlsr;
809         char bdata[512];
810
811         /* Commented condition is always not NULL if rtp->rtcp is not NULL */
812         if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
813                 return 0;
814
815         if (!rtp->rtcp->them.sin_addr.s_addr) {  /* This'll stop rtcp for this rtp session */
816                 ast_verbose("RTCP SR transmission error, rtcp halted\n");
817                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
818                 return 0;
819         }
820
821         gettimeofday(&now, NULL);
822         timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
823         rtcpheader = (unsigned int *)bdata;
824         rtcpheader[1] = htonl(rtp->ssrc);               /* Our SSRC */
825         rtcpheader[2] = htonl(now_msw);                 /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
826         rtcpheader[3] = htonl(now_lsw);                 /* now, LSW */
827         rtcpheader[4] = htonl(rtp->lastts);             /* FIXME shouldn't be that, it should be now */
828         rtcpheader[5] = htonl(rtp->txcount);            /* No. packets sent */
829         rtcpheader[6] = htonl(rtp->txoctetcount);       /* No. bytes sent */
830         len += 28;
831
832         extended = rtp->cycles + rtp->lastrxseqno;
833         expected = extended - rtp->seedrxseqno + 1;
834         if (rtp->rxcount > expected)
835                 expected += rtp->rxcount - expected;
836         lost = expected - rtp->rxcount;
837         expected_interval = expected - rtp->rtcp->expected_prior;
838         rtp->rtcp->expected_prior = expected;
839         received_interval = rtp->rxcount - rtp->rtcp->received_prior;
840         rtp->rtcp->received_prior = rtp->rxcount;
841         lost_interval = expected_interval - received_interval;
842         if (expected_interval == 0 || lost_interval <= 0)
843                 fraction = 0;
844         else
845                 fraction = (lost_interval << 8) / expected_interval;
846         timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
847         rtcpheader[7] = htonl(rtp->themssrc);
848         rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
849         rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
850         rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
851         rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
852         rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
853         len += 24;
854
855         rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
856
857         /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
858         /* it can change mid call, and SDES can't) */
859         rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
860         rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
861         rtcpheader[(len/4)+2] = htonl(0x01 << 24);                    /* Empty for the moment */
862         len += 12;
863
864         res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
865         if (res < 0) {
866                 ast_log(LOG_ERROR, "RTCP SR transmission error to %s:%d, rtcp halted %s\n",ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port), strerror(errno));
867                 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
868                 return 0;
869         }
870
871         /* FIXME Don't need to get a new one */
872         gettimeofday(&rtp->rtcp->txlsr, NULL);
873         rtp->rtcp->sr_count++;
874
875         rtp->rtcp->lastsrtxcount = rtp->txcount;
876
877         if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
878                 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
879                 ast_verbose("  Our SSRC: %u\n", rtp->ssrc);
880                 ast_verbose("  Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
881                 ast_verbose("  Sent(RTP): %u\n", rtp->lastts);
882                 ast_verbose("  Sent packets: %u\n", rtp->txcount);
883                 ast_verbose("  Sent octets: %u\n", rtp->txoctetcount);
884                 ast_verbose("  Report block:\n");
885                 ast_verbose("  Fraction lost: %u\n", fraction);
886                 ast_verbose("  Cumulative loss: %u\n", lost);
887                 ast_verbose("  IA jitter: %.4f\n", rtp->rxjitter);
888                 ast_verbose("  Their last SR: %u\n", rtp->rtcp->themrxlsr);
889                 ast_verbose("  DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
890         }
891         manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To %s:%d\r\n"
892                                             "OurSSRC: %u\r\n"
893                                             "SentNTP: %u.%010u\r\n"
894                                             "SentRTP: %u\r\n"
895                                             "SentPackets: %u\r\n"
896                                             "SentOctets: %u\r\n"
897                                             "ReportBlock:\r\n"
898                                             "FractionLost: %u\r\n"
899                                             "CumulativeLoss: %u\r\n"
900                                             "IAJitter: %.4f\r\n"
901                                             "TheirLastSR: %u\r\n"
902                       "DLSR: %4.4f (sec)\r\n",
903                       ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port),
904                       rtp->ssrc,
905                       (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
906                       rtp->lastts,
907                       rtp->txcount,
908                       rtp->txoctetcount,
909                       fraction,
910                       lost,
911                       rtp->rxjitter,
912                       rtp->rtcp->themrxlsr,
913                       (double)(ntohl(rtcpheader[12])/65536.0));
914         return res;
915 }
916
917 /*! \brief Write and RTCP packet to the far end
918  * \note Decide if we are going to send an SR (with Reception Block) or RR
919  * RR is sent if we have not sent any rtp packets in the previous interval */
920 static int ast_rtcp_write(const void *data)
921 {
922         struct ast_rtp *rtp = (struct ast_rtp *)data;
923         int res;
924
925         if (!rtp || !rtp->rtcp)
926                 return 0;
927
928         if (rtp->txcount > rtp->rtcp->lastsrtxcount)
929                 res = ast_rtcp_write_sr(data);
930         else
931                 res = ast_rtcp_write_rr(data);
932
933         return res;
934 }
935
936 static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
937 {
938         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
939         int pred, mark = 0;
940         unsigned int ms = calc_txstamp(rtp, &frame->delivery);
941         struct sockaddr_in remote_address;
942
943         if (rtp->sending_digit) {
944                 return 0;
945         }
946
947         if (frame->frametype == AST_FRAME_VOICE) {
948                 pred = rtp->lastts + frame->samples;
949
950                 /* Re-calculate last TS */
951                 rtp->lastts = rtp->lastts + ms * 8;
952                 if (ast_tvzero(frame->delivery)) {
953                         /* If this isn't an absolute delivery time, Check if it is close to our prediction,
954                            and if so, go with our prediction */
955                         if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
956                                 rtp->lastts = pred;
957                         } else {
958                                 ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
959                                 mark = 1;
960                         }
961                 }
962         } else if (frame->frametype == AST_FRAME_VIDEO) {
963                 mark = frame->subclass & 0x1;
964                 pred = rtp->lastovidtimestamp + frame->samples;
965                 /* Re-calculate last TS */
966                 rtp->lastts = rtp->lastts + ms * 90;
967                 /* If it's close to our prediction, go for it */
968                 if (ast_tvzero(frame->delivery)) {
969                         if (abs(rtp->lastts - pred) < 7200) {
970                                 rtp->lastts = pred;
971                                 rtp->lastovidtimestamp += frame->samples;
972                         } else {
973                                 ast_debug(3, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
974                                 rtp->lastovidtimestamp = rtp->lastts;
975                         }
976                 }
977         } else {
978                 pred = rtp->lastotexttimestamp + frame->samples;
979                 /* Re-calculate last TS */
980                 rtp->lastts = rtp->lastts + ms * 90;
981                 /* If it's close to our prediction, go for it */
982                 if (ast_tvzero(frame->delivery)) {
983                         if (abs(rtp->lastts - pred) < 7200) {
984                                 rtp->lastts = pred;
985                                 rtp->lastotexttimestamp += frame->samples;
986                         } else {
987                                 ast_debug(3, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
988                                 rtp->lastotexttimestamp = rtp->lastts;
989                         }
990                 }
991         }
992
993         /* If we have been explicitly told to set the marker bit then do so */
994         if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
995                 mark = 1;
996                 ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
997         }
998
999         /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
1000         if (rtp->lastts > rtp->lastdigitts) {
1001                 rtp->lastdigitts = rtp->lastts;
1002         }
1003
1004         if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
1005                 rtp->lastts = frame->ts * 8;
1006         }
1007
1008         ast_rtp_instance_get_remote_address(instance, &remote_address);
1009
1010         /* If we know the remote address construct a packet and send it out */
1011         if (remote_address.sin_port && remote_address.sin_addr.s_addr) {
1012                 int hdrlen = 12, res;
1013                 unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
1014
1015                 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
1016                 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
1017                 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
1018
1019                 if ((res = sendto(rtp->s, (void *)rtpheader, frame->datalen + hdrlen, 0, (struct sockaddr *)&remote_address, sizeof(remote_address))) < 0) {
1020                         if (!ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1021                                 ast_debug(1, "RTP Transmission error of packet %d to %s:%d: %s\n", rtp->seqno, ast_inet_ntoa(remote_address.sin_addr), ntohs(remote_address.sin_port), strerror(errno));
1022                         } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
1023                                 /* Only give this error message once if we are not RTP debugging */
1024                                 if (option_debug || rtpdebug)
1025                                         ast_debug(0, "RTP NAT: Can't write RTP to private address %s:%d, waiting for other end to send audio...\n", ast_inet_ntoa(remote_address.sin_addr), ntohs(remote_address.sin_port));
1026                                 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
1027                         }
1028                 } else {
1029                         rtp->txcount++;
1030                         rtp->txoctetcount += (res - hdrlen);
1031
1032                         if (rtp->rtcp && rtp->rtcp->schedid < 1) {
1033                                 ast_debug(1, "Starting RTCP transmission on RTP instance '%p'\n", instance);
1034                                 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1035                         }
1036                 }
1037
1038                 if (rtp_debug_test_addr(&remote_address)) {
1039                         ast_verbose("Sent RTP packet to      %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1040                                     ast_inet_ntoa(remote_address.sin_addr), ntohs(remote_address.sin_port), codec, rtp->seqno, rtp->lastts, res - hdrlen);
1041                 }
1042         }
1043
1044         rtp->seqno++;
1045
1046         return 0;
1047 }
1048
1049 static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
1050         unsigned char *data = red->t140red.data.ptr;
1051         int len = 0;
1052         int i;
1053
1054         /* replace most aged generation */
1055         if (red->len[0]) {
1056                 for (i = 1; i < red->num_gen+1; i++)
1057                         len += red->len[i];
1058
1059                 memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
1060         }
1061
1062         /* Store length of each generation and primary data length*/
1063         for (i = 0; i < red->num_gen; i++)
1064                 red->len[i] = red->len[i+1];
1065         red->len[i] = red->t140.datalen;
1066
1067         /* write each generation length in red header */
1068         len = red->hdrlen;
1069         for (i = 0; i < red->num_gen; i++)
1070                 len += data[i*4+3] = red->len[i];
1071
1072         /* add primary data to buffer */
1073         memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
1074         red->t140red.datalen = len + red->t140.datalen;
1075
1076         /* no primary data and no generations to send */
1077         if (len == red->hdrlen && !red->t140.datalen)
1078                 return NULL;
1079
1080         /* reset t.140 buffer */
1081         red->t140.datalen = 0;
1082
1083         return &red->t140red;
1084 }
1085
1086 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
1087 {
1088         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1089         struct sockaddr_in remote_address;
1090         int codec, subclass;
1091
1092         ast_rtp_instance_get_remote_address(instance, &remote_address);
1093
1094         /* If we don't actually know the remote address don't even bother doing anything */
1095         if (!remote_address.sin_addr.s_addr) {
1096                 ast_debug(1, "No remote address on RTP instance '%p' so dropping frame\n", instance);
1097                 return -1;
1098         }
1099
1100         /* If there is no data length we can't very well send the packet */
1101         if (!frame->datalen) {
1102                 ast_debug(1, "Received frame with no data for RTP instance '%p' so dropping frame\n", instance);
1103                 return -1;
1104         }
1105
1106         /* If the packet is not one our RTP stack supports bail out */
1107         if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
1108                 ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
1109                 return -1;
1110         }
1111
1112         if (rtp->red) {
1113                 /* return 0; */
1114                 /* no primary data or generations to send */
1115                 if ((frame = red_t140_to_red(rtp->red)) == NULL)
1116                         return 0;
1117         }
1118
1119         /* Grab the subclass and look up the payload we are going to use */
1120         subclass = frame->subclass;
1121         if (frame->frametype == AST_FRAME_VIDEO) {
1122                 subclass &= ~0x1;
1123         }
1124         if ((codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 1, subclass)) < 0) {
1125                 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(frame->subclass));
1126                 return -1;
1127         }
1128
1129         /* Oh dear, if the format changed we will have to set up a new smoother */
1130         if (rtp->lasttxformat != subclass) {
1131                 ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
1132                 rtp->lasttxformat = subclass;
1133                 if (rtp->smoother) {
1134                         ast_smoother_free(rtp->smoother);
1135                         rtp->smoother = NULL;
1136                 }
1137         }
1138
1139         /* If no smoother is present see if we have to set one up */
1140         if (!rtp->smoother) {
1141                 struct ast_format_list fmt = ast_codec_pref_getsize(&ast_rtp_instance_get_codecs(instance)->pref, subclass);
1142
1143                 switch (subclass) {
1144                 case AST_FORMAT_SPEEX:
1145                 case AST_FORMAT_G723_1:
1146                 case AST_FORMAT_SIREN7:
1147                 case AST_FORMAT_SIREN14:
1148                         /* these are all frame-based codecs and cannot be safely run through
1149                            a smoother */
1150                         break;
1151                 default:
1152                         if (fmt.inc_ms) {
1153                                 if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
1154                                         ast_log(LOG_WARNING, "Unable to create smoother: format %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
1155                                         return -1;
1156                                 }
1157                                 if (fmt.flags) {
1158                                         ast_smoother_set_flags(rtp->smoother, fmt.flags);
1159                                 }
1160                                 ast_debug(1, "Created smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
1161                         }
1162                 }
1163         }
1164
1165         /* Feed audio frames into the actual function that will create a frame and send it */
1166         if (rtp->smoother) {
1167                 struct ast_frame *f;
1168
1169                 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
1170                         ast_smoother_feed_be(rtp->smoother, frame);
1171                 } else {
1172                         ast_smoother_feed(rtp->smoother, frame);
1173                 }
1174
1175                 while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
1176                         if (f->subclass == AST_FORMAT_G722) {
1177                                 f->samples /= 2;
1178                         }
1179
1180                         ast_rtp_raw_write(instance, f, codec);
1181                 }
1182         } else {
1183                 int hdrlen = 12;
1184                 struct ast_frame *f = NULL;
1185
1186                 if (frame->offset < hdrlen) {
1187                         f = ast_frdup(frame);
1188                 } else {
1189                         f = frame;
1190                 }
1191                 if (f->data.ptr) {
1192                         ast_rtp_raw_write(instance, f, codec);
1193                 }
1194                 if (f != frame) {
1195                         ast_frfree(f);
1196                 }
1197
1198         }
1199
1200         return 0;
1201 }
1202
1203 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
1204 {
1205         struct timeval now;
1206         double transit;
1207         double current_time;
1208         double d;
1209         double dtv;
1210         double prog;
1211
1212         double normdev_rxjitter_current;
1213         if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
1214                 gettimeofday(&rtp->rxcore, NULL);
1215                 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
1216                 /* map timestamp to a real time */
1217                 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
1218                 rtp->rxcore.tv_sec -= timestamp / 8000;
1219                 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
1220                 /* Round to 0.1ms for nice, pretty timestamps */
1221                 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
1222                 if (rtp->rxcore.tv_usec < 0) {
1223                         /* Adjust appropriately if necessary */
1224                         rtp->rxcore.tv_usec += 1000000;
1225                         rtp->rxcore.tv_sec -= 1;
1226                 }
1227         }
1228
1229         gettimeofday(&now,NULL);
1230         /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
1231         tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
1232         tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
1233         if (tv->tv_usec >= 1000000) {
1234                 tv->tv_usec -= 1000000;
1235                 tv->tv_sec += 1;
1236         }
1237         prog = (double)((timestamp-rtp->seedrxts)/8000.);
1238         dtv = (double)rtp->drxcore + (double)(prog);
1239         current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
1240         transit = current_time - dtv;
1241         d = transit - rtp->rxtransit;
1242         rtp->rxtransit = transit;
1243         if (d<0)
1244                 d=-d;
1245         rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1246
1247         if (rtp->rtcp) {
1248                 if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
1249                         rtp->rtcp->maxrxjitter = rtp->rxjitter;
1250                 if (rtp->rtcp->rxjitter_count == 1)
1251                         rtp->rtcp->minrxjitter = rtp->rxjitter;
1252                 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1253                         rtp->rtcp->minrxjitter = rtp->rxjitter;
1254
1255                 normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
1256                 rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
1257
1258                 rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
1259                 rtp->rtcp->rxjitter_count++;
1260         }
1261 }
1262
1263 static struct ast_frame *send_dtmf(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
1264 {
1265         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1266         struct sockaddr_in remote_address;
1267
1268         ast_rtp_instance_get_remote_address(instance, &remote_address);
1269
1270         if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
1271                 ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(remote_address.sin_addr));
1272                 rtp->resp = 0;
1273                 rtp->dtmfsamples = 0;
1274                 return &ast_null_frame;
1275         }
1276         ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(remote_address.sin_addr));
1277         if (rtp->resp == 'X') {
1278                 rtp->f.frametype = AST_FRAME_CONTROL;
1279                 rtp->f.subclass = AST_CONTROL_FLASH;
1280         } else {
1281                 rtp->f.frametype = type;
1282                 rtp->f.subclass = rtp->resp;
1283         }
1284         rtp->f.datalen = 0;
1285         rtp->f.samples = 0;
1286         rtp->f.mallocd = 0;
1287         rtp->f.src = "RTP";
1288
1289         return &rtp->f;
1290 }
1291
1292 static struct ast_frame *process_dtmf_rfc2833(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct sockaddr_in *sin, int payloadtype, int mark)
1293 {
1294         struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1295         struct sockaddr_in remote_address;
1296         unsigned int event, event_end, samples;
1297         char resp = 0;
1298         struct ast_frame *f = NULL;
1299
1300         ast_rtp_instance_get_remote_address(instance, &remote_address);
1301
1302         /* Figure out event, event end, and samples */
1303         event = ntohl(*((unsigned int *)(data)));
1304         event >>= 24;
1305         event_end = ntohl(*((unsigned int *)(data)));
1306         event_end <<= 8;
1307         event_end >>= 24;
1308         samples = ntohl(*((unsigned int *)(data)));
1309         samples &= 0xFFFF;
1310
1311         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),
1312                     ntohs(remote_address.sin_port), payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
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;
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;
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;
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                 );