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