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