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