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