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