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