2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2008, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
22 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
24 * \author Mark Spencer <markster@digium.com>
26 * \note RTP is defined in RFC 3550.
28 * \ingroup rtp_engines
32 <support_level>core</support_level>
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43 #include "asterisk/stun.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/frame.h"
46 #include "asterisk/channel.h"
47 #include "asterisk/acl.h"
48 #include "asterisk/config.h"
49 #include "asterisk/lock.h"
50 #include "asterisk/utils.h"
51 #include "asterisk/cli.h"
52 #include "asterisk/manager.h"
53 #include "asterisk/unaligned.h"
54 #include "asterisk/module.h"
55 #include "asterisk/rtp_engine.h"
57 #define MAX_TIMESTAMP_SKEW 640
59 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
60 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
61 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
62 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
64 #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
65 #define DEFAULT_RTP_END 31000 /*!< Default maximum port number to end allocating RTP ports at */
67 #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
68 #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
70 #define RTCP_PT_FUR 192
71 #define RTCP_PT_SR 200
72 #define RTCP_PT_RR 201
73 #define RTCP_PT_SDES 202
74 #define RTCP_PT_BYE 203
75 #define RTCP_PT_APP 204
79 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
81 #define ZFONE_PROFILE_ID 0x505a
83 extern struct ast_srtp_res *res_srtp;
84 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
86 static int rtpstart = DEFAULT_RTP_START; /*!< First port for RTP sessions (set in rtp.conf) */
87 static int rtpend = DEFAULT_RTP_END; /*!< Last port for RTP sessions (set in rtp.conf) */
88 static int rtpdebug; /*!< Are we debugging? */
89 static int rtcpdebug; /*!< Are we debugging RTCP? */
90 static int rtcpstats; /*!< Are we debugging RTCP? */
91 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
92 static struct ast_sockaddr rtpdebugaddr; /*!< Debug packets to/from this host */
93 static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
94 static int rtpdebugport; /*< Debug only RTP packets from IP or IP+Port if port is > 0 */
95 static int rtcpdebugport; /*< Debug only RTCP packets from IP or IP+Port if port is > 0 */
97 static int nochecksums;
101 enum strict_rtp_state {
102 STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
103 STRICT_RTP_LEARN, /*! Accept next packet as source */
104 STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
107 #define FLAG_3389_WARNING (1 << 0)
108 #define FLAG_NAT_ACTIVE (3 << 1)
109 #define FLAG_NAT_INACTIVE (0 << 1)
110 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
111 #define FLAG_NEED_MARKER_BIT (1 << 3)
112 #define FLAG_DTMF_COMPENSATE (1 << 4)
114 /*! \brief RTP session description */
118 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
119 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
120 unsigned int themssrc; /*!< Their SSRC */
123 unsigned int lastrxts;
124 unsigned int lastividtimestamp;
125 unsigned int lastovidtimestamp;
126 unsigned int lastitexttimestamp;
127 unsigned int lastotexttimestamp;
128 unsigned int lasteventseqn;
129 int lastrxseqno; /*!< Last received sequence number */
130 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
131 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
132 unsigned int rxcount; /*!< How many packets have we received? */
133 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
134 unsigned int txcount; /*!< How many packets have we sent? */
135 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
136 unsigned int cycles; /*!< Shifted count of sequence number cycles */
137 double rxjitter; /*!< Interarrival jitter at the moment */
138 double rxtransit; /*!< Relative transit time for previous packet */
139 struct ast_format lasttxformat;
140 struct ast_format lastrxformat;
142 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
143 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
144 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
146 /* DTMF Reception Variables */
148 unsigned int lastevent;
149 unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
150 unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
151 unsigned int dtmfsamples;
152 enum ast_rtp_dtmf_mode dtmfmode;/*!< The current DTMF mode of the RTP stream */
153 /* DTMF Transmission Variables */
154 unsigned int lastdigitts;
155 char sending_digit; /*!< boolean - are we sending digits */
156 char send_digit; /*!< digit we are sending */
160 struct timeval rxcore;
161 struct timeval txcore;
162 double drxcore; /*!< The double representation of the first received packet */
163 struct timeval lastrx; /*!< timeval when we last received a packet */
164 struct timeval dtmfmute;
165 struct ast_smoother *smoother;
167 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
168 unsigned short rxseqno;
169 struct ast_sched_context *sched;
170 struct io_context *io;
172 struct ast_rtcp *rtcp;
173 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
175 enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
176 struct ast_sockaddr strict_rtp_address; /*!< Remote address information for strict RTP purposes */
177 struct ast_sockaddr alt_rtp_address; /*!<Alternate remote address information */
183 * \brief Structure defining an RTCP session.
185 * The concept "RTCP session" is not defined in RFC 3550, but since
186 * this structure is analogous to ast_rtp, which tracks a RTP session,
187 * it is logical to think of this as a RTCP session.
189 * RTCP packet is defined on page 9 of RFC 3550.
194 int s; /*!< Socket */
195 struct ast_sockaddr us; /*!< Socket representation of the local endpoint. */
196 struct ast_sockaddr them; /*!< Socket representation of the remote endpoint. */
197 unsigned int soc; /*!< What they told us */
198 unsigned int spc; /*!< What they told us */
199 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
200 struct timeval rxlsr; /*!< Time when we got their last SR */
201 struct timeval txlsr; /*!< Time when we sent or last SR*/
202 unsigned int expected_prior; /*!< no. packets in previous interval */
203 unsigned int received_prior; /*!< no. packets received in previous interval */
204 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
205 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
206 unsigned int sr_count; /*!< number of SRs we've sent */
207 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
208 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
209 double rtt; /*!< Last reported rtt */
210 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
211 unsigned int reported_lost; /*!< Reported lost packets in their RR */
213 double reported_maxjitter;
214 double reported_minjitter;
215 double reported_normdev_jitter;
216 double reported_stdev_jitter;
217 unsigned int reported_jitter_count;
219 double reported_maxlost;
220 double reported_minlost;
221 double reported_normdev_lost;
222 double reported_stdev_lost;
227 double normdev_rxlost;
229 unsigned int rxlost_count;
233 double normdev_rxjitter;
234 double stdev_rxjitter;
235 unsigned int rxjitter_count;
240 unsigned int rtt_count;
244 struct ast_frame t140; /*!< Primary data */
245 struct ast_frame t140red; /*!< Redundant t140*/
246 unsigned char pt[AST_RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
247 unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
248 unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
249 int num_gen; /*!< Number of generations */
250 int schedid; /*!< Timer id */
251 int ti; /*!< How long to buffer data before send */
252 unsigned char t140red_data[64000];
253 unsigned char buf_data[64000]; /*!< buffered primary data */
258 AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
260 /* Forward Declarations */
261 static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
262 static int ast_rtp_destroy(struct ast_rtp_instance *instance);
263 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
264 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
265 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
266 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
267 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
268 static void ast_rtp_update_source(struct ast_rtp_instance *instance);
269 static void ast_rtp_change_source(struct ast_rtp_instance *instance);
270 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
271 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
272 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
273 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
274 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
275 static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
276 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
277 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
278 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
279 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
280 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
281 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
282 static void ast_rtp_stop(struct ast_rtp_instance *instance);
283 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
284 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
286 /* RTP Engine Declaration */
287 static struct ast_rtp_engine asterisk_rtp_engine = {
290 .destroy = ast_rtp_destroy,
291 .dtmf_begin = ast_rtp_dtmf_begin,
292 .dtmf_end = ast_rtp_dtmf_end,
293 .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
294 .dtmf_mode_set = ast_rtp_dtmf_mode_set,
295 .dtmf_mode_get = ast_rtp_dtmf_mode_get,
296 .update_source = ast_rtp_update_source,
297 .change_source = ast_rtp_change_source,
298 .write = ast_rtp_write,
299 .read = ast_rtp_read,
300 .prop_set = ast_rtp_prop_set,
302 .remote_address_set = ast_rtp_remote_address_set,
303 .alt_remote_address_set = ast_rtp_alt_remote_address_set,
304 .red_init = rtp_red_init,
305 .red_buffer = rtp_red_buffer,
306 .local_bridge = ast_rtp_local_bridge,
307 .get_stat = ast_rtp_get_stat,
308 .dtmf_compatible = ast_rtp_dtmf_compatible,
309 .stun_request = ast_rtp_stun_request,
310 .stop = ast_rtp_stop,
311 .qos = ast_rtp_qos_set,
312 .sendcng = ast_rtp_sendcng,
315 static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
320 if (!ast_sockaddr_isnull(&rtpdebugaddr)) {
322 return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
324 return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
331 static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
336 if (!ast_sockaddr_isnull(&rtcpdebugaddr)) {
338 return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
340 return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
347 static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
350 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
351 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
353 if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
357 if (res_srtp && srtp && res_srtp->unprotect(srtp, buf, &len, rtcp) < 0) {
364 static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
366 return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
369 static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
371 return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
374 static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
378 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
379 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
381 if (res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
385 return ast_sendto(rtcp ? rtp->rtcp->s : rtp->s, temp, len, flags, sa);
388 static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
390 return __rtp_sendto(instance, buf, size, flags, sa, 1);
393 static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
395 return __rtp_sendto(instance, buf, size, flags, sa, 0);
398 static int rtp_get_rate(struct ast_format *format)
400 return (format->id == AST_FORMAT_G722) ? 8000 : ast_format_rate(format);
403 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
405 unsigned int interval;
406 /*! \todo XXX Do a more reasonable calculation on this one
407 * Look in RFC 3550 Section A.7 for an example*/
408 interval = rtcpinterval;
412 /*! \brief Calculate normal deviation */
413 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
415 normdev = normdev * sample_count + sample;
418 return normdev / sample_count;
421 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
424 for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
425 return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
426 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
429 #define SQUARE(x) ((x) * (x))
431 stddev = sample_count * stddev;
435 ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
436 ( SQUARE(sample - normdev_curent) / sample_count );
441 static int create_new_socket(const char *type, int af)
443 int sock = socket(af, SOCK_DGRAM, 0);
449 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
451 long flags = fcntl(sock, F_GETFL);
452 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
455 setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
463 static int ast_rtp_new(struct ast_rtp_instance *instance,
464 struct ast_sched_context *sched, struct ast_sockaddr *addr,
467 struct ast_rtp *rtp = NULL;
470 /* Create a new RTP structure to hold all of our data */
471 if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
475 /* Set default parameters on the newly created RTP structure */
476 rtp->ssrc = ast_random();
477 rtp->seqno = ast_random() & 0xffff;
478 rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
480 /* Create a new socket for us to listen on and use */
482 create_new_socket("RTP",
483 ast_sockaddr_is_ipv4(addr) ? AF_INET :
484 ast_sockaddr_is_ipv6(addr) ? AF_INET6 : -1)) < 0) {
485 ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
490 /* Now actually find a free RTP port to use */
491 x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
496 ast_sockaddr_set_port(addr, x);
497 /* Try to bind, this will tell us whether the port is available or not */
498 if (!ast_bind(rtp->s, addr)) {
499 ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
500 ast_rtp_instance_set_local_address(instance, addr);
506 x = (rtpstart + 1) & ~1;
509 /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
510 if (x == startplace || errno != EADDRINUSE) {
511 ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
516 /* Record any information we may need */
519 /* Associate the RTP structure with the RTP instance and be done */
520 ast_rtp_instance_set_data(instance, rtp);
525 static int ast_rtp_destroy(struct ast_rtp_instance *instance)
527 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
529 /* Destroy the smoother that was smoothing out audio if present */
531 ast_smoother_free(rtp->smoother);
534 /* Close our own socket so we no longer get packets */
539 /* Destroy RTCP if it was being used */
542 * It is not possible for there to be an active RTCP scheduler
543 * entry at this point since it holds a reference to the
544 * RTP instance while it's active.
550 /* Destroy RED if it was being used */
552 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
556 /* Finally destroy ourselves */
562 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
564 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
565 rtp->dtmfmode = dtmf_mode;
569 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
571 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
572 return rtp->dtmfmode;
575 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
577 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
578 struct ast_sockaddr remote_address = { {0,} };
579 int hdrlen = 12, res = 0, i = 0, payload = 101;
581 unsigned int *rtpheader = (unsigned int*)data;
583 ast_rtp_instance_get_remote_address(instance, &remote_address);
585 /* If we have no remote address information bail out now */
586 if (ast_sockaddr_isnull(&remote_address)) {
590 /* Convert given digit into what we want to transmit */
591 if ((digit <= '9') && (digit >= '0')) {
593 } else if (digit == '*') {
595 } else if (digit == '#') {
597 } else if ((digit >= 'A') && (digit <= 'D')) {
598 digit = digit - 'A' + 12;
599 } else if ((digit >= 'a') && (digit <= 'd')) {
600 digit = digit - 'a' + 12;
602 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
606 /* Grab the payload that they expect the RFC2833 packet to be received in */
607 payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_DTMF);
609 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
610 rtp->send_duration = 160;
611 rtp->lastdigitts = rtp->lastts + rtp->send_duration;
613 /* Create the actual packet that we will be sending */
614 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
615 rtpheader[1] = htonl(rtp->lastdigitts);
616 rtpheader[2] = htonl(rtp->ssrc);
618 /* Actually send the packet */
619 for (i = 0; i < 2; i++) {
620 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
621 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address);
623 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
624 ast_sockaddr_stringify(&remote_address),
627 if (rtp_debug_test_addr(&remote_address)) {
628 ast_verbose("Sent RTP DTMF packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
629 ast_sockaddr_stringify(&remote_address),
630 payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
633 rtp->send_duration += 160;
634 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
637 /* Record that we are in the process of sending a digit and information needed to continue doing so */
638 rtp->sending_digit = 1;
639 rtp->send_digit = digit;
640 rtp->send_payload = payload;
645 static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
647 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
648 struct ast_sockaddr remote_address = { {0,} };
649 int hdrlen = 12, res = 0;
651 unsigned int *rtpheader = (unsigned int*)data;
653 ast_rtp_instance_get_remote_address(instance, &remote_address);
655 /* Make sure we know where the other side is so we can send them the packet */
656 if (ast_sockaddr_isnull(&remote_address)) {
660 /* Actually create the packet we will be sending */
661 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
662 rtpheader[1] = htonl(rtp->lastdigitts);
663 rtpheader[2] = htonl(rtp->ssrc);
664 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
665 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
667 /* Boom, send it on out */
668 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address);
670 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
671 ast_sockaddr_stringify(&remote_address),
675 if (rtp_debug_test_addr(&remote_address)) {
676 ast_verbose("Sent RTP DTMF packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
677 ast_sockaddr_stringify(&remote_address),
678 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
681 /* And now we increment some values for the next time we swing by */
683 rtp->send_duration += 160;
688 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
690 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
691 struct ast_sockaddr remote_address = { {0,} };
692 int hdrlen = 12, res = 0, i = 0;
694 unsigned int *rtpheader = (unsigned int*)data;
695 unsigned int measured_samples;
697 ast_rtp_instance_get_remote_address(instance, &remote_address);
699 /* Make sure we know where the remote side is so we can send them the packet we construct */
700 if (ast_sockaddr_isnull(&remote_address)) {
704 /* Convert the given digit to the one we are going to send */
705 if ((digit <= '9') && (digit >= '0')) {
707 } else if (digit == '*') {
709 } else if (digit == '#') {
711 } else if ((digit >= 'A') && (digit <= 'D')) {
712 digit = digit - 'A' + 12;
713 } else if ((digit >= 'a') && (digit <= 'd')) {
714 digit = digit - 'a' + 12;
716 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
720 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
722 if (duration > 0 && (measured_samples = duration * rtp_get_rate(&rtp->f.subclass.format) / 1000) > rtp->send_duration) {
723 ast_debug(2, "Adjusting final end duration from %u to %u\n", rtp->send_duration, measured_samples);
724 rtp->send_duration = measured_samples;
727 /* Construct the packet we are going to send */
728 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
729 rtpheader[1] = htonl(rtp->lastdigitts);
730 rtpheader[2] = htonl(rtp->ssrc);
731 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
732 rtpheader[3] |= htonl((1 << 23));
733 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
735 /* Send it 3 times, that's the magical number */
736 for (i = 0; i < 3; i++) {
737 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address);
739 ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
740 ast_sockaddr_stringify(&remote_address),
743 if (rtp_debug_test_addr(&remote_address)) {
744 ast_verbose("Sent RTP DTMF packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
745 ast_sockaddr_stringify(&remote_address),
746 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
750 /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
751 rtp->lastts += rtp->send_duration;
752 rtp->sending_digit = 0;
758 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
760 return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
763 static void ast_rtp_update_source(struct ast_rtp_instance *instance)
765 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
767 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
768 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
769 ast_debug(3, "Setting the marker bit due to a source update\n");
774 static void ast_rtp_change_source(struct ast_rtp_instance *instance)
776 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
777 struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
778 unsigned int ssrc = ast_random();
781 ast_debug(3, "Not changing SSRC since we haven't sent any RTP yet\n");
785 /* We simply set this bit so that the next packet sent will have the marker bit turned on */
786 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
788 ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
791 ast_debug(3, "Changing ssrc for SRTP from %u to %u\n", rtp->ssrc, ssrc);
792 res_srtp->change_source(srtp, rtp->ssrc, ssrc);
800 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
805 if (ast_tvzero(rtp->txcore)) {
806 rtp->txcore = ast_tvnow();
807 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
810 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
811 if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
816 return (unsigned int) ms;
819 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
821 unsigned int sec, usec, frac;
822 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
824 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
829 /*! \brief Send RTCP recipient's report */
830 static int ast_rtcp_write_rr(struct ast_rtp_instance *instance)
832 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
836 unsigned int extended;
837 unsigned int expected;
838 unsigned int expected_interval;
839 unsigned int received_interval;
842 unsigned int *rtcpheader;
847 double rxlost_current;
849 if (!rtp || !rtp->rtcp)
852 if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
859 extended = rtp->cycles + rtp->lastrxseqno;
860 expected = extended - rtp->seedrxseqno + 1;
861 lost = expected - rtp->rxcount;
862 expected_interval = expected - rtp->rtcp->expected_prior;
863 rtp->rtcp->expected_prior = expected;
864 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
865 rtp->rtcp->received_prior = rtp->rxcount;
866 lost_interval = expected_interval - received_interval;
868 if (lost_interval <= 0)
869 rtp->rtcp->rxlost = 0;
870 else rtp->rtcp->rxlost = rtp->rtcp->rxlost;
871 if (rtp->rtcp->rxlost_count == 0)
872 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
873 if (lost_interval < rtp->rtcp->minrxlost)
874 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
875 if (lost_interval > rtp->rtcp->maxrxlost)
876 rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
878 rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->rxlost_count);
879 rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->normdev_rxlost, rxlost_current, rtp->rtcp->rxlost_count);
880 rtp->rtcp->normdev_rxlost = rxlost_current;
881 rtp->rtcp->rxlost_count++;
883 if (expected_interval == 0 || lost_interval <= 0)
886 fraction = (lost_interval << 8) / expected_interval;
887 gettimeofday(&now, NULL);
888 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
889 rtcpheader = (unsigned int *)bdata;
890 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
891 rtcpheader[1] = htonl(rtp->ssrc);
892 rtcpheader[2] = htonl(rtp->themssrc);
893 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
894 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
895 rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
896 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
897 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
899 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
900 it can change mid call, and SDES can't) */
901 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
902 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
903 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
906 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &rtp->rtcp->them);
909 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
913 rtp->rtcp->rr_count++;
914 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
915 ast_verbose("\n* Sending RTCP RR to %s\n"
916 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
918 " Their last SR: %u\n"
919 " DLSR: %4.4f (sec)\n\n",
920 ast_sockaddr_stringify(&rtp->rtcp->them),
921 rtp->ssrc, rtp->themssrc, fraction, lost,
923 rtp->rtcp->themrxlsr,
924 (double)(ntohl(rtcpheader[7])/65536.0));
930 /*! \brief Send RTCP sender's report */
931 static int ast_rtcp_write_sr(struct ast_rtp_instance *instance)
933 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
937 unsigned int now_lsw;
938 unsigned int now_msw;
939 unsigned int *rtcpheader;
941 unsigned int extended;
942 unsigned int expected;
943 unsigned int expected_interval;
944 unsigned int received_interval;
950 if (!rtp || !rtp->rtcp)
953 if (ast_sockaddr_isnull(&rtp->rtcp->them)) { /* This'll stop rtcp for this rtp session */
960 gettimeofday(&now, NULL);
961 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
962 rtcpheader = (unsigned int *)bdata;
963 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
964 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
965 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
966 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
967 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
968 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
971 extended = rtp->cycles + rtp->lastrxseqno;
972 expected = extended - rtp->seedrxseqno + 1;
973 if (rtp->rxcount > expected)
974 expected += rtp->rxcount - expected;
975 lost = expected - rtp->rxcount;
976 expected_interval = expected - rtp->rtcp->expected_prior;
977 rtp->rtcp->expected_prior = expected;
978 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
979 rtp->rtcp->received_prior = rtp->rxcount;
980 lost_interval = expected_interval - received_interval;
981 if (expected_interval == 0 || lost_interval <= 0)
984 fraction = (lost_interval << 8) / expected_interval;
985 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
986 rtcpheader[7] = htonl(rtp->themssrc);
987 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
988 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
989 rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
990 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
991 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
994 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
996 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
997 /* it can change mid call, and SDES can't) */
998 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
999 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
1000 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
1003 res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &rtp->rtcp->them);
1005 ast_log(LOG_ERROR, "RTCP SR transmission error to %s, rtcp halted %s\n",
1006 ast_sockaddr_stringify(&rtp->rtcp->them),
1011 /* FIXME Don't need to get a new one */
1012 gettimeofday(&rtp->rtcp->txlsr, NULL);
1013 rtp->rtcp->sr_count++;
1015 rtp->rtcp->lastsrtxcount = rtp->txcount;
1017 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
1018 ast_verbose("* Sent RTCP SR to %s\n", ast_sockaddr_stringify(&rtp->rtcp->them));
1019 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
1020 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
1021 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
1022 ast_verbose(" Sent packets: %u\n", rtp->txcount);
1023 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
1024 ast_verbose(" Report block:\n");
1025 ast_verbose(" Fraction lost: %u\n", fraction);
1026 ast_verbose(" Cumulative loss: %u\n", lost);
1027 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
1028 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
1029 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
1031 manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To: %s\r\n"
1033 "SentNTP: %u.%010u\r\n"
1035 "SentPackets: %u\r\n"
1036 "SentOctets: %u\r\n"
1038 "FractionLost: %u\r\n"
1039 "CumulativeLoss: %u\r\n"
1040 "IAJitter: %.4f\r\n"
1041 "TheirLastSR: %u\r\n"
1042 "DLSR: %4.4f (sec)\r\n",
1043 ast_sockaddr_stringify(&rtp->rtcp->them),
1045 (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
1052 rtp->rtcp->themrxlsr,
1053 (double)(ntohl(rtcpheader[12])/65536.0));
1057 /*! \brief Write and RTCP packet to the far end
1058 * \note Decide if we are going to send an SR (with Reception Block) or RR
1059 * RR is sent if we have not sent any rtp packets in the previous interval */
1060 static int ast_rtcp_write(const void *data)
1062 struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
1063 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1066 if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
1067 ao2_ref(instance, -1);
1071 if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
1072 res = ast_rtcp_write_sr(instance);
1074 res = ast_rtcp_write_rr(instance);
1079 * Not being rescheduled.
1081 ao2_ref(instance, -1);
1082 rtp->rtcp->schedid = -1;
1088 static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
1090 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1092 unsigned int ms = calc_txstamp(rtp, &frame->delivery);
1093 struct ast_sockaddr remote_address = { {0,} };
1094 int rate = rtp_get_rate(&frame->subclass.format) / 1000;
1096 if (frame->subclass.format.id == AST_FORMAT_G722) {
1097 frame->samples /= 2;
1100 if (rtp->sending_digit) {
1104 if (frame->frametype == AST_FRAME_VOICE) {
1105 pred = rtp->lastts + frame->samples;
1107 /* Re-calculate last TS */
1108 rtp->lastts = rtp->lastts + ms * rate;
1109 if (ast_tvzero(frame->delivery)) {
1110 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
1111 and if so, go with our prediction */
1112 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
1115 ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
1119 } else if (frame->frametype == AST_FRAME_VIDEO) {
1120 mark = ast_format_get_video_mark(&frame->subclass.format);
1121 pred = rtp->lastovidtimestamp + frame->samples;
1122 /* Re-calculate last TS */
1123 rtp->lastts = rtp->lastts + ms * 90;
1124 /* If it's close to our prediction, go for it */
1125 if (ast_tvzero(frame->delivery)) {
1126 if (abs(rtp->lastts - pred) < 7200) {
1128 rtp->lastovidtimestamp += frame->samples;
1130 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);
1131 rtp->lastovidtimestamp = rtp->lastts;
1135 pred = rtp->lastotexttimestamp + frame->samples;
1136 /* Re-calculate last TS */
1137 rtp->lastts = rtp->lastts + ms;
1138 /* If it's close to our prediction, go for it */
1139 if (ast_tvzero(frame->delivery)) {
1140 if (abs(rtp->lastts - pred) < 7200) {
1142 rtp->lastotexttimestamp += frame->samples;
1144 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);
1145 rtp->lastotexttimestamp = rtp->lastts;
1150 /* If we have been explicitly told to set the marker bit then do so */
1151 if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
1153 ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
1156 /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
1157 if (rtp->lastts > rtp->lastdigitts) {
1158 rtp->lastdigitts = rtp->lastts;
1161 if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
1162 rtp->lastts = frame->ts * rate;
1165 ast_rtp_instance_get_remote_address(instance, &remote_address);
1167 /* If we know the remote address construct a packet and send it out */
1168 if (!ast_sockaddr_isnull(&remote_address)) {
1169 int hdrlen = 12, res;
1170 unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
1172 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
1173 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
1174 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
1176 if ((res = rtp_sendto(instance, (void *)rtpheader, frame->datalen + hdrlen, 0, &remote_address)) < 0) {
1177 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))) {
1178 ast_debug(1, "RTP Transmission error of packet %d to %s: %s\n",
1180 ast_sockaddr_stringify(&remote_address),
1182 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
1183 /* Only give this error message once if we are not RTP debugging */
1185 ast_debug(0, "RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
1186 ast_sockaddr_stringify(&remote_address));
1187 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
1191 rtp->txoctetcount += (res - hdrlen);
1193 if (rtp->rtcp && rtp->rtcp->schedid < 1) {
1194 ast_debug(1, "Starting RTCP transmission on RTP instance '%p'\n", instance);
1195 ao2_ref(instance, +1);
1196 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
1197 if (rtp->rtcp->schedid < 0) {
1198 ao2_ref(instance, -1);
1199 ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
1204 if (rtp_debug_test_addr(&remote_address)) {
1205 ast_verbose("Sent RTP packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1206 ast_sockaddr_stringify(&remote_address),
1207 codec, rtp->seqno, rtp->lastts, res - hdrlen);
1216 static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
1217 unsigned char *data = red->t140red.data.ptr;
1221 /* replace most aged generation */
1223 for (i = 1; i < red->num_gen+1; i++)
1226 memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
1229 /* Store length of each generation and primary data length*/
1230 for (i = 0; i < red->num_gen; i++)
1231 red->len[i] = red->len[i+1];
1232 red->len[i] = red->t140.datalen;
1234 /* write each generation length in red header */
1236 for (i = 0; i < red->num_gen; i++)
1237 len += data[i*4+3] = red->len[i];
1239 /* add primary data to buffer */
1240 memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
1241 red->t140red.datalen = len + red->t140.datalen;
1243 /* no primary data and no generations to send */
1244 if (len == red->hdrlen && !red->t140.datalen)
1247 /* reset t.140 buffer */
1248 red->t140.datalen = 0;
1250 return &red->t140red;
1253 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
1255 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1256 struct ast_sockaddr remote_address = { {0,} };
1257 struct ast_format subclass;
1260 ast_rtp_instance_get_remote_address(instance, &remote_address);
1262 /* If we don't actually know the remote address don't even bother doing anything */
1263 if (ast_sockaddr_isnull(&remote_address)) {
1264 ast_debug(1, "No remote address on RTP instance '%p' so dropping frame\n", instance);
1268 /* If there is no data length we can't very well send the packet */
1269 if (!frame->datalen) {
1270 ast_debug(1, "Received frame with no data for RTP instance '%p' so dropping frame\n", instance);
1274 /* If the packet is not one our RTP stack supports bail out */
1275 if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
1276 ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
1282 /* no primary data or generations to send */
1283 if ((frame = red_t140_to_red(rtp->red)) == NULL)
1287 /* Grab the subclass and look up the payload we are going to use */
1288 ast_format_copy(&subclass, &frame->subclass.format);
1289 if ((codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 1, &subclass, 0)) < 0) {
1290 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(&frame->subclass.format));
1294 /* Oh dear, if the format changed we will have to set up a new smoother */
1295 if (ast_format_cmp(&rtp->lasttxformat, &subclass) == AST_FORMAT_CMP_NOT_EQUAL) {
1296 ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(&rtp->lasttxformat), ast_getformatname(&subclass));
1297 rtp->lasttxformat = subclass;
1298 ast_format_copy(&rtp->lasttxformat, &subclass);
1299 if (rtp->smoother) {
1300 ast_smoother_free(rtp->smoother);
1301 rtp->smoother = NULL;
1305 /* If no smoother is present see if we have to set one up */
1306 if (!rtp->smoother) {
1307 struct ast_format_list fmt = ast_codec_pref_getsize(&ast_rtp_instance_get_codecs(instance)->pref, &subclass);
1309 switch (subclass.id) {
1310 case AST_FORMAT_SPEEX:
1311 case AST_FORMAT_SPEEX16:
1312 case AST_FORMAT_SPEEX32:
1313 case AST_FORMAT_SILK:
1314 case AST_FORMAT_CELT:
1315 case AST_FORMAT_G723_1:
1316 case AST_FORMAT_SIREN7:
1317 case AST_FORMAT_SIREN14:
1318 case AST_FORMAT_G719:
1319 /* these are all frame-based codecs and cannot be safely run through
1324 if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
1325 ast_log(LOG_WARNING, "Unable to create smoother: format %s ms: %d len: %d\n", ast_getformatname(&subclass), fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
1329 ast_smoother_set_flags(rtp->smoother, fmt.flags);
1331 ast_debug(1, "Created smoother: format: %s ms: %d len: %d\n", ast_getformatname(&subclass), fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
1336 /* Feed audio frames into the actual function that will create a frame and send it */
1337 if (rtp->smoother) {
1338 struct ast_frame *f;
1340 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
1341 ast_smoother_feed_be(rtp->smoother, frame);
1343 ast_smoother_feed(rtp->smoother, frame);
1346 while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
1347 ast_rtp_raw_write(instance, f, codec);
1351 struct ast_frame *f = NULL;
1353 if (frame->offset < hdrlen) {
1354 f = ast_frdup(frame);
1359 ast_rtp_raw_write(instance, f, codec);
1370 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
1375 double current_time;
1379 int rate = rtp_get_rate(&rtp->f.subclass.format);
1381 double normdev_rxjitter_current;
1382 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
1383 gettimeofday(&rtp->rxcore, NULL);
1384 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
1385 /* map timestamp to a real time */
1386 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
1387 tmp = ast_samp2tv(timestamp, rate);
1388 rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
1389 /* Round to 0.1ms for nice, pretty timestamps */
1390 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
1393 gettimeofday(&now,NULL);
1394 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
1395 tmp = ast_samp2tv(timestamp, rate);
1396 *tv = ast_tvadd(rtp->rxcore, tmp);
1398 prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
1399 dtv = (double)rtp->drxcore + (double)(prog);
1400 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
1401 transit = current_time - dtv;
1402 d = transit - rtp->rxtransit;
1403 rtp->rxtransit = transit;
1406 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1409 if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
1410 rtp->rtcp->maxrxjitter = rtp->rxjitter;
1411 if (rtp->rtcp->rxjitter_count == 1)
1412 rtp->rtcp->minrxjitter = rtp->rxjitter;
1413 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1414 rtp->rtcp->minrxjitter = rtp->rxjitter;
1416 normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
1417 rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
1419 rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
1420 rtp->rtcp->rxjitter_count++;
1424 static struct ast_frame *create_dtmf_frame(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
1426 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1427 struct ast_sockaddr remote_address = { {0,} };
1429 ast_rtp_instance_get_remote_address(instance, &remote_address);
1431 if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
1432 ast_debug(1, "Ignore potential DTMF echo from '%s'\n",
1433 ast_sockaddr_stringify(&remote_address));
1435 rtp->dtmfsamples = 0;
1436 return &ast_null_frame;
1438 ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp,
1439 ast_sockaddr_stringify(&remote_address));
1440 if (rtp->resp == 'X') {
1441 rtp->f.frametype = AST_FRAME_CONTROL;
1442 rtp->f.subclass.integer = AST_CONTROL_FLASH;
1444 rtp->f.frametype = type;
1445 rtp->f.subclass.integer = rtp->resp;
1451 AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
1456 static void process_dtmf_rfc2833(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark, struct frame_list *frames)
1458 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1459 struct ast_sockaddr remote_address = { {0,} };
1460 unsigned int event, event_end, samples;
1462 struct ast_frame *f = NULL;
1464 ast_rtp_instance_get_remote_address(instance, &remote_address);
1466 /* Figure out event, event end, and samples */
1467 event = ntohl(*((unsigned int *)(data)));
1469 event_end = ntohl(*((unsigned int *)(data)));
1472 samples = ntohl(*((unsigned int *)(data)));
1475 if (rtp_debug_test_addr(&remote_address)) {
1476 ast_verbose("Got RTP RFC2833 from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n",
1477 ast_sockaddr_stringify(&remote_address),
1478 payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
1481 /* Print out debug if turned on */
1483 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
1485 /* Figure out what digit was pressed */
1488 } else if (event < 11) {
1490 } else if (event < 12) {
1492 } else if (event < 16) {
1493 resp = 'A' + (event - 12);
1494 } else if (event < 17) { /* Event 16: Hook flash */
1497 /* Not a supported event */
1498 ast_debug(1, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
1502 if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
1503 if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
1505 rtp->dtmf_timeout = 0;
1506 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)));
1508 rtp->lastevent = timestamp;
1509 AST_LIST_INSERT_TAIL(frames, f, frame_list);
1512 /* The duration parameter measures the complete
1513 duration of the event (from the beginning) - RFC2833.
1514 Account for the fact that duration is only 16 bits long
1515 (about 8 seconds at 8000 Hz) and can wrap is digit
1516 is hold for too long. */
1517 unsigned int new_duration = rtp->dtmf_duration;
1518 unsigned int last_duration = new_duration & 0xFFFF;
1520 if (last_duration > 64000 && samples < last_duration) {
1521 new_duration += 0xFFFF + 1;
1523 new_duration = (new_duration & ~0xFFFF) | samples;
1525 /* The second portion of this check is to not mistakenly
1526 * stop accepting DTMF if the seqno rolls over beyond
1529 if (rtp->lastevent > seqno && rtp->lastevent - seqno < 50) {
1530 /* Out of order frame. Processing this can cause us to
1531 * improperly duplicate incoming DTMF, so just drop
1537 if (event_end & 0x80) {
1539 if ((rtp->lastevent != seqno) && rtp->resp) {
1540 rtp->dtmf_duration = new_duration;
1541 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
1542 f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
1544 rtp->dtmf_duration = rtp->dtmf_timeout = 0;
1545 AST_LIST_INSERT_TAIL(frames, f, frame_list);
1548 /* Begin/continuation */
1550 if (rtp->resp && rtp->resp != resp) {
1551 /* Another digit already began. End it */
1552 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
1553 f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
1555 rtp->dtmf_duration = rtp->dtmf_timeout = 0;
1556 AST_LIST_INSERT_TAIL(frames, f, frame_list);
1560 /* Digit continues */
1561 rtp->dtmf_duration = new_duration;
1563 /* New digit began */
1565 f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0));
1566 rtp->dtmf_duration = samples;
1567 AST_LIST_INSERT_TAIL(frames, f, frame_list);
1570 rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
1573 rtp->lastevent = seqno;
1576 rtp->dtmfsamples = samples;
1581 static struct ast_frame *process_dtmf_cisco(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark)
1583 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1584 unsigned int event, flags, power;
1587 struct ast_frame *f = NULL;
1593 /* The format of Cisco RTP DTMF packet looks like next:
1594 +0 - sequence number of DTMF RTP packet (begins from 1,
1597 +1 (bit 0) - flaps by different DTMF digits delimited by audio
1598 or repeated digit without audio???
1599 +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
1600 then falls to 0 at its end)
1601 +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
1602 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
1603 by each new packet and thus provides some redudancy.
1605 Sample of Cisco RTP DTMF packet is (all data in hex):
1606 19 07 00 02 12 02 20 02
1607 showing end of DTMF digit '2'.
1610 27 07 00 02 0A 02 20 02
1611 28 06 20 02 00 02 0A 02
1612 shows begin of new digit '2' with very short pause (20 ms) after
1613 previous digit '2'. Bit +1.0 flips at begin of new digit.
1615 Cisco RTP DTMF packets comes as replacement of audio RTP packets
1616 so its uses the same sequencing and timestamping rules as replaced
1617 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
1618 on audio framing parameters. Marker bit isn't used within stream of
1619 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
1620 are not sequential at borders between DTMF and audio streams,
1626 event = data[3] & 0x1f;
1629 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);
1632 } else if (event < 11) {
1634 } else if (event < 12) {
1636 } else if (event < 16) {
1637 resp = 'A' + (event - 12);
1638 } else if (event < 17) {
1641 if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
1643 /* Why we should care on DTMF compensation at reception? */
1644 if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
1645 f = create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0);
1646 rtp->dtmfsamples = 0;
1648 } else if ((rtp->resp == resp) && !power) {
1649 f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE));
1650 f->samples = rtp->dtmfsamples * (rtp->lastrxformat.id ? (rtp_get_rate(&rtp->lastrxformat) / 1000) : 8);
1652 } else if (rtp->resp == resp)
1653 rtp->dtmfsamples += 20 * (rtp->lastrxformat.id ? (rtp_get_rate(&rtp->lastrxformat) / 1000) : 8);
1655 rtp->dtmf_timeout = 0;
1660 static struct ast_frame *process_cn_rfc3389(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark)
1662 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1664 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
1665 totally help us out becuase we don't have an engine to keep it going and we are not
1666 guaranteed to have it every 20ms or anything */
1668 ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", (int) rtp->lastrxformat.id, len);
1670 if (ast_test_flag(rtp, FLAG_3389_WARNING)) {
1671 struct ast_sockaddr remote_address = { {0,} };
1673 ast_rtp_instance_get_remote_address(instance, &remote_address);
1675 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client address: %s\n",
1676 ast_sockaddr_stringify(&remote_address));
1677 ast_set_flag(rtp, FLAG_3389_WARNING);
1680 /* Must have at least one byte */
1684 rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
1685 rtp->f.datalen = len - 1;
1686 rtp->f.offset = AST_FRIENDLY_OFFSET;
1687 memcpy(rtp->f.data.ptr, data + 1, len - 1);
1689 rtp->f.data.ptr = NULL;
1693 rtp->f.frametype = AST_FRAME_CNG;
1694 rtp->f.subclass.integer = data[0] & 0x7f;
1696 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
1701 static struct ast_frame *ast_rtcp_read(struct ast_rtp_instance *instance)
1703 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
1704 struct ast_sockaddr addr;
1705 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
1706 unsigned int *rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
1707 int res, packetwords, position = 0;
1708 struct ast_frame *f = &ast_null_frame;
1710 /* Read in RTCP data from the socket */
1711 if ((res = rtcp_recvfrom(instance, rtcpdata + AST_FRIENDLY_OFFSET,
1712 sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
1714 ast_assert(errno != EBADF);
1715 if (errno != EAGAIN) {
1716 ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n", strerror(errno));
1719 return &ast_null_frame;
1722 packetwords = res / 4;
1724 if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
1725 /* Send to whoever sent to us */
1726 if (ast_sockaddr_cmp(&rtp->rtcp->them, &addr)) {
1727 ast_sockaddr_copy(&rtp->rtcp->them, &addr);
1729 ast_debug(0, "RTCP NAT: Got RTCP from other end. Now sending to address %s\n",
1730 ast_sockaddr_stringify(&rtp->rtcp->them));
1734 ast_debug(1, "Got RTCP report of %d bytes\n", res);
1736 while (position < packetwords) {
1738 unsigned int length, dlsr, lsr, msw, lsw, comp;
1740 double rttsec, reported_jitter, reported_normdev_jitter_current, normdevrtt_current, reported_lost, reported_normdev_lost_current;
1744 length = ntohl(rtcpheader[i]);
1745 pt = (length & 0xff0000) >> 16;
1746 rc = (length & 0x1f000000) >> 24;
1749 if ((i + length) > packetwords) {
1751 ast_debug(1, "RTCP Read too short\n");
1752 return &ast_null_frame;
1755 if (rtcp_debug_test_addr(&addr)) {
1756 ast_verbose("\n\nGot RTCP from %s\n",
1757 ast_sockaddr_stringify(&addr));
1758 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
1759 ast_verbose("Reception reports: %d\n", rc);
1760 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
1763 i += 2; /* Advance past header and ssrc */
1764 if (rc == 0 && pt == RTCP_PT_RR) { /* We're receiving a receiver report with no reports, which is ok */
1765 position += (length + 1);
1771 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
1772 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
1773 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
1774 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
1776 if (rtcp_debug_test_addr(&addr)) {
1777 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
1778 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
1779 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
1784 /* Intentional fall through */
1786 /* Don't handle multiple reception reports (rc > 1) yet */
1787 /* Calculate RTT per RFC */
1788 gettimeofday(&now, NULL);
1789 timeval2ntp(now, &msw, &lsw);
1790 if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
1791 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
1792 lsr = ntohl(rtcpheader[i + 4]);
1793 dlsr = ntohl(rtcpheader[i + 5]);
1794 rtt = comp - lsr - dlsr;
1796 /* Convert end to end delay to usec (keeping the calculation in 64bit space)
1797 sess->ee_delay = (eedelay * 1000) / 65536; */
1799 rtt = (rtt * 1000000) >> 16;
1801 rtt = (rtt * 1000) >> 16;
1805 rttsec = rtt / 1000.;
1806 rtp->rtcp->rtt = rttsec;
1808 if (comp - dlsr >= lsr) {
1809 rtp->rtcp->accumulated_transit += rttsec;
1811 if (rtp->rtcp->rtt_count == 0)
1812 rtp->rtcp->minrtt = rttsec;
1814 if (rtp->rtcp->maxrtt<rttsec)
1815 rtp->rtcp->maxrtt = rttsec;
1816 if (rtp->rtcp->minrtt>rttsec)
1817 rtp->rtcp->minrtt = rttsec;
1819 normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt, rttsec, rtp->rtcp->rtt_count);
1821 rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt, rttsec, rtp->rtcp->normdevrtt, normdevrtt_current, rtp->rtcp->rtt_count);
1823 rtp->rtcp->normdevrtt = normdevrtt_current;
1825 rtp->rtcp->rtt_count++;
1826 } else if (rtcp_debug_test_addr(&addr)) {
1827 ast_verbose("Internal RTCP NTP clock skew detected: "
1828 "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
1830 lsr, comp, dlsr, dlsr / 65536,
1831 (dlsr % 65536) * 1000 / 65536,
1832 dlsr - (comp - lsr));
1836 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
1837 reported_jitter = (double) rtp->rtcp->reported_jitter;
1839 if (rtp->rtcp->reported_jitter_count == 0)
1840 rtp->rtcp->reported_minjitter = reported_jitter;
1842 if (reported_jitter < rtp->rtcp->reported_minjitter)
1843 rtp->rtcp->reported_minjitter = reported_jitter;
1845 if (reported_jitter > rtp->rtcp->reported_maxjitter)
1846 rtp->rtcp->reported_maxjitter = reported_jitter;
1848 reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);
1850 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);
1852 rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;
1854 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
1856 reported_lost = (double) rtp->rtcp->reported_lost;
1858 /* using same counter as for jitter */
1859 if (rtp->rtcp->reported_jitter_count == 0)
1860 rtp->rtcp->reported_minlost = reported_lost;
1862 if (reported_lost < rtp->rtcp->reported_minlost)
1863 rtp->rtcp->reported_minlost = reported_lost;
1865 if (reported_lost > rtp->rtcp->reported_maxlost)
1866 rtp->rtcp->reported_maxlost = reported_lost;
1867 reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);
1869 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);
1871 rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;
1873 rtp->rtcp->reported_jitter_count++;
1875 if (rtcp_debug_test_addr(&addr)) {
1876 ast_verbose(" Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
1877 ast_verbose(" Packets lost so far: %d\n", rtp->rtcp->reported_lost);
1878 ast_verbose(" Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
1879 ast_verbose(" Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
1880 ast_verbose(" Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
1881 ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
1882 ast_verbose(" DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
1884 ast_verbose(" RTT: %lu(sec)\n", (unsigned long) rtt);
1887 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s\r\n"
1889 "ReceptionReports: %d\r\n"
1890 "SenderSSRC: %u\r\n"
1891 "FractionLost: %ld\r\n"
1892 "PacketsLost: %d\r\n"
1893 "HighestSequence: %ld\r\n"
1894 "SequenceNumberCycles: %ld\r\n"
1896 "LastSR: %lu.%010lu\r\n"
1897 "DLSR: %4.4f(sec)\r\n"
1898 "RTT: %llu(sec)\r\n",
1899 ast_sockaddr_stringify(&addr),
1900 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1903 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1904 rtp->rtcp->reported_lost,
1905 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1906 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1907 rtp->rtcp->reported_jitter,
1908 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1909 ntohl(rtcpheader[i + 5])/65536.0,
1910 (unsigned long long)rtt);
1912 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s\r\n"
1914 "ReceptionReports: %d\r\n"
1915 "SenderSSRC: %u\r\n"
1916 "FractionLost: %ld\r\n"
1917 "PacketsLost: %d\r\n"
1918 "HighestSequence: %ld\r\n"
1919 "SequenceNumberCycles: %ld\r\n"
1921 "LastSR: %lu.%010lu\r\n"
1922 "DLSR: %4.4f(sec)\r\n",
1923 ast_sockaddr_stringify(&addr),
1924 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1927 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1928 rtp->rtcp->reported_lost,
1929 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1930 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1931 rtp->rtcp->reported_jitter,
1932 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
1933 ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1934 ntohl(rtcpheader[i + 5])/65536.0);
1938 if (rtcp_debug_test_addr(&addr))
1939 ast_verbose("Received an RTCP Fast Update Request\n");
1940 rtp->f.frametype = AST_FRAME_CONTROL;
1941 rtp->f.subclass.integer = AST_CONTROL_VIDUPDATE;
1949 if (rtcp_debug_test_addr(&addr))
1950 ast_verbose("Received an SDES from %s\n",
1951 ast_sockaddr_stringify(&rtp->rtcp->them));
1954 if (rtcp_debug_test_addr(&addr))
1955 ast_verbose("Received a BYE from %s\n",
1956 ast_sockaddr_stringify(&rtp->rtcp->them));
1959 ast_debug(1, "Unknown RTCP packet (pt=%d) received from %s\n",
1960 pt, ast_sockaddr_stringify(&rtp->rtcp->them));
1963 position += (length + 1);
1966 rtp->rtcp->rtcp_info = 1;
1971 static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance, unsigned int *rtpheader, int len, int hdrlen)
1973 struct ast_rtp_instance *instance1 = ast_rtp_instance_get_bridged(instance);
1974 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance), *bridged = ast_rtp_instance_get_data(instance1);
1975 int res = 0, payload = 0, bridged_payload = 0, mark;
1976 struct ast_rtp_payload_type payload_type;
1977 int reconstruct = ntohl(rtpheader[0]);
1978 struct ast_sockaddr remote_address = { {0,} };
1980 /* Get fields from packet */
1981 payload = (reconstruct & 0x7f0000) >> 16;
1982 mark = (((reconstruct & 0x800000) >> 23) != 0);
1984 /* Check what the payload value should be */
1985 payload_type = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), payload);
1987 /* Otherwise adjust bridged payload to match */
1988 bridged_payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance1), payload_type.asterisk_format, &payload_type.format, payload_type.rtp_code);
1990 /* 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 */
1991 if (!(ast_rtp_instance_get_codecs(instance1)->payloads[bridged_payload].rtp_code) &&
1992 !(ast_rtp_instance_get_codecs(instance1)->payloads[bridged_payload].asterisk_format)) {
1996 /* If the marker bit has been explicitly set turn it on */
1997 if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
1999 ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
2002 /* Reconstruct part of the packet */
2003 reconstruct &= 0xFF80FFFF;
2004 reconstruct |= (bridged_payload << 16);
2005 reconstruct |= (mark << 23);
2006 rtpheader[0] = htonl(reconstruct);
2008 ast_rtp_instance_get_remote_address(instance1, &remote_address);
2010 if (ast_sockaddr_isnull(&remote_address)) {
2011 ast_debug(1, "Remote address is null, most likely RTP has been stopped\n");
2015 /* Send the packet back out */
2016 res = rtp_sendto(instance1, (void *)rtpheader, len, 0, &remote_address);
2018 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))) {
2019 ast_log(LOG_WARNING,
2020 "RTP Transmission error of packet to %s: %s\n",
2021 ast_sockaddr_stringify(&remote_address),
2023 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
2024 if (option_debug || rtpdebug)
2025 ast_log(LOG_WARNING,
2026 "RTP NAT: Can't write RTP to private "
2027 "address %s, waiting for other end to "
2029 ast_sockaddr_stringify(&remote_address));
2030 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
2033 } else if (rtp_debug_test_addr(&remote_address)) {
2034 ast_verbose("Sent RTP P2P packet to %s (type %-2.2d, len %-6.6u)\n",
2035 ast_sockaddr_stringify(&remote_address),
2036 bridged_payload, len - hdrlen);
2042 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
2044 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2045 struct ast_sockaddr addr;
2046 int res, hdrlen = 12, version, payloadtype, padding, mark, ext, cc, prev_seqno;
2047 unsigned int *rtpheader = (unsigned int*)(rtp->rawdata + AST_FRIENDLY_OFFSET), seqno, ssrc, timestamp;
2048 struct ast_rtp_payload_type payload;
2049 struct ast_sockaddr remote_address = { {0,} };
2050 struct frame_list frames;
2052 /* If this is actually RTCP let's hop on over and handle it */
2055 return ast_rtcp_read(instance);
2057 return &ast_null_frame;
2060 /* If we are currently sending DTMF to the remote party send a continuation packet */
2061 if (rtp->sending_digit) {
2062 ast_rtp_dtmf_continuation(instance);
2065 /* Actually read in the data from the socket */
2066 if ((res = rtp_recvfrom(instance, rtp->rawdata + AST_FRIENDLY_OFFSET,
2067 sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0,
2069 ast_assert(errno != EBADF);
2070 if (errno != EAGAIN) {
2071 ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
2074 return &ast_null_frame;
2077 /* Make sure the data that was read in is actually enough to make up an RTP packet */
2079 ast_log(LOG_WARNING, "RTP Read too short\n");
2080 return &ast_null_frame;
2083 /* If strict RTP protection is enabled see if we need to learn the remote address or if we need to drop the packet */
2084 if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
2085 ast_sockaddr_copy(&rtp->strict_rtp_address, &addr);
2086 rtp->strict_rtp_state = STRICT_RTP_CLOSED;
2087 } else if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
2088 if (ast_sockaddr_cmp(&rtp->strict_rtp_address, &addr)) {
2089 /* Hmm, not the strict addres. Perhaps we're getting audio from the alternate? */
2090 if (!ast_sockaddr_cmp(&rtp->alt_rtp_address, &addr)) {
2091 /* ooh, we did! You're now the new expected address, son! */
2092 ast_sockaddr_copy(&rtp->strict_rtp_address,
2095 const char *real_addr = ast_strdupa(ast_sockaddr_stringify(&addr));
2096 const char *expected_addr = ast_strdupa(ast_sockaddr_stringify(&rtp->strict_rtp_address));
2098 ast_debug(1, "Received RTP packet from %s, dropping due to strict RTP protection. Expected it to be from %s\n",
2099 real_addr, expected_addr);
2101 return &ast_null_frame;
2106 /* Get fields and verify this is an RTP packet */
2107 seqno = ntohl(rtpheader[0]);
2109 ast_rtp_instance_get_remote_address(instance, &remote_address);
2111 if (!(version = (seqno & 0xC0000000) >> 30)) {
2112 struct sockaddr_in addr_tmp;
2113 struct ast_sockaddr addr_v4;
2114 if (ast_sockaddr_is_ipv4(&addr)) {
2115 ast_sockaddr_to_sin(&addr, &addr_tmp);
2116 } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
2117 ast_debug(1, "Using IPv6 mapped address %s for STUN\n",
2118 ast_sockaddr_stringify(&addr));
2119 ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
2121 ast_debug(1, "Cannot do STUN for non IPv4 address %s\n",
2122 ast_sockaddr_stringify(&addr));
2123 return &ast_null_frame;
2125 if ((ast_stun_handle_packet(rtp->s, &addr_tmp, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == AST_STUN_ACCEPT) &&
2126 ast_sockaddr_isnull(&remote_address)) {
2127 ast_sockaddr_from_sin(&addr, &addr_tmp);
2128 ast_rtp_instance_set_remote_address(instance, &addr);
2130 return &ast_null_frame;
2133 /* If symmetric RTP is enabled see if the remote side is not what we expected and change where we are sending audio */
2134 if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
2135 if (ast_sockaddr_cmp(&remote_address, &addr)) {
2136 ast_rtp_instance_set_remote_address(instance, &addr);
2137 ast_sockaddr_copy(&remote_address, &addr);
2139 ast_sockaddr_copy(&rtp->rtcp->them, &addr);
2140 ast_sockaddr_set_port(&rtp->rtcp->them, ast_sockaddr_port(&addr) + 1);
2143 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
2145 ast_debug(0, "RTP NAT: Got audio from other end. Now sending to address %s\n",
2146 ast_sockaddr_stringify(&remote_address));
2150 /* If we are directly bridged to another instance send the audio directly out */
2151 if (ast_rtp_instance_get_bridged(instance) && !bridge_p2p_rtp_write(instance, rtpheader, res, hdrlen)) {
2152 return &ast_null_frame;
2155 /* If the version is not what we expected by this point then just drop the packet */
2157 return &ast_null_frame;
2160 /* Pull out the various other fields we will need */
2161 payloadtype = (seqno & 0x7f0000) >> 16;
2162 padding = seqno & (1 << 29);
2163 mark = seqno & (1 << 23);
2164 ext = seqno & (1 << 28);
2165 cc = (seqno & 0xF000000) >> 24;
2167 timestamp = ntohl(rtpheader[1]);
2168 ssrc = ntohl(rtpheader[2]);
2170 AST_LIST_HEAD_INIT_NOLOCK(&frames);
2171 /* Force a marker bit and change SSRC if the SSRC changes */
2172 if (rtp->rxssrc && rtp->rxssrc != ssrc) {
2173 struct ast_frame *f, srcupdate = {
2175 .subclass.integer = AST_CONTROL_SRCCHANGE,
2180 ast_debug(1, "Forcing Marker bit, because SSRC has changed\n");
2185 f = ast_frisolate(&srcupdate);
2186 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
2191 /* Remove any padding bytes that may be present */
2193 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
2196 /* Skip over any CSRC fields */
2201 /* Look for any RTP extensions, currently we do not support any */
2203 hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
2207 profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
2208 if (profile == 0x505a)
2209 ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
2211 ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
2215 /* Make sure after we potentially mucked with the header length that it is once again valid */
2217 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d\n", res, hdrlen);
2218 return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
2222 if (rtp->rxcount == 1) {
2223 rtp->seedrxseqno = seqno;
2226 /* Do not schedule RR if RTCP isn't run */
2227 if (rtp->rtcp && !ast_sockaddr_isnull(&rtp->rtcp->them) && rtp->rtcp->schedid < 1) {
2228 /* Schedule transmission of Receiver Report */
2229 ao2_ref(instance, +1);
2230 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
2231 if (rtp->rtcp->schedid < 0) {
2232 ao2_ref(instance, -1);
2233 ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
2236 if ((int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
2237 rtp->cycles += RTP_SEQ_MOD;
2239 prev_seqno = rtp->lastrxseqno;
2240 rtp->lastrxseqno = seqno;
2242 if (!rtp->themssrc) {
2243 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
2246 if (rtp_debug_test_addr(&addr)) {
2247 ast_verbose("Got RTP packet from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2248 ast_sockaddr_stringify(&addr),
2249 payloadtype, seqno, timestamp,res - hdrlen);
2252 payload = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), payloadtype);
2254 /* If the payload is not actually an Asterisk one but a special one pass it off to the respective handler */
2255 if (!payload.asterisk_format) {
2256 struct ast_frame *f = NULL;
2257 if (payload.rtp_code == AST_RTP_DTMF) {
2258 /* process_dtmf_rfc2833 may need to return multiple frames. We do this
2259 * by passing the pointer to the frame list to it so that the method
2260 * can append frames to the list as needed.
2262 process_dtmf_rfc2833(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark, &frames);
2263 } else if (payload.rtp_code == AST_RTP_CISCO_DTMF) {
2264 f = process_dtmf_cisco(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
2265 } else if (payload.rtp_code == AST_RTP_CN) {
2266 f = process_cn_rfc3389(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
2268 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n",
2270 ast_sockaddr_stringify(&remote_address));
2274 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
2276 /* Even if no frame was returned by one of the above methods,
2277 * we may have a frame to return in our frame list
2279 if (!AST_LIST_EMPTY(&frames)) {
2280 return AST_LIST_FIRST(&frames);
2282 return &ast_null_frame;
2285 ast_format_copy(&rtp->lastrxformat, &payload.format);
2286 ast_format_copy(&rtp->f.subclass.format, &payload.format);
2287 rtp->f.frametype = (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_AUDIO) ? AST_FRAME_VOICE : (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_VIDEO) ? AST_FRAME_VIDEO : AST_FRAME_TEXT;
2289 rtp->rxseqno = seqno;
2291 if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
2292 rtp->dtmf_timeout = 0;
2295 struct ast_frame *f;
2296 f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0);
2297 f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
2299 rtp->dtmf_timeout = rtp->dtmf_duration = 0;
2300 AST_LIST_INSERT_TAIL(&frames, f, frame_list);
2301 return AST_LIST_FIRST(&frames);
2305 rtp->lastrxts = timestamp;
2309 rtp->f.datalen = res - hdrlen;
2310 rtp->f.data.ptr = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
2311 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
2312 rtp->f.seqno = seqno;
2314 if (rtp->f.subclass.format.id == AST_FORMAT_T140 && (int)seqno - (prev_seqno+1) > 0 && (int)seqno - (prev_seqno+1) < 10) {
2315 unsigned char *data = rtp->f.data.ptr;
2317 memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
2324 if (rtp->f.subclass.format.id == AST_FORMAT_T140RED) {
2325 unsigned char *data = rtp->f.data.ptr;
2326 unsigned char *header_end;
2327 int num_generations;
2330 int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
2333 ast_format_set(&rtp->f.subclass.format, AST_FORMAT_T140, 0);
2334 header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
2335 if (header_end == NULL) {
2336 return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
2340 header_length = header_end - data;
2341 num_generations = header_length / 4;
2342 len = header_length;
2345 for (x = 0; x < num_generations; x++)
2346 len += data[x * 4 + 3];
2348 if (!(rtp->f.datalen - len))
2349 return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
2351 rtp->f.data.ptr += len;
2352 rtp->f.datalen -= len;
2353 } else if (diff > num_generations && diff < 10) {
2355 rtp->f.data.ptr += len;
2356 rtp->f.datalen -= len;
2358 data = rtp->f.data.ptr;
2363 for ( x = 0; x < num_generations - diff; x++)
2364 len += data[x * 4 + 3];
2366 rtp->f.data.ptr += len;
2367 rtp->f.datalen -= len;
2371 if (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_AUDIO) {
2372 rtp->f.samples = ast_codec_get_samples(&rtp->f);
2373 if (ast_format_is_slinear(&rtp->f.subclass.format)) {
2374 ast_frame_byteswap_be(&rtp->f);
2376 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
2377 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
2378 ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
2379 rtp->f.ts = timestamp / (rtp_get_rate(&rtp->f.subclass.format) / 1000);
2380 rtp->f.len = rtp->f.samples / ((ast_format_rate(&rtp->f.subclass.format) / 1000));
2381 } else if (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_VIDEO) {
2382 /* Video -- samples is # of samples vs. 90000 */
2383 if (!rtp->lastividtimestamp)
2384 rtp->lastividtimestamp = timestamp;
2385 rtp->f.samples = timestamp - rtp->lastividtimestamp;
2386 rtp->lastividtimestamp = timestamp;
2387 rtp->f.delivery.tv_sec = 0;
2388 rtp->f.delivery.tv_usec = 0;
2389 /* Pass the RTP marker bit as bit */
2391 ast_format_set_video_mark(&rtp->f.subclass.format);
2394 /* TEXT -- samples is # of samples vs. 1000 */
2395 if (!rtp->lastitexttimestamp)
2396 rtp->lastitexttimestamp = timestamp;
2397 rtp->f.samples = timestamp - rtp->lastitexttimestamp;
2398 rtp->lastitexttimestamp = timestamp;
2399 rtp->f.delivery.tv_sec = 0;
2400 rtp->f.delivery.tv_usec = 0;
2403 AST_LIST_INSERT_TAIL(&frames, &rtp->f, frame_list);
2404 return AST_LIST_FIRST(&frames);
2407 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
2409 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2411 if (property == AST_RTP_PROPERTY_RTCP) {
2414 ast_debug(1, "Ignoring duplicate RTCP property on RTP instance '%p'\n", instance);
2417 /* Setup RTCP to be activated on the next RTP write */
2418 if (!(rtp->rtcp = ast_calloc(1, sizeof(*rtp->rtcp)))) {
2422 /* Grab the IP address and port we are going to use */
2423 ast_rtp_instance_get_local_address(instance, &rtp->rtcp->us);
2424 ast_sockaddr_set_port(&rtp->rtcp->us,
2425 ast_sockaddr_port(&rtp->rtcp->us) + 1);
2428 create_new_socket("RTCP",
2429 ast_sockaddr_is_ipv4(&rtp->rtcp->us) ?
2431 ast_sockaddr_is_ipv6(&rtp->rtcp->us) ?
2432 AF_INET6 : -1)) < 0) {
2433 ast_debug(1, "Failed to create a new socket for RTCP on instance '%p'\n", instance);
2434 ast_free(rtp->rtcp);
2439 /* 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 */
2440 if (ast_bind(rtp->rtcp->s, &rtp->rtcp->us)) {
2441 ast_debug(1, "Failed to setup RTCP on RTP instance '%p'\n", instance);
2442 close(rtp->rtcp->s);
2443 ast_free(rtp->rtcp);
2448 ast_debug(1, "Setup RTCP on RTP instance '%p'\n", instance);
2449 rtp->rtcp->schedid = -1;
2454 if (rtp->rtcp->schedid > 0) {
2455 if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
2456 /* Successfully cancelled scheduler entry. */
2457 ao2_ref(instance, -1);
2459 /* Unable to cancel scheduler entry */
2460 ast_debug(1, "Failed to tear down RTCP on RTP instance '%p'\n", instance);
2463 rtp->rtcp->schedid = -1;
2465 close(rtp->rtcp->s);
2466 ast_free(rtp->rtcp);
2476 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp)
2478 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2480 return rtcp ? (rtp->rtcp ? rtp->rtcp->s : -1) : rtp->s;
2483 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
2485 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2488 ast_debug(1, "Setting RTCP address on RTP instance '%p'\n", instance);
2489 ast_sockaddr_copy(&rtp->rtcp->them, addr);
2490 if (!ast_sockaddr_isnull(addr)) {
2491 ast_sockaddr_set_port(&rtp->rtcp->them,
2492 ast_sockaddr_port(addr) + 1);
2499 rtp->strict_rtp_state = STRICT_RTP_LEARN;
2505 static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
2507 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2509 /* No need to futz with rtp->rtcp here because ast_rtcp_read is already able to adjust if receiving
2510 * RTCP from an "unexpected" source
2512 ast_sockaddr_copy(&rtp->alt_rtp_address, addr);
2517 /*! \brief Write t140 redundacy frame
2518 * \param data primary data to be buffered
2520 static int red_write(const void *data)
2522 struct ast_rtp_instance *instance = (struct ast_rtp_instance*) data;
2523 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2525 ast_rtp_write(instance, &rtp->red->t140);
2530 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
2532 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2535 if (!(rtp->red = ast_calloc(1, sizeof(*rtp->red)))) {
2539 rtp->red->t140.frametype = AST_FRAME_TEXT;
2540 ast_format_set(&rtp->red->t140.subclass.format, AST_FORMAT_T140RED, 0);
2541 rtp->red->t140.data.ptr = &rtp->red->buf_data;
2543 rtp->red->t140.ts = 0;
2544 rtp->red->t140red = rtp->red->t140;
2545 rtp->red->t140red.data.ptr = &rtp->red->t140red_data;
2546 rtp->red->t140red.datalen = 0;
2547 rtp->red->ti = buffer_time;
2548 rtp->red->num_gen = generations;
2549 rtp->red->hdrlen = generations * 4 + 1;
2550 rtp->red->prev_ts = 0;
2552 for (x = 0; x < generations; x++) {
2553 rtp->red->pt[x] = payloads[x];
2554 rtp->red->pt[x] |= 1 << 7; /* mark redundant generations pt */
2555 rtp->red->t140red_data[x*4] = rtp->red->pt[x];
2557 rtp->red->t140red_data[x*4] = rtp->red->pt[x] = payloads[x]; /* primary pt */
2558 rtp->red->schedid = ast_sched_add(rtp->sched, generations, red_write, instance);
2560 rtp->red->t140.datalen = 0;
2565 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
2567 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2569 if (frame->datalen > -1) {
2570 struct rtp_red *red = rtp->red;
2571 memcpy(&red->buf_data[red->t140.datalen], frame->data.ptr, frame->datalen);
2572 red->t140.datalen += frame->datalen;
2573 red->t140.ts = frame->ts;
2579 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1)
2581 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance0);
2583 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2588 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
2590 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2596 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXCOUNT, -1, stats->txcount, rtp->txcount);
2597 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXCOUNT, -1, stats->rxcount, rtp->rxcount);
2599 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->txploss, rtp->rtcp->reported_lost);
2600 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);
2601 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_maxrxploss, rtp->rtcp->reported_maxlost);
2602 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_minrxploss, rtp->rtcp->reported_minlost);
2603 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_normdevrxploss, rtp->rtcp->reported_normdev_lost);
2604 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_stdevrxploss, rtp->rtcp->reported_stdev_lost);
2605 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_maxrxploss, rtp->rtcp->maxrxlost);
2606 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_minrxploss, rtp->rtcp->minrxlost);
2607 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_normdevrxploss, rtp->rtcp->normdev_rxlost);
2608 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_stdevrxploss, rtp->rtcp->stdev_rxlost);
2609 AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_LOSS);
2611 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->txjitter, rtp->rxjitter);
2612 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);
2613 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_maxjitter, rtp->rtcp->reported_maxjitter);
2614 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_minjitter, rtp->rtcp->reported_minjitter);
2615 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_normdevjitter, rtp->rtcp->reported_normdev_jitter);
2616 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_stdevjitter, rtp->rtcp->reported_stdev_jitter);
2617 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_maxjitter, rtp->rtcp->maxrxjitter);
2618 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_minjitter, rtp->rtcp->minrxjitter);
2619 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_normdevjitter, rtp->rtcp->normdev_rxjitter);
2620 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_stdevjitter, rtp->rtcp->stdev_rxjitter);
2621 AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_JITTER);
2623 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->rtt, rtp->rtcp->rtt);
2624 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MAX_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->maxrtt, rtp->rtcp->maxrtt);
2625 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MIN_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->minrtt, rtp->rtcp->minrtt);
2626 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_NORMDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->normdevrtt, rtp->rtcp->normdevrtt);
2627 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_STDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->stdevrtt, rtp->rtcp->stdevrtt);
2628 AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_RTT);
2630 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_SSRC, -1, stats->local_ssrc, rtp->ssrc);
2631 AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_SSRC, -1, stats->remote_ssrc, rtp->themssrc);
2636 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1)
2638 /* If both sides are not using the same method of DTMF transmission
2639 * (ie: one is RFC2833, other is INFO... then we can not do direct media.
2640 * --------------------------------------------------
2641 * | DTMF Mode | HAS_DTMF | Accepts Begin Frames |
2642 * |-----------|------------|-----------------------|
2643 * | Inband | False | True |
2644 * | RFC2833 | True | True |
2645 * | SIP INFO | False | False |
2646 * --------------------------------------------------
2648 return (((ast_rtp_instance_get_prop(instance0, AST_RTP_PROPERTY_DTMF) != ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_DTMF)) ||
2649 (!chan0->tech->send_digit_begin != !chan1->tech->send_digit_begin)) ? 0 : 1);
2652 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username)
2654 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2655 struct sockaddr_in suggestion_tmp;
2657 ast_sockaddr_to_sin(suggestion, &suggestion_tmp);
2658 ast_stun_request(rtp->s, &suggestion_tmp, username, NULL);
2659 ast_sockaddr_from_sin(suggestion, &suggestion_tmp);
2662 static void ast_rtp_stop(struct ast_rtp_instance *instance)
2664 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2665 struct ast_sockaddr addr = { {0,} };
2667 if (rtp->rtcp && rtp->rtcp->schedid > 0) {
2668 if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
2669 /* successfully cancelled scheduler entry. */
2670 ao2_ref(instance, -1);
2672 rtp->rtcp->schedid = -1;
2676 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
2681 ast_rtp_instance_set_remote_address(instance, &addr);
2683 ast_sockaddr_setnull(&rtp->rtcp->them);
2686 ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
2689 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
2691 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2693 return ast_set_qos(rtp->s, tos, cos, desc);
2696 /*! \brief generate comfort noice (CNG) */
2697 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level)
2699 unsigned int *rtpheader;
2704 struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
2705 struct ast_sockaddr remote_address = { {0,} };
2707 ast_rtp_instance_get_remote_address(instance, &remote_address);
2709 if (ast_sockaddr_isnull(&remote_address)) {
2713 payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_CN);
2715 level = 127 - (level & 0x7f);
2717 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2719 /* Get a pointer to the header */
2720 rtpheader = (unsigned int *)data;
2721 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2722 rtpheader[1] = htonl(rtp->lastts);
2723 rtpheader[2] = htonl(rtp->ssrc);
2726 res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 1, 0, &remote_address);
2729 ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s: %s\n", ast_sockaddr_stringify(&remote_address), strerror(errno));
2730 } else if (rtp_debug_test_addr(&remote_address)) {
2731 ast_verbose("Sent Comfort Noise RTP packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2732 ast_sockaddr_stringify(&remote_address),
2733 AST_RTP_CN, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2739 static char *rtp_do_debug_ip(struct ast_cli_args *a)
2741 char *arg = ast_strdupa(a->argv[4]);
2742 char *debughost = NULL;
2743 char *debugport = NULL;
2745 if (!ast_sockaddr_parse(&rtpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
2746 ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
2749 rtpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
2750 ast_cli(a->fd, "RTP Debugging Enabled for address: %s\n",
2751 ast_sockaddr_stringify(&rtpdebugaddr));
2756 static char *rtcp_do_debug_ip(struct ast_cli_args *a)
2758 char *arg = ast_strdupa(a->argv[4]);
2759 char *debughost = NULL;
2760 char *debugport = NULL;
2762 if (!ast_sockaddr_parse(&rtcpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
2763 ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
2766 rtcpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
2767 ast_cli(a->fd, "RTCP Debugging Enabled for address: %s\n",
2768 ast_sockaddr_stringify(&rtcpdebugaddr));
2773 static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2777 e->command = "rtp set debug {on|off|ip}";
2779 "Usage: rtp set debug {on|off|ip host[:port]}\n"
2780 " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
2781 " specified, limit the dumped packets to those to and from\n"
2782 " the specified 'host' with optional port.\n";
2788 if (a->argc == e->args) { /* set on or off */
2789 if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
2791 memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
2792 ast_cli(a->fd, "RTP Debugging Enabled\n");
2794 } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
2796 ast_cli(a->fd, "RTP Debugging Disabled\n");
2799 } else if (a->argc == e->args +1) { /* ip */
2800 return rtp_do_debug_ip(a);
2803 return CLI_SHOWUSAGE; /* default, failure */
2806 static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2810 e->command = "rtcp set debug {on|off|ip}";
2812 "Usage: rtcp set debug {on|off|ip host[:port]}\n"
2813 " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
2814 " specified, limit the dumped packets to those to and from\n"
2815 " the specified 'host' with optional port.\n";
2821 if (a->argc == e->args) { /* set on or off */
2822 if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
2824 memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
2825 ast_cli(a->fd, "RTCP Debugging Enabled\n");
2827 } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
2829 ast_cli(a->fd, "RTCP Debugging Disabled\n");
2832 } else if (a->argc == e->args +1) { /* ip */
2833 return rtcp_do_debug_ip(a);
2836 return CLI_SHOWUSAGE; /* default, failure */
2839 static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2843 e->command = "rtcp set stats {on|off}";
2845 "Usage: rtcp set stats {on|off}\n"
2846 " Enable/Disable dumping of RTCP stats.\n";
2852 if (a->argc != e->args)
2853 return CLI_SHOWUSAGE;
2855 if (!strncasecmp(a->argv[e->args-1], "on", 2))
2857 else if (!strncasecmp(a->argv[e->args-1], "off", 3))
2860 return CLI_SHOWUSAGE;
2862 ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
2866 static struct ast_cli_entry cli_rtp[] = {
2867 AST_CLI_DEFINE(handle_cli_rtp_set_debug, "Enable/Disable RTP debugging"),
2868 AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging"),
2869 AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats"),
2872 static int rtp_reload(int reload)
2874 struct ast_config *cfg;
2876 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
2878 cfg = ast_config_load2("rtp.conf", "rtp", config_flags);
2879 if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
2883 rtpstart = DEFAULT_RTP_START;
2884 rtpend = DEFAULT_RTP_END;
2885 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2886 strictrtp = STRICT_RTP_CLOSED;
2888 if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
2890 if (rtpstart < MINIMUM_RTP_PORT)
2891 rtpstart = MINIMUM_RTP_PORT;
2892 if (rtpstart > MAXIMUM_RTP_PORT)
2893 rtpstart = MAXIMUM_RTP_PORT;
2895 if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
2897 if (rtpend < MINIMUM_RTP_PORT)
2898 rtpend = MINIMUM_RTP_PORT;
2899 if (rtpend > MAXIMUM_RTP_PORT)
2900 rtpend = MAXIMUM_RTP_PORT;
2902 if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
2903 rtcpinterval = atoi(s);
2904 if (rtcpinterval == 0)
2905 rtcpinterval = 0; /* Just so we're clear... it's zero */
2906 if (rtcpinterval < RTCP_MIN_INTERVALMS)
2907 rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
2908 if (rtcpinterval > RTCP_MAX_INTERVALMS)
2909 rtcpinterval = RTCP_MAX_INTERVALMS;
2911 if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
2913 nochecksums = ast_false(s) ? 1 : 0;
2916 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
2919 if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
2920 dtmftimeout = atoi(s);
2921 if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
2922 ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
2923 dtmftimeout, DEFAULT_DTMF_TIMEOUT);
2924 dtmftimeout = DEFAULT_DTMF_TIMEOUT;
2927 if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
2928 strictrtp = ast_true(s);
2930 ast_config_destroy(cfg);
2932 if (rtpstart >= rtpend) {
2933 ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
2934 rtpstart = DEFAULT_RTP_START;
2935 rtpend = DEFAULT_RTP_END;
2937 ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
2941 static int reload_module(void)
2947 static int load_module(void)
2949 if (ast_rtp_engine_register(&asterisk_rtp_engine)) {
2950 return AST_MODULE_LOAD_DECLINE;
2953 if (ast_cli_register_multiple(cli_rtp, ARRAY_LEN(cli_rtp))) {
2954 ast_rtp_engine_unregister(&asterisk_rtp_engine);
2955 return AST_MODULE_LOAD_DECLINE;
2960 return AST_MODULE_LOAD_SUCCESS;