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