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