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