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