2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, 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.
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
38 #include "asterisk/rtp.h"
39 #include "asterisk/pbx.h"
40 #include "asterisk/frame.h"
41 #include "asterisk/channel.h"
42 #include "asterisk/acl.h"
43 #include "asterisk/config.h"
44 #include "asterisk/lock.h"
45 #include "asterisk/utils.h"
46 #include "asterisk/netsock.h"
47 #include "asterisk/cli.h"
48 #include "asterisk/manager.h"
49 #include "asterisk/unaligned.h"
51 #define MAX_TIMESTAMP_SKEW 640
53 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
54 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
55 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
56 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
58 #define RTCP_PT_FUR 192
59 #define RTCP_PT_SR 200
60 #define RTCP_PT_RR 201
61 #define RTCP_PT_SDES 202
62 #define RTCP_PT_BYE 203
63 #define RTCP_PT_APP 204
67 #define DEFAULT_DTMF_TIMEOUT 3000 /*!< samples */
69 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
71 static int rtpstart; /*!< First port for RTP sessions (set in rtp.conf) */
72 static int rtpend; /*!< Last port for RTP sessions (set in rtp.conf) */
73 static int rtpdebug; /*!< Are we debugging? */
74 static int rtcpdebug; /*!< Are we debugging RTCP? */
75 static int rtcpstats; /*!< Are we debugging RTCP? */
76 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
77 static int stundebug; /*!< Are we debugging stun? */
78 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
79 static struct sockaddr_in rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
81 static int nochecksums;
85 enum strict_rtp_state {
86 STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
87 STRICT_RTP_LEARN, /*! Accept next packet as source */
88 STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
91 /* Uncomment this to enable more intense native bridging, but note: this is currently buggy */
92 /* #define P2P_INTENSE */
95 * \brief Structure representing a RTP session.
97 * RTP session is defined on page 9 of RFC 3550: "An association among a set of participants communicating with RTP. A participant may be involved in multiple RTP sessions at the same time [...]"
100 /*! \brief The value of each payload format mapping: */
101 struct rtpPayloadType {
102 int isAstFormat; /*!< whether the following code is an AST_FORMAT */
107 /*! \brief RTP session description */
111 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
112 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
113 unsigned int themssrc; /*!< Their SSRC */
116 unsigned int lastrxts;
117 unsigned int lastividtimestamp;
118 unsigned int lastovidtimestamp;
119 unsigned int lastitexttimestamp;
120 unsigned int lastotexttimestamp;
121 unsigned int lasteventseqn;
122 int lastrxseqno; /*!< Last received sequence number */
123 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
124 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
125 unsigned int rxcount; /*!< How many packets have we received? */
126 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
127 unsigned int txcount; /*!< How many packets have we sent? */
128 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
129 unsigned int cycles; /*!< Shifted count of sequence number cycles */
130 double rxjitter; /*!< Interarrival jitter at the moment */
131 double rxtransit; /*!< Relative transit time for previous packet */
135 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
136 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
137 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
139 /* DTMF Reception Variables */
141 unsigned int lastevent;
143 unsigned int dtmfsamples;
144 /* DTMF Transmission Variables */
145 unsigned int lastdigitts;
146 char sending_digit; /*!< boolean - are we sending digits */
147 char send_digit; /*!< digit we are sending */
152 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
153 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
154 struct timeval rxcore;
155 struct timeval txcore;
156 double drxcore; /*!< The double representation of the first received packet */
157 struct timeval lastrx; /*!< timeval when we last received a packet */
158 struct timeval dtmfmute;
159 struct ast_smoother *smoother;
161 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
162 unsigned short rxseqno;
163 struct sched_context *sched;
164 struct io_context *io;
166 ast_rtp_callback callback;
168 ast_mutex_t bridge_lock;
170 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
171 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
172 int rtp_lookup_code_cache_code;
173 int rtp_lookup_code_cache_result;
174 struct ast_rtcp *rtcp;
175 struct ast_codec_pref pref;
176 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
178 enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
179 struct sockaddr_in strict_rtp_address; /*!< Remote address information for strict RTP purposes */
181 int set_marker_bit:1; /*!< Whether to set the marker bit or not */
185 static struct ast_frame *red_t140_to_red(struct rtp_red *red);
186 static int red_write(const void *data);
189 struct ast_frame t140; /*!< Primary data */
190 struct ast_frame t140red; /*!< Redundant t140*/
191 unsigned char pt[RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
192 unsigned char ts[RED_MAX_GENERATION]; /*!< Time stamps */
193 unsigned char len[RED_MAX_GENERATION]; /*!< length of each generation */
194 int num_gen; /*!< Number of generations */
195 int schedid; /*!< Timer id */
196 int ti; /*!< How long to buffer data before send */
197 unsigned char t140red_data[64000];
198 unsigned char buf_data[64000]; /*!< buffered primary data */
203 /* Forward declarations */
204 static int ast_rtcp_write(const void *data);
205 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
206 static int ast_rtcp_write_sr(const void *data);
207 static int ast_rtcp_write_rr(const void *data);
208 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
209 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
210 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
212 #define FLAG_3389_WARNING (1 << 0)
213 #define FLAG_NAT_ACTIVE (3 << 1)
214 #define FLAG_NAT_INACTIVE (0 << 1)
215 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
216 #define FLAG_HAS_DTMF (1 << 3)
217 #define FLAG_P2P_SENT_MARK (1 << 4)
218 #define FLAG_P2P_NEED_DTMF (1 << 5)
219 #define FLAG_CALLBACK_MODE (1 << 6)
220 #define FLAG_DTMF_COMPENSATE (1 << 7)
221 #define FLAG_HAS_STUN (1 << 8)
224 * \brief Structure defining an RTCP session.
226 * The concept "RTCP session" is not defined in RFC 3550, but since
227 * this structure is analogous to ast_rtp, which tracks a RTP session,
228 * it is logical to think of this as a RTCP session.
230 * RTCP packet is defined on page 9 of RFC 3550.
235 int s; /*!< Socket */
236 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
237 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
238 unsigned int soc; /*!< What they told us */
239 unsigned int spc; /*!< What they told us */
240 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
241 struct timeval rxlsr; /*!< Time when we got their last SR */
242 struct timeval txlsr; /*!< Time when we sent or last SR*/
243 unsigned int expected_prior; /*!< no. packets in previous interval */
244 unsigned int received_prior; /*!< no. packets received in previous interval */
245 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
246 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
247 unsigned int sr_count; /*!< number of SRs we've sent */
248 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
249 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
250 double rtt; /*!< Last reported rtt */
251 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
252 unsigned int reported_lost; /*!< Reported lost packets in their RR */
253 char quality[AST_MAX_USER_FIELD];
254 char quality_jitter[AST_MAX_USER_FIELD];
255 char quality_loss[AST_MAX_USER_FIELD];
256 char quality_rtt[AST_MAX_USER_FIELD];
258 double reported_maxjitter;
259 double reported_minjitter;
260 double reported_normdev_jitter;
261 double reported_stdev_jitter;
262 unsigned int reported_jitter_count;
264 double reported_maxlost;
265 double reported_minlost;
266 double reported_normdev_lost;
267 double reported_stdev_lost;
272 double normdev_rxlost;
274 unsigned int rxlost_count;
278 double normdev_rxjitter;
279 double stdev_rxjitter;
280 unsigned int rxjitter_count;
285 unsigned int rtt_count;
290 * \brief STUN support code
292 * This code provides some support for doing STUN transactions.
293 * Eventually it should be moved elsewhere as other protocols
294 * than RTP can benefit from it - e.g. SIP.
295 * STUN is described in RFC3489 and it is based on the exchange
296 * of UDP packets between a client and one or more servers to
297 * determine the externally visible address (and port) of the client
298 * once it has gone through the NAT boxes that connect it to the
300 * The simplest request packet is just the header defined in
301 * struct stun_header, and from the response we may just look at
302 * one attribute, STUN_MAPPED_ADDRESS, that we find in the response.
303 * By doing more transactions with different server addresses we
304 * may determine more about the behaviour of the NAT boxes, of
305 * course - the details are in the RFC.
307 * All STUN packets start with a simple header made of a type,
308 * length (excluding the header) and a 16-byte random transaction id.
309 * Following the header we may have zero or more attributes, each
310 * structured as a type, length and a value (whose format depends
311 * on the type, but often contains addresses).
312 * Of course all fields are in network format.
315 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
318 unsigned short msgtype;
319 unsigned short msglen;
321 unsigned char ies[0];
322 } __attribute__((packed));
327 unsigned char value[0];
328 } __attribute__((packed));
331 * The format normally used for addresses carried by STUN messages.
334 unsigned char unused;
335 unsigned char family;
338 } __attribute__((packed));
340 #define STUN_IGNORE (0)
341 #define STUN_ACCEPT (1)
343 /*! \brief STUN message types
344 * 'BIND' refers to transactions used to determine the externally
345 * visible addresses. 'SEC' refers to transactions used to establish
346 * a session key for subsequent requests.
347 * 'SEC' functionality is not supported here.
350 #define STUN_BINDREQ 0x0001
351 #define STUN_BINDRESP 0x0101
352 #define STUN_BINDERR 0x0111
353 #define STUN_SECREQ 0x0002
354 #define STUN_SECRESP 0x0102
355 #define STUN_SECERR 0x0112
357 /*! \brief Basic attribute types in stun messages.
358 * Messages can also contain custom attributes (codes above 0x7fff)
360 #define STUN_MAPPED_ADDRESS 0x0001
361 #define STUN_RESPONSE_ADDRESS 0x0002
362 #define STUN_CHANGE_REQUEST 0x0003
363 #define STUN_SOURCE_ADDRESS 0x0004
364 #define STUN_CHANGED_ADDRESS 0x0005
365 #define STUN_USERNAME 0x0006
366 #define STUN_PASSWORD 0x0007
367 #define STUN_MESSAGE_INTEGRITY 0x0008
368 #define STUN_ERROR_CODE 0x0009
369 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
370 #define STUN_REFLECTED_FROM 0x000b
372 /*! \brief helper function to print message names */
373 static const char *stun_msg2str(int msg)
377 return "Binding Request";
379 return "Binding Response";
381 return "Binding Error Response";
383 return "Shared Secret Request";
385 return "Shared Secret Response";
387 return "Shared Secret Error Response";
389 return "Non-RFC3489 Message";
392 /*! \brief helper function to print attribute names */
393 static const char *stun_attr2str(int msg)
396 case STUN_MAPPED_ADDRESS:
397 return "Mapped Address";
398 case STUN_RESPONSE_ADDRESS:
399 return "Response Address";
400 case STUN_CHANGE_REQUEST:
401 return "Change Request";
402 case STUN_SOURCE_ADDRESS:
403 return "Source Address";
404 case STUN_CHANGED_ADDRESS:
405 return "Changed Address";
410 case STUN_MESSAGE_INTEGRITY:
411 return "Message Integrity";
412 case STUN_ERROR_CODE:
414 case STUN_UNKNOWN_ATTRIBUTES:
415 return "Unknown Attributes";
416 case STUN_REFLECTED_FROM:
417 return "Reflected From";
419 return "Non-RFC3489 Attribute";
422 /*! \brief here we store credentials extracted from a message */
424 const char *username;
425 const char *password;
428 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
431 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
432 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
433 switch (ntohs(attr->attr)) {
435 state->username = (const char *) (attr->value);
438 state->password = (const char *) (attr->value);
442 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
443 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
448 /*! \brief append a string to an STUN message */
449 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
451 int size = sizeof(**attr) + strlen(s);
453 (*attr)->attr = htons(attrval);
454 (*attr)->len = htons(strlen(s));
455 memcpy((*attr)->value, s, strlen(s));
456 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
462 /*! \brief append an address to an STUN message */
463 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
465 int size = sizeof(**attr) + 8;
466 struct stun_addr *addr;
468 (*attr)->attr = htons(attrval);
469 (*attr)->len = htons(8);
470 addr = (struct stun_addr *)((*attr)->value);
473 addr->port = sin->sin_port;
474 addr->addr = sin->sin_addr.s_addr;
475 (*attr) = (struct stun_attr *)((*attr)->value + 8);
481 /*! \brief wrapper to send an STUN message */
482 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
484 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
485 (struct sockaddr *)dst, sizeof(*dst));
488 /*! \brief helper function to generate a random request id */
489 static void stun_req_id(struct stun_header *req)
492 for (x = 0; x < 4; x++)
493 req->id.id[x] = ast_random();
496 size_t ast_rtp_alloc_size(void)
498 return sizeof(struct ast_rtp);
501 /*! \brief callback type to be invoked on stun responses. */
502 typedef int (stun_cb_f)(struct stun_attr *attr, void *arg);
504 /*! \brief handle an incoming STUN message.
506 * Do some basic sanity checks on packet size and content,
507 * try to extract a bit of information, and possibly reply.
508 * At the moment this only processes BIND requests, and returns
509 * the externally visible address of the request.
510 * If a callback is specified, invoke it with the attribute.
512 static int stun_handle_packet(int s, struct sockaddr_in *src,
513 unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
515 struct stun_header *hdr = (struct stun_header *)data;
516 struct stun_attr *attr;
517 struct stun_state st;
518 int ret = STUN_IGNORE;
521 /* On entry, 'len' is the length of the udp payload. After the
522 * initial checks it becomes the size of unprocessed options,
523 * while 'data' is advanced accordingly.
525 if (len < sizeof(struct stun_header)) {
526 ast_debug(1, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
529 len -= sizeof(struct stun_header);
530 data += sizeof(struct stun_header);
531 x = ntohs(hdr->msglen); /* len as advertised in the message */
533 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), x);
535 ast_debug(1, "Scrambled STUN packet length (got %d, expecting %d)\n", x, (int)len);
538 memset(&st, 0, sizeof(st));
540 if (len < sizeof(struct stun_attr)) {
541 ast_debug(1, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
544 attr = (struct stun_attr *)data;
545 /* compute total attribute length */
546 x = ntohs(attr->len) + sizeof(struct stun_attr);
548 ast_debug(1, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x, (int)len);
553 if (stun_process_attr(&st, attr)) {
554 ast_debug(1, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
557 /* Clear attribute id: in case previous entry was a string,
558 * this will act as the terminator for the string.
564 /* Null terminate any string.
565 * XXX NOTE, we write past the size of the buffer passed by the
566 * caller, so this is potentially dangerous. The only thing that
567 * saves us is that usually we read the incoming message in a
568 * much larger buffer in the struct ast_rtp
572 /* Now prepare to generate a reply, which at the moment is done
573 * only for properly formed (len == 0) STUN_BINDREQ messages.
576 unsigned char respdata[1024];
577 struct stun_header *resp = (struct stun_header *)respdata;
578 int resplen = 0; /* len excluding header */
579 int respleft = sizeof(respdata) - sizeof(struct stun_header);
584 attr = (struct stun_attr *)resp->ies;
585 switch (ntohs(hdr->msgtype)) {
588 ast_verbose("STUN Bind Request, username: %s\n",
589 st.username ? st.username : "<none>");
591 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
592 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
593 resp->msglen = htons(resplen);
594 resp->msgtype = htons(STUN_BINDRESP);
595 stun_send(s, src, resp);
600 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
606 /*! \brief Extract the STUN_MAPPED_ADDRESS from the stun response.
607 * This is used as a callback for stun_handle_response
608 * when called from ast_stun_request.
610 static int stun_get_mapped(struct stun_attr *attr, void *arg)
612 struct stun_addr *addr = (struct stun_addr *)(attr + 1);
613 struct sockaddr_in *sa = (struct sockaddr_in *)arg;
615 if (ntohs(attr->attr) != STUN_MAPPED_ADDRESS || ntohs(attr->len) != 8)
616 return 1; /* not us. */
617 sa->sin_port = addr->port;
618 sa->sin_addr.s_addr = addr->addr;
622 /*! \brief Generic STUN request
623 * Send a generic stun request to the server specified,
624 * possibly waiting for a reply and filling the 'reply' field with
625 * the externally visible address. Note that in this case the request
627 * (Note, the interface may change slightly in the future).
629 * \param s the socket used to send the request
630 * \param dst the address of the STUN server
631 * \param username if non null, add the username in the request
632 * \param answer if non null, the function waits for a response and
633 * puts here the externally visible address.
634 * \return 0 on success, other values on error.
636 int ast_stun_request(int s, struct sockaddr_in *dst,
637 const char *username, struct sockaddr_in *answer)
639 struct stun_header *req;
640 unsigned char reqdata[1024];
642 struct stun_attr *attr;
646 req = (struct stun_header *)reqdata;
649 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
652 attr = (struct stun_attr *)req->ies;
654 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
655 req->msglen = htons(reqlen);
656 req->msgtype = htons(STUN_BINDREQ);
657 for (retry = 0; retry < 3; retry++) { /* XXX make retries configurable */
658 /* send request, possibly wait for reply */
659 unsigned char reply_buf[1024];
661 struct timeval to = { 3, 0 }; /* timeout, make it configurable */
662 struct sockaddr_in src;
665 res = stun_send(s, dst, req);
667 ast_log(LOG_WARNING, "ast_stun_request send #%d failed error %d, retry\n",
675 res = ast_select(s + 1, &rfds, NULL, NULL, &to);
676 if (res <= 0) /* timeout or error */
678 bzero(&src, sizeof(src));
679 srclen = sizeof(src);
680 /* XXX pass -1 in the size, because stun_handle_packet might
681 * write past the end of the buffer.
683 res = recvfrom(s, reply_buf, sizeof(reply_buf) - 1,
684 0, (struct sockaddr *)&src, &srclen);
686 ast_log(LOG_WARNING, "ast_stun_request recvfrom #%d failed error %d, retry\n",
690 bzero(answer, sizeof(struct sockaddr_in));
691 stun_handle_packet(s, &src, reply_buf, res,
692 stun_get_mapped, answer);
693 res = 0; /* signal regular exit */
699 /*! \brief send a STUN BIND request to the given destination.
700 * Optionally, add a username if specified.
702 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
704 ast_stun_request(rtp->s, suggestion, username, NULL);
707 /*! \brief List of current sessions */
708 static AST_RWLIST_HEAD_STATIC(protos, ast_rtp_protocol);
710 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
712 unsigned int sec, usec, frac;
713 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
715 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
720 int ast_rtp_fd(struct ast_rtp *rtp)
725 int ast_rtcp_fd(struct ast_rtp *rtp)
732 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
734 unsigned int interval;
735 /*! \todo XXX Do a more reasonable calculation on this one
736 * Look in RFC 3550 Section A.7 for an example*/
737 interval = rtcpinterval;
741 /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
742 void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
744 rtp->rtptimeout = (-1) * rtp->rtptimeout;
745 rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
748 /*! \brief Set rtp timeout */
749 void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
751 rtp->rtptimeout = timeout;
754 /*! \brief Set rtp hold timeout */
755 void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
757 rtp->rtpholdtimeout = timeout;
760 /*! \brief set RTP keepalive interval */
761 void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
763 rtp->rtpkeepalive = period;
766 /*! \brief Get rtp timeout */
767 int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
769 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
771 return rtp->rtptimeout;
774 /*! \brief Get rtp hold timeout */
775 int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
777 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
779 return rtp->rtpholdtimeout;
782 /*! \brief Get RTP keepalive interval */
783 int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
785 return rtp->rtpkeepalive;
788 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
793 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
795 rtp->callback = callback;
798 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
803 int ast_rtp_getnat(struct ast_rtp *rtp)
805 return ast_test_flag(rtp, FLAG_NAT_ACTIVE);
808 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
810 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
813 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
815 ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
818 void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
820 ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
823 static void rtp_bridge_lock(struct ast_rtp *rtp)
826 ast_mutex_lock(&rtp->bridge_lock);
831 static void rtp_bridge_unlock(struct ast_rtp *rtp)
834 ast_mutex_unlock(&rtp->bridge_lock);
839 /*! \brief Calculate normal deviation */
840 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
842 normdev = normdev * sample_count + sample;
845 return normdev / sample_count;
848 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
851 for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
852 return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
853 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
856 #define SQUARE(x) ((x) * (x))
858 stddev = sample_count * stddev;
862 ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
863 ( SQUARE(sample - normdev_curent) / sample_count );
868 static struct ast_frame *send_dtmf(struct ast_rtp *rtp, enum ast_frame_type type)
870 if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
871 (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
872 ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
874 rtp->dtmfsamples = 0;
875 return &ast_null_frame;
877 ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
878 if (rtp->resp == 'X') {
879 rtp->f.frametype = AST_FRAME_CONTROL;
880 rtp->f.subclass = AST_CONTROL_FLASH;
882 rtp->f.frametype = type;
883 rtp->f.subclass = rtp->resp;
893 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
897 if (rtpdebugaddr.sin_addr.s_addr) {
898 if (((ntohs(rtpdebugaddr.sin_port) != 0)
899 && (rtpdebugaddr.sin_port != addr->sin_port))
900 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
906 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
910 if (rtcpdebugaddr.sin_addr.s_addr) {
911 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
912 && (rtcpdebugaddr.sin_port != addr->sin_port))
913 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
920 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
924 struct ast_frame *f = NULL;
929 /* We should have at least 4 bytes in RTP data */
933 /* The format of Cisco RTP DTMF packet looks like next:
934 +0 - sequence number of DTMF RTP packet (begins from 1,
937 +1 (bit 0) - flaps by different DTMF digits delimited by audio
938 or repeated digit without audio???
939 +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
940 then falls to 0 at its end)
941 +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
942 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
943 by each new packet and thus provides some redudancy.
945 Sample of Cisco RTP DTMF packet is (all data in hex):
946 19 07 00 02 12 02 20 02
947 showing end of DTMF digit '2'.
950 27 07 00 02 0A 02 20 02
951 28 06 20 02 00 02 0A 02
952 shows begin of new digit '2' with very short pause (20 ms) after
953 previous digit '2'. Bit +1.0 flips at begin of new digit.
955 Cisco RTP DTMF packets comes as replacement of audio RTP packets
956 so its uses the same sequencing and timestamping rules as replaced
957 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
958 on audio framing parameters. Marker bit isn't used within stream of
959 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
960 are not sequential at borders between DTMF and audio streams,
966 event = data[3] & 0x1f;
968 if (option_debug > 2 || rtpdebug)
969 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);
972 } else if (event < 11) {
974 } else if (event < 12) {
976 } else if (event < 16) {
977 resp = 'A' + (event - 12);
978 } else if (event < 17) {
981 if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
983 /* Why we should care on DTMF compensation at reception? */
984 if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
985 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
986 rtp->dtmfsamples = 0;
988 } else if ((rtp->resp == resp) && !power) {
989 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
990 f->samples = rtp->dtmfsamples * 8;
992 } else if (rtp->resp == resp)
993 rtp->dtmfsamples += 20 * 8;
994 rtp->dtmfcount = dtmftimeout;
999 * \brief Process RTP DTMF and events according to RFC 2833.
1001 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
1010 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp)
1013 unsigned int event_end;
1014 unsigned int samples;
1016 struct ast_frame *f = NULL;
1018 /* Figure out event, event end, and samples */
1019 event = ntohl(*((unsigned int *)(data)));
1021 event_end = ntohl(*((unsigned int *)(data)));
1024 samples = ntohl(*((unsigned int *)(data)));
1027 /* Print out debug if turned on */
1028 if (rtpdebug || option_debug > 2)
1029 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
1031 /* Figure out what digit was pressed */
1034 } else if (event < 11) {
1036 } else if (event < 12) {
1038 } else if (event < 16) {
1039 resp = 'A' + (event - 12);
1040 } else if (event < 17) { /* Event 16: Hook flash */
1043 /* Not a supported event */
1044 ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
1045 return &ast_null_frame;
1048 if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
1049 if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
1051 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
1053 rtp->lastevent = timestamp;
1056 if ((!(rtp->resp) && (!(event_end & 0x80))) || (rtp->resp && rtp->resp != resp)) {
1058 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
1059 } else if ((event_end & 0x80) && (rtp->lastevent != seqno) && rtp->resp) {
1060 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
1061 f->len = ast_tvdiff_ms(ast_samp2tv(samples, 8000), ast_tv(0, 0)); /* XXX hard coded 8kHz */
1063 rtp->lastevent = seqno;
1067 rtp->dtmfcount = dtmftimeout;
1068 rtp->dtmfsamples = samples;
1074 * \brief Process Comfort Noise RTP.
1076 * This is incomplete at the moment.
1079 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
1081 struct ast_frame *f = NULL;
1082 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
1083 totally help us out becuase we don't have an engine to keep it going and we are not
1084 guaranteed to have it every 20ms or anything */
1086 ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
1088 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
1089 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
1090 ast_inet_ntoa(rtp->them.sin_addr));
1091 ast_set_flag(rtp, FLAG_3389_WARNING);
1094 /* Must have at least one byte */
1098 rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
1099 rtp->f.datalen = len - 1;
1100 rtp->f.offset = AST_FRIENDLY_OFFSET;
1101 memcpy(rtp->f.data.ptr, data + 1, len - 1);
1103 rtp->f.data.ptr = NULL;
1107 rtp->f.frametype = AST_FRAME_CNG;
1108 rtp->f.subclass = data[0] & 0x7f;
1109 rtp->f.datalen = len - 1;
1111 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
1116 static int rtpread(int *id, int fd, short events, void *cbdata)
1118 struct ast_rtp *rtp = cbdata;
1119 struct ast_frame *f;
1120 f = ast_rtp_read(rtp);
1123 rtp->callback(rtp, f, rtp->data);
1128 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
1131 int position, i, packetwords;
1133 struct sockaddr_in sin;
1134 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
1135 unsigned int *rtcpheader;
1138 unsigned int length;
1147 struct ast_frame *f = &ast_null_frame;
1149 double reported_jitter;
1150 double reported_normdev_jitter_current;
1151 double normdevrtt_current;
1152 double reported_lost;
1153 double reported_normdev_lost_current;
1155 if (!rtp || !rtp->rtcp)
1156 return &ast_null_frame;
1160 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
1161 0, (struct sockaddr *)&sin, &len);
1162 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
1165 ast_assert(errno != EBADF);
1166 if (errno != EAGAIN) {
1167 ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n", strerror(errno));
1170 return &ast_null_frame;
1173 packetwords = res / 4;
1176 /* Send to whoever sent to us */
1177 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1178 (rtp->rtcp->them.sin_port != sin.sin_port)) {
1179 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1180 if (option_debug || rtpdebug)
1181 ast_debug(0, "RTCP NAT: Got RTCP from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1185 ast_debug(1, "Got RTCP report of %d bytes\n", res);
1187 /* Process a compound packet */
1189 while (position < packetwords) {
1191 length = ntohl(rtcpheader[i]);
1192 pt = (length & 0xff0000) >> 16;
1193 rc = (length & 0x1f000000) >> 24;
1196 if ((i + length) > packetwords) {
1197 if (option_debug || rtpdebug)
1198 ast_log(LOG_DEBUG, "RTCP Read too short\n");
1199 return &ast_null_frame;
1202 if (rtcp_debug_test_addr(&sin)) {
1203 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1204 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
1205 ast_verbose("Reception reports: %d\n", rc);
1206 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
1209 i += 2; /* Advance past header and ssrc */
1213 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
1214 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
1215 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
1216 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
1218 if (rtcp_debug_test_addr(&sin)) {
1219 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
1220 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
1221 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
1226 /* Intentional fall through */
1228 /* Don't handle multiple reception reports (rc > 1) yet */
1229 /* Calculate RTT per RFC */
1230 gettimeofday(&now, NULL);
1231 timeval2ntp(now, &msw, &lsw);
1232 if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
1233 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
1234 lsr = ntohl(rtcpheader[i + 4]);
1235 dlsr = ntohl(rtcpheader[i + 5]);
1236 rtt = comp - lsr - dlsr;
1238 /* Convert end to end delay to usec (keeping the calculation in 64bit space)
1239 sess->ee_delay = (eedelay * 1000) / 65536; */
1241 rtt = (rtt * 1000000) >> 16;
1243 rtt = (rtt * 1000) >> 16;
1247 rttsec = rtt / 1000.;
1248 rtp->rtcp->rtt = rttsec;
1250 if (comp - dlsr >= lsr) {
1251 rtp->rtcp->accumulated_transit += rttsec;
1253 if (rtp->rtcp->rtt_count == 0)
1254 rtp->rtcp->minrtt = rttsec;
1256 if (rtp->rtcp->maxrtt<rttsec)
1257 rtp->rtcp->maxrtt = rttsec;
1259 if (rtp->rtcp->minrtt>rttsec)
1260 rtp->rtcp->minrtt = rttsec;
1262 normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt, rttsec, rtp->rtcp->rtt_count);
1264 rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt, rttsec, rtp->rtcp->normdevrtt, normdevrtt_current, rtp->rtcp->rtt_count);
1266 rtp->rtcp->normdevrtt = normdevrtt_current;
1268 rtp->rtcp->rtt_count++;
1269 } else if (rtcp_debug_test_addr(&sin)) {
1270 ast_verbose("Internal RTCP NTP clock skew detected: "
1271 "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
1273 lsr, comp, dlsr, dlsr / 65536,
1274 (dlsr % 65536) * 1000 / 65536,
1275 dlsr - (comp - lsr));
1279 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
1280 reported_jitter = (double) rtp->rtcp->reported_jitter;
1282 if (rtp->rtcp->reported_jitter_count == 0)
1283 rtp->rtcp->reported_minjitter = reported_jitter;
1285 if (reported_jitter < rtp->rtcp->reported_minjitter)
1286 rtp->rtcp->reported_minjitter = reported_jitter;
1288 if (reported_jitter > rtp->rtcp->reported_maxjitter)
1289 rtp->rtcp->reported_maxjitter = reported_jitter;
1291 reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);
1293 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);
1295 rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;
1297 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
1299 reported_lost = (double) rtp->rtcp->reported_lost;
1301 /* using same counter as for jitter */
1302 if (rtp->rtcp->reported_jitter_count == 0)
1303 rtp->rtcp->reported_minlost = reported_lost;
1305 if (reported_lost < rtp->rtcp->reported_minlost)
1306 rtp->rtcp->reported_minlost = reported_lost;
1308 if (reported_lost > rtp->rtcp->reported_maxlost)
1309 rtp->rtcp->reported_maxlost = reported_lost;
1311 reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);
1313 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);
1315 rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;
1317 rtp->rtcp->reported_jitter_count++;
1319 if (rtcp_debug_test_addr(&sin)) {
1320 ast_verbose(" Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
1321 ast_verbose(" Packets lost so far: %d\n", rtp->rtcp->reported_lost);
1322 ast_verbose(" Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
1323 ast_verbose(" Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
1324 ast_verbose(" Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
1325 ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
1326 ast_verbose(" DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
1328 ast_verbose(" RTT: %lu(sec)\n", (unsigned long) rtt);
1332 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From %s:%d\r\n"
1334 "ReceptionReports: %d\r\n"
1335 "SenderSSRC: %u\r\n"
1336 "FractionLost: %ld\r\n"
1337 "PacketsLost: %d\r\n"
1338 "HighestSequence: %ld\r\n"
1339 "SequenceNumberCycles: %ld\r\n"
1341 "LastSR: %lu.%010lu\r\n"
1342 "DLSR: %4.4f(sec)\r\n"
1343 "RTT: %llu(sec)\r\n",
1344 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
1345 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1348 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1349 rtp->rtcp->reported_lost,
1350 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1351 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1352 rtp->rtcp->reported_jitter,
1353 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1354 ntohl(rtcpheader[i + 5])/65536.0,
1355 (unsigned long long)rtt);
1357 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From %s:%d\r\n"
1359 "ReceptionReports: %d\r\n"
1360 "SenderSSRC: %u\r\n"
1361 "FractionLost: %ld\r\n"
1362 "PacketsLost: %d\r\n"
1363 "HighestSequence: %ld\r\n"
1364 "SequenceNumberCycles: %ld\r\n"
1366 "LastSR: %lu.%010lu\r\n"
1367 "DLSR: %4.4f(sec)\r\n",
1368 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
1369 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1372 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1373 rtp->rtcp->reported_lost,
1374 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1375 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1376 rtp->rtcp->reported_jitter,
1377 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
1378 ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1379 ntohl(rtcpheader[i + 5])/65536.0);
1383 if (rtcp_debug_test_addr(&sin))
1384 ast_verbose("Received an RTCP Fast Update Request\n");
1385 rtp->f.frametype = AST_FRAME_CONTROL;
1386 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
1394 if (rtcp_debug_test_addr(&sin))
1395 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1398 if (rtcp_debug_test_addr(&sin))
1399 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1402 ast_debug(1, "Unknown RTCP packet (pt=%d) received from %s:%d\n", pt, ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1405 position += (length + 1);
1407 rtp->rtcp->rtcp_info = 1;
1411 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
1415 double current_time;
1420 double normdev_rxjitter_current;
1421 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
1422 gettimeofday(&rtp->rxcore, NULL);
1423 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
1424 /* map timestamp to a real time */
1425 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
1426 rtp->rxcore.tv_sec -= timestamp / 8000;
1427 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
1428 /* Round to 0.1ms for nice, pretty timestamps */
1429 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
1430 if (rtp->rxcore.tv_usec < 0) {
1431 /* Adjust appropriately if necessary */
1432 rtp->rxcore.tv_usec += 1000000;
1433 rtp->rxcore.tv_sec -= 1;
1437 gettimeofday(&now,NULL);
1438 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
1439 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
1440 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
1441 if (tv->tv_usec >= 1000000) {
1442 tv->tv_usec -= 1000000;
1445 prog = (double)((timestamp-rtp->seedrxts)/8000.);
1446 dtv = (double)rtp->drxcore + (double)(prog);
1447 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
1448 transit = current_time - dtv;
1449 d = transit - rtp->rxtransit;
1450 rtp->rxtransit = transit;
1453 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1454 if (rtp->rtcp && rtp->rxjitter > rtp->rtcp->maxrxjitter)
1455 rtp->rtcp->maxrxjitter = rtp->rxjitter;
1456 if (rtp->rtcp->rxjitter_count == 1)
1457 rtp->rtcp->minrxjitter = rtp->rxjitter;
1458 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1459 rtp->rtcp->minrxjitter = rtp->rxjitter;
1461 normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
1462 rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
1464 rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
1465 rtp->rtcp->rxjitter_count++;
1468 /*! \brief Perform a Packet2Packet RTP write */
1469 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, struct ast_rtp *bridged, unsigned int *rtpheader, int len, int hdrlen)
1471 int res = 0, payload = 0, bridged_payload = 0, mark;
1472 struct rtpPayloadType rtpPT;
1473 int reconstruct = ntohl(rtpheader[0]);
1475 /* Get fields from packet */
1476 payload = (reconstruct & 0x7f0000) >> 16;
1477 mark = (((reconstruct & 0x800000) >> 23) != 0);
1479 /* Check what the payload value should be */
1480 rtpPT = ast_rtp_lookup_pt(rtp, payload);
1482 /* 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 */
1483 if (!bridged->current_RTP_PT[payload].code)
1486 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
1487 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
1490 /* Otherwise adjust bridged payload to match */
1491 bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
1493 /* If the mark bit has not been sent yet... do it now */
1494 if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
1496 ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
1499 /* Reconstruct part of the packet */
1500 reconstruct &= 0xFF80FFFF;
1501 reconstruct |= (bridged_payload << 16);
1502 reconstruct |= (mark << 23);
1503 rtpheader[0] = htonl(reconstruct);
1505 /* Send the packet back out */
1506 res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
1508 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1509 ast_debug(1, "RTP Transmission error of packet to %s:%d: %s\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), strerror(errno));
1510 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1511 if (option_debug || rtpdebug)
1512 ast_debug(0, "RTP NAT: Can't write RTP to private address %s:%d, waiting for other end to send audio...\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port));
1513 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1516 } else if (rtp_debug_test_addr(&bridged->them))
1517 ast_verbose("Sent RTP P2P packet to %s:%u (type %-2.2d, len %-6.6u)\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), bridged_payload, len - hdrlen);
1522 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
1525 struct sockaddr_in sin;
1536 unsigned int timestamp;
1537 unsigned int *rtpheader;
1538 struct rtpPayloadType rtpPT;
1539 struct ast_rtp *bridged = NULL;
1542 /* If time is up, kill it */
1543 if (rtp->sending_digit)
1544 ast_rtp_senddigit_continuation(rtp);
1548 /* Cache where the header will go */
1549 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
1550 0, (struct sockaddr *)&sin, &len);
1552 /* If strict RTP protection is enabled see if we need to learn this address or if the packet should be dropped */
1553 if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
1554 /* Copy over address that this packet was received on */
1555 memcpy(&rtp->strict_rtp_address, &sin, sizeof(rtp->strict_rtp_address));
1556 /* Now move over to actually protecting the RTP port */
1557 rtp->strict_rtp_state = STRICT_RTP_CLOSED;
1558 ast_debug(1, "Learned remote address is %s:%d for strict RTP purposes, now protecting the port.\n", ast_inet_ntoa(rtp->strict_rtp_address.sin_addr), ntohs(rtp->strict_rtp_address.sin_port));
1559 } else if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
1560 /* If the address we previously learned doesn't match the address this packet came in on simply drop it */
1561 if ((rtp->strict_rtp_address.sin_addr.s_addr != sin.sin_addr.s_addr) || (rtp->strict_rtp_address.sin_port != sin.sin_port)) {
1562 ast_debug(1, "Received RTP packet from %s:%d, dropping due to strict RTP protection. Expected it to be from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), ast_inet_ntoa(rtp->strict_rtp_address.sin_addr), ntohs(rtp->strict_rtp_address.sin_port));
1563 return &ast_null_frame;
1567 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
1569 ast_assert(errno != EBADF);
1570 if (errno != EAGAIN) {
1571 ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
1574 return &ast_null_frame;
1578 ast_log(LOG_WARNING, "RTP Read too short\n");
1579 return &ast_null_frame;
1583 seqno = ntohl(rtpheader[0]);
1585 /* Check RTP version */
1586 version = (seqno & 0xC0000000) >> 30;
1588 /* If the two high bits are 0, this might be a
1589 * STUN message, so process it. stun_handle_packet()
1590 * answers to requests, and it returns STUN_ACCEPT
1591 * if the request is valid.
1593 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == STUN_ACCEPT) &&
1594 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
1595 memcpy(&rtp->them, &sin, sizeof(rtp->them));
1597 return &ast_null_frame;
1600 #if 0 /* Allow to receive RTP stream with closed transmission path */
1601 /* If we don't have the other side's address, then ignore this */
1602 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1603 return &ast_null_frame;
1606 /* Send to whoever send to us if NAT is turned on */
1608 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1609 (rtp->them.sin_port != sin.sin_port)) {
1612 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1613 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1616 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1617 if (option_debug || rtpdebug)
1618 ast_debug(0, "RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
1622 /* If we are bridged to another RTP stream, send direct */
1623 if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
1624 return &ast_null_frame;
1627 return &ast_null_frame;
1629 payloadtype = (seqno & 0x7f0000) >> 16;
1630 padding = seqno & (1 << 29);
1631 mark = seqno & (1 << 23);
1632 ext = seqno & (1 << 28);
1633 cc = (seqno & 0xF000000) >> 24;
1635 timestamp = ntohl(rtpheader[1]);
1636 ssrc = ntohl(rtpheader[2]);
1638 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1639 if (option_debug || rtpdebug)
1640 ast_debug(0, "Forcing Marker bit, because SSRC has changed\n");
1647 /* Remove padding bytes */
1648 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1652 /* CSRC fields present */
1657 /* RTP Extension present */
1658 hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
1662 profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
1663 if (profile == 0x505a)
1664 ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
1666 ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
1671 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1672 return &ast_null_frame;
1675 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1677 if (rtp->rxcount==1) {
1678 /* This is the first RTP packet successfully received from source */
1679 rtp->seedrxseqno = seqno;
1682 /* Do not schedule RR if RTCP isn't run */
1683 if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
1684 /* Schedule transmission of Receiver Report */
1685 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1687 if ((int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
1688 rtp->cycles += RTP_SEQ_MOD;
1690 prev_seqno = rtp->lastrxseqno;
1692 rtp->lastrxseqno = seqno;
1695 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1697 if (rtp_debug_test_addr(&sin))
1698 ast_verbose("Got RTP packet from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1699 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1701 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1702 if (!rtpPT.isAstFormat) {
1703 struct ast_frame *f = NULL;
1705 /* This is special in-band data that's not one of our codecs */
1706 if (rtpPT.code == AST_RTP_DTMF) {
1707 /* It's special -- rfc2833 process it */
1708 if (rtp_debug_test_addr(&sin)) {
1709 unsigned char *data;
1711 unsigned int event_end;
1712 unsigned int duration;
1713 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1714 event = ntohl(*((unsigned int *)(data)));
1716 event_end = ntohl(*((unsigned int *)(data)));
1719 duration = ntohl(*((unsigned int *)(data)));
1721 ast_verbose("Got RTP RFC2833 from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
1723 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp);
1724 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1725 /* It's really special -- process it the Cisco way */
1726 if (rtp->lastevent <= seqno || (rtp->lastevent >= 65530 && seqno <= 6)) {
1727 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1728 rtp->lastevent = seqno;
1730 } else if (rtpPT.code == AST_RTP_CN) {
1732 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1734 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1736 return f ? f : &ast_null_frame;
1738 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1739 rtp->f.frametype = (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) ? AST_FRAME_VOICE : (rtp->f.subclass & AST_FORMAT_VIDEO_MASK) ? AST_FRAME_VIDEO : AST_FRAME_TEXT;
1742 rtp->lastrxts = timestamp;
1744 rtp->rxseqno = seqno;
1746 /* Record received timestamp as last received now */
1747 rtp->lastrxts = timestamp;
1750 rtp->f.datalen = res - hdrlen;
1751 rtp->f.data.ptr = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1752 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1753 rtp->f.seqno = seqno;
1755 if (rtp->f.subclass == AST_FORMAT_T140 && (int)seqno - (prev_seqno+1) > 0 && (int)seqno - (prev_seqno+1) < 10) {
1756 unsigned char *data = rtp->f.data.ptr;
1758 memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
1765 if (rtp->f.subclass == AST_FORMAT_T140RED) {
1766 unsigned char *data = rtp->f.data.ptr;
1767 unsigned char *header_end;
1768 int num_generations;
1771 int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
1774 rtp->f.subclass = AST_FORMAT_T140;
1775 header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
1778 header_length = header_end - data;
1779 num_generations = header_length / 4;
1780 len = header_length;
1783 for (x = 0; x < num_generations; x++)
1784 len += data[x * 4 + 3];
1786 if (!(rtp->f.datalen - len))
1787 return &ast_null_frame;
1789 rtp->f.data.ptr += len;
1790 rtp->f.datalen -= len;
1791 } else if (diff > num_generations && diff < 10) {
1793 rtp->f.data.ptr += len;
1794 rtp->f.datalen -= len;
1796 data = rtp->f.data.ptr;
1801 for ( x = 0; x < num_generations - diff; x++)
1802 len += data[x * 4 + 3];
1804 rtp->f.data.ptr += len;
1805 rtp->f.datalen -= len;
1809 if (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) {
1810 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1811 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1812 ast_frame_byteswap_be(&rtp->f);
1813 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1814 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1815 ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
1816 rtp->f.ts = timestamp / 8;
1817 rtp->f.len = rtp->f.samples / ( (ast_format_rate(rtp->f.subclass) == 16000) ? 16 : 8 );
1818 } else if (rtp->f.subclass & AST_FORMAT_VIDEO_MASK) {
1819 /* Video -- samples is # of samples vs. 90000 */
1820 if (!rtp->lastividtimestamp)
1821 rtp->lastividtimestamp = timestamp;
1822 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1823 rtp->lastividtimestamp = timestamp;
1824 rtp->f.delivery.tv_sec = 0;
1825 rtp->f.delivery.tv_usec = 0;
1826 /* Pass the RTP marker bit as bit 0 in the subclass field.
1827 * This is ok because subclass is actually a bitmask, and
1828 * the low bits represent audio formats, that are not
1829 * involved here since we deal with video.
1832 rtp->f.subclass |= 0x1;
1834 /* TEXT -- samples is # of samples vs. 1000 */
1835 if (!rtp->lastitexttimestamp)
1836 rtp->lastitexttimestamp = timestamp;
1837 rtp->f.samples = timestamp - rtp->lastitexttimestamp;
1838 rtp->lastitexttimestamp = timestamp;
1839 rtp->f.delivery.tv_sec = 0;
1840 rtp->f.delivery.tv_usec = 0;
1846 /* The following array defines the MIME Media type (and subtype) for each
1847 of our codecs, or RTP-specific data type. */
1849 struct rtpPayloadType payloadType;
1853 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1854 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1855 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1856 {{1, AST_FORMAT_ULAW}, "audio", "G711U"},
1857 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1858 {{1, AST_FORMAT_ALAW}, "audio", "G711A"},
1859 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1860 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1861 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1862 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1863 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1864 {{1, AST_FORMAT_G729A}, "audio", "G729A"},
1865 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1866 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1867 {{1, AST_FORMAT_G722}, "audio", "G722"},
1868 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
1869 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1870 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1871 {{0, AST_RTP_CN}, "audio", "CN"},
1872 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1873 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1874 {{1, AST_FORMAT_H261}, "video", "H261"},
1875 {{1, AST_FORMAT_H263}, "video", "H263"},
1876 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1877 {{1, AST_FORMAT_H264}, "video", "H264"},
1878 {{1, AST_FORMAT_MP4_VIDEO}, "video", "MP4V-ES"},
1879 {{1, AST_FORMAT_T140RED}, "text", "RED"},
1880 {{1, AST_FORMAT_T140}, "text", "T140"},
1884 * \brief Mapping between Asterisk codecs and rtp payload types
1886 * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1887 * also, our own choices for dynamic payload types. This is our master
1888 * table for transmission
1890 * See http://www.iana.org/assignments/rtp-parameters for a list of
1893 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1894 [0] = {1, AST_FORMAT_ULAW},
1895 #ifdef USE_DEPRECATED_G726
1896 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1898 [3] = {1, AST_FORMAT_GSM},
1899 [4] = {1, AST_FORMAT_G723_1},
1900 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1901 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1902 [7] = {1, AST_FORMAT_LPC10},
1903 [8] = {1, AST_FORMAT_ALAW},
1904 [9] = {1, AST_FORMAT_G722},
1905 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1906 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1907 [13] = {0, AST_RTP_CN},
1908 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1909 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1910 [18] = {1, AST_FORMAT_G729A},
1911 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1912 [26] = {1, AST_FORMAT_JPEG},
1913 [31] = {1, AST_FORMAT_H261},
1914 [34] = {1, AST_FORMAT_H263},
1915 [97] = {1, AST_FORMAT_ILBC},
1916 [98] = {1, AST_FORMAT_H263_PLUS},
1917 [99] = {1, AST_FORMAT_H264},
1918 [101] = {0, AST_RTP_DTMF},
1919 [103] = {1, AST_FORMAT_H263_PLUS},
1920 [104] = {1, AST_FORMAT_MP4_VIDEO},
1921 [105] = {1, AST_FORMAT_T140RED}, /* Real time text chat (with redundancy encoding) */
1922 [106] = {1, AST_FORMAT_T140}, /* Real time text chat */
1923 [110] = {1, AST_FORMAT_SPEEX},
1924 [111] = {1, AST_FORMAT_G726},
1925 [112] = {1, AST_FORMAT_G726_AAL2},
1926 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1929 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1936 rtp_bridge_lock(rtp);
1938 for (i = 0; i < MAX_RTP_PT; ++i) {
1939 rtp->current_RTP_PT[i].isAstFormat = 0;
1940 rtp->current_RTP_PT[i].code = 0;
1943 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1944 rtp->rtp_lookup_code_cache_code = 0;
1945 rtp->rtp_lookup_code_cache_result = 0;
1947 rtp_bridge_unlock(rtp);
1950 void ast_rtp_pt_default(struct ast_rtp* rtp)
1954 rtp_bridge_lock(rtp);
1956 /* Initialize to default payload types */
1957 for (i = 0; i < MAX_RTP_PT; ++i) {
1958 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1959 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1962 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1963 rtp->rtp_lookup_code_cache_code = 0;
1964 rtp->rtp_lookup_code_cache_result = 0;
1966 rtp_bridge_unlock(rtp);
1969 void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
1973 rtp_bridge_lock(dest);
1974 rtp_bridge_lock(src);
1976 for (i = 0; i < MAX_RTP_PT; ++i) {
1977 dest->current_RTP_PT[i].isAstFormat =
1978 src->current_RTP_PT[i].isAstFormat;
1979 dest->current_RTP_PT[i].code =
1980 src->current_RTP_PT[i].code;
1982 dest->rtp_lookup_code_cache_isAstFormat = 0;
1983 dest->rtp_lookup_code_cache_code = 0;
1984 dest->rtp_lookup_code_cache_result = 0;
1986 rtp_bridge_unlock(src);
1987 rtp_bridge_unlock(dest);
1990 /*! \brief Get channel driver interface structure */
1991 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1993 struct ast_rtp_protocol *cur = NULL;
1995 AST_RWLIST_RDLOCK(&protos);
1996 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1997 if (cur->type == chan->tech->type)
2000 AST_RWLIST_UNLOCK(&protos);
2005 int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
2007 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
2008 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
2009 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
2010 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
2011 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED, text_dest_res = AST_RTP_GET_FAILED;
2012 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED, text_src_res = AST_RTP_GET_FAILED;
2013 int srccodec, destcodec, nat_active = 0;
2016 ast_channel_lock(c0);
2018 while (ast_channel_trylock(c1)) {
2019 ast_channel_unlock(c0);
2021 ast_channel_lock(c0);
2025 /* Find channel driver interfaces */
2026 destpr = get_proto(c0);
2028 srcpr = get_proto(c1);
2030 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c0->name);
2031 ast_channel_unlock(c0);
2033 ast_channel_unlock(c1);
2037 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
2038 ast_channel_unlock(c0);
2040 ast_channel_unlock(c1);
2044 /* Get audio, video and text interface (if native bridge is possible) */
2045 audio_dest_res = destpr->get_rtp_info(c0, &destp);
2046 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
2047 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(c0, &tdestp) : AST_RTP_GET_FAILED;
2049 audio_src_res = srcpr->get_rtp_info(c1, &srcp);
2050 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
2051 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(c1, &tsrcp) : AST_RTP_GET_FAILED;
2054 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
2055 if (audio_dest_res != AST_RTP_TRY_NATIVE) {
2056 /* Somebody doesn't want to play... */
2057 ast_channel_unlock(c0);
2059 ast_channel_unlock(c1);
2062 if (audio_src_res == AST_RTP_TRY_NATIVE && srcpr->get_codec)
2063 srccodec = srcpr->get_codec(c1);
2066 if (audio_dest_res == AST_RTP_TRY_NATIVE && destpr->get_codec)
2067 destcodec = destpr->get_codec(c0);
2070 /* Ensure we have at least one matching codec */
2071 if (!(srccodec & destcodec)) {
2072 ast_channel_unlock(c0);
2074 ast_channel_unlock(c1);
2077 /* Consider empty media as non-existent */
2078 if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
2080 if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
2082 /* Bridge media early */
2083 if (destpr->set_rtp_peer(c0, srcp, vsrcp, tsrcp, srccodec, nat_active))
2084 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
2085 ast_channel_unlock(c0);
2087 ast_channel_unlock(c1);
2088 ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
2092 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
2094 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
2095 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
2096 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
2097 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
2098 enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED, text_dest_res = AST_RTP_GET_FAILED;
2099 enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED, text_src_res = AST_RTP_GET_FAILED;
2100 int srccodec, destcodec;
2103 ast_channel_lock(dest);
2104 while (ast_channel_trylock(src)) {
2105 ast_channel_unlock(dest);
2107 ast_channel_lock(dest);
2110 /* Find channel driver interfaces */
2111 if (!(destpr = get_proto(dest))) {
2112 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", dest->name);
2113 ast_channel_unlock(dest);
2114 ast_channel_unlock(src);
2117 if (!(srcpr = get_proto(src))) {
2118 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", src->name);
2119 ast_channel_unlock(dest);
2120 ast_channel_unlock(src);
2124 /* Get audio and video interface (if native bridge is possible) */
2125 audio_dest_res = destpr->get_rtp_info(dest, &destp);
2126 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
2127 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(dest, &tdestp) : AST_RTP_GET_FAILED;
2128 audio_src_res = srcpr->get_rtp_info(src, &srcp);
2129 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
2130 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(src, &tsrcp) : AST_RTP_GET_FAILED;
2132 /* Ensure we have at least one matching codec */
2133 if (srcpr->get_codec)
2134 srccodec = srcpr->get_codec(src);
2137 if (destpr->get_codec)
2138 destcodec = destpr->get_codec(dest);
2142 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
2143 if (audio_dest_res != AST_RTP_TRY_NATIVE || audio_src_res != AST_RTP_TRY_NATIVE || !(srccodec & destcodec)) {
2144 /* Somebody doesn't want to play... */
2145 ast_channel_unlock(dest);
2146 ast_channel_unlock(src);
2149 ast_rtp_pt_copy(destp, srcp);
2150 if (vdestp && vsrcp)
2151 ast_rtp_pt_copy(vdestp, vsrcp);
2152 if (tdestp && tsrcp)
2153 ast_rtp_pt_copy(tdestp, tsrcp);
2156 if (destpr->set_rtp_peer(dest, srcp, vsrcp, tsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
2157 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
2159 ast_channel_unlock(dest);
2160 ast_channel_unlock(src);
2161 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
2165 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
2166 * By default, use the well-known value for this type (although it may
2167 * still be set to a different value by a subsequent "a=rtpmap:" line)
2169 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
2171 if (pt < 0 || pt > MAX_RTP_PT || static_RTP_PT[pt].code == 0)
2172 return; /* bogus payload type */
2174 rtp_bridge_lock(rtp);
2175 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
2176 rtp_bridge_unlock(rtp);
2179 /*! \brief remove setting from payload type list if the rtpmap header indicates
2180 an unknown media type */
2181 void ast_rtp_unset_m_type(struct ast_rtp* rtp, int pt)
2183 if (pt < 0 || pt > MAX_RTP_PT)
2184 return; /* bogus payload type */
2186 rtp_bridge_lock(rtp);
2187 rtp->current_RTP_PT[pt].isAstFormat = 0;
2188 rtp->current_RTP_PT[pt].code = 0;
2189 rtp_bridge_unlock(rtp);
2192 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
2193 * an SDP "a=rtpmap:" line.
2194 * \return 0 if the MIME type was found and set, -1 if it wasn't found
2196 int ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
2197 char *mimeType, char *mimeSubtype,
2198 enum ast_rtp_options options)
2203 if (pt < 0 || pt > MAX_RTP_PT)
2204 return -1; /* bogus payload type */
2206 rtp_bridge_lock(rtp);
2208 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
2209 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
2210 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
2212 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
2213 if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
2214 mimeTypes[i].payloadType.isAstFormat &&
2215 (options & AST_RTP_OPT_G726_NONSTANDARD))
2216 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
2221 rtp_bridge_unlock(rtp);
2223 return (found ? 0 : -1);
2226 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
2227 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
2228 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
2229 int* astFormats, int* nonAstFormats)
2233 rtp_bridge_lock(rtp);
2235 *astFormats = *nonAstFormats = 0;
2236 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2237 if (rtp->current_RTP_PT[pt].isAstFormat) {
2238 *astFormats |= rtp->current_RTP_PT[pt].code;
2240 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
2244 rtp_bridge_unlock(rtp);
2247 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
2249 struct rtpPayloadType result;
2251 result.isAstFormat = result.code = 0;
2253 if (pt < 0 || pt > MAX_RTP_PT)
2254 return result; /* bogus payload type */
2256 /* Start with negotiated codecs */
2257 rtp_bridge_lock(rtp);
2258 result = rtp->current_RTP_PT[pt];
2259 rtp_bridge_unlock(rtp);
2261 /* If it doesn't exist, check our static RTP type list, just in case */
2263 result = static_RTP_PT[pt];
2268 /*! \brief Looks up an RTP code out of our *static* outbound list */
2269 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
2273 rtp_bridge_lock(rtp);
2275 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
2276 code == rtp->rtp_lookup_code_cache_code) {
2277 /* Use our cached mapping, to avoid the overhead of the loop below */
2278 pt = rtp->rtp_lookup_code_cache_result;
2279 rtp_bridge_unlock(rtp);
2283 /* Check the dynamic list first */
2284 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2285 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
2286 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2287 rtp->rtp_lookup_code_cache_code = code;
2288 rtp->rtp_lookup_code_cache_result = pt;
2289 rtp_bridge_unlock(rtp);
2294 /* Then the static list */
2295 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2296 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
2297 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2298 rtp->rtp_lookup_code_cache_code = code;
2299 rtp->rtp_lookup_code_cache_result = pt;
2300 rtp_bridge_unlock(rtp);
2305 rtp_bridge_unlock(rtp);
2310 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
2311 enum ast_rtp_options options)
2315 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
2316 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
2318 (code == AST_FORMAT_G726_AAL2) &&
2319 (options & AST_RTP_OPT_G726_NONSTANDARD))
2322 return mimeTypes[i].subtype;
2329 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
2330 const int isAstFormat, enum ast_rtp_options options)
2340 snprintf(end, size, "0x%x (", capability);
2347 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
2348 if (capability & format) {
2349 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
2351 snprintf(end, size, "%s|", name);
2359 ast_copy_string(start, "nothing)", size);
2366 /*! \brief Open RTP or RTCP socket for a session.
2367 * Print a message on failure.
2369 static int rtp_socket(const char *type)
2371 int s = socket(AF_INET, SOCK_DGRAM, 0);
2375 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
2377 long flags = fcntl(s, F_GETFL);
2378 fcntl(s, F_SETFL, flags | O_NONBLOCK);
2381 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
2388 * \brief Initialize a new RTCP session.
2390 * \returns The newly initialized RTCP session.
2392 static struct ast_rtcp *ast_rtcp_new(void)
2394 struct ast_rtcp *rtcp;
2396 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
2398 rtcp->s = rtp_socket("RTCP");
2399 rtcp->us.sin_family = AF_INET;
2400 rtcp->them.sin_family = AF_INET;
2412 * \brief Initialize a new RTP structure.
2415 void ast_rtp_new_init(struct ast_rtp *rtp)
2418 ast_mutex_init(&rtp->bridge_lock);
2421 rtp->them.sin_family = AF_INET;
2422 rtp->us.sin_family = AF_INET;
2423 rtp->ssrc = ast_random();
2424 rtp->seqno = ast_random() & 0xffff;
2425 ast_set_flag(rtp, FLAG_HAS_DTMF);
2426 rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
2429 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
2431 struct ast_rtp *rtp;
2435 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
2438 ast_rtp_new_init(rtp);
2440 rtp->s = rtp_socket("RTP");
2443 if (sched && rtcpenable) {
2445 rtp->rtcp = ast_rtcp_new();
2449 * Try to bind the RTP port, x, and possibly the RTCP port, x+1 as well.
2450 * Start from a random (even, by RTP spec) port number, and
2451 * iterate until success or no ports are available.
2452 * Note that the requirement of RTP port being even, or RTCP being the
2453 * next one, cannot be enforced in presence of a NAT box because the
2454 * mapping is not under our control.
2456 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
2457 x = x & ~1; /* make it an even number */
2458 startplace = x; /* remember the starting point */
2459 /* this is constant across the loop */
2460 rtp->us.sin_addr = addr;
2462 rtp->rtcp->us.sin_addr = addr;
2464 rtp->us.sin_port = htons(x);
2465 if (!bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) {
2466 /* bind succeeded, if no rtcp then we are done */
2469 /* have rtcp, try to bind it */
2470 rtp->rtcp->us.sin_port = htons(x + 1);
2471 if (!bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us)))
2472 break; /* success again, we are really done */
2474 * RTCP bind failed, so close and recreate the
2475 * already bound RTP socket for the next round.
2478 rtp->s = rtp_socket("RTP");
2483 * If we get here, there was an error in one of the bind()
2484 * calls, so make sure it is nothing unexpected.
2486 if (errno != EADDRINUSE) {
2487 /* We got an error that wasn't expected, abort! */
2488 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
2492 * One of the ports is in use. For the next iteration,
2493 * increment by two and handle wraparound.
2494 * If we reach the starting point, then declare failure.
2498 x = (rtpstart + 1) & ~1;
2499 if (x == startplace) {
2500 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
2507 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
2508 ast_set_flag(rtp, FLAG_CALLBACK_MODE);
2510 ast_rtp_pt_default(rtp);
2517 close(rtp->rtcp->s);
2518 ast_free(rtp->rtcp);
2524 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
2528 memset(&ia, 0, sizeof(ia));
2529 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
2532 int ast_rtp_setqos(struct ast_rtp *rtp, int tos, int cos, char *desc)
2534 return ast_netsock_set_qos(rtp->s, tos, cos, desc);
2537 void ast_rtp_new_source(struct ast_rtp *rtp)
2539 rtp->set_marker_bit = 1;
2543 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2545 rtp->them.sin_port = them->sin_port;
2546 rtp->them.sin_addr = them->sin_addr;
2548 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
2549 rtp->rtcp->them.sin_addr = them->sin_addr;
2552 /* If strict RTP protection is enabled switch back to the learn state so we don't drop packets from above */
2554 rtp->strict_rtp_state = STRICT_RTP_LEARN;
2557 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2559 if ((them->sin_family != AF_INET) ||
2560 (them->sin_port != rtp->them.sin_port) ||
2561 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
2562 them->sin_family = AF_INET;
2563 them->sin_port = rtp->them.sin_port;
2564 them->sin_addr = rtp->them.sin_addr;
2570 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
2575 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
2577 struct ast_rtp *bridged = NULL;
2579 rtp_bridge_lock(rtp);
2580 bridged = rtp->bridged;
2581 rtp_bridge_unlock(rtp);
2586 void ast_rtp_stop(struct ast_rtp *rtp)
2589 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2592 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
2597 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
2598 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
2600 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
2601 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
2604 ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
2607 void ast_rtp_reset(struct ast_rtp *rtp)
2609 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
2610 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
2611 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
2613 rtp->lastdigitts = 0;
2615 rtp->lastividtimestamp = 0;
2616 rtp->lastovidtimestamp = 0;
2617 rtp->lastitexttimestamp = 0;
2618 rtp->lastotexttimestamp = 0;
2619 rtp->lasteventseqn = 0;
2621 rtp->lasttxformat = 0;
2622 rtp->lastrxformat = 0;
2624 rtp->dtmfsamples = 0;
2629 static double __ast_rtp_get_qos(struct ast_rtp *rtp, const char *qos, int *found)
2633 if (!strcasecmp(qos, "remote_maxjitter"))
2634 return rtp->rtcp->reported_maxjitter * 1000.0;
2635 if (!strcasecmp(qos, "remote_minjitter"))
2636 return rtp->rtcp->reported_minjitter * 1000.0;
2637 if (!strcasecmp(qos, "remote_normdevjitter"))
2638 return rtp->rtcp->reported_normdev_jitter * 1000.0;
2639 if (!strcasecmp(qos, "remote_stdevjitter"))
2640 return sqrt(rtp->rtcp->reported_stdev_jitter) * 1000.0;
2642 if (!strcasecmp(qos, "local_maxjitter"))
2643 return rtp->rtcp->maxrxjitter * 1000.0;
2644 if (!strcasecmp(qos, "local_minjitter"))
2645 return rtp->rtcp->minrxjitter * 1000.0;
2646 if (!strcasecmp(qos, "local_normdevjitter"))
2647 return rtp->rtcp->normdev_rxjitter * 1000.0;
2648 if (!strcasecmp(qos, "local_stdevjitter"))
2649 return sqrt(rtp->rtcp->stdev_rxjitter) * 1000.0;
2651 if (!strcasecmp(qos, "maxrtt"))
2652 return rtp->rtcp->maxrtt * 1000.0;
2653 if (!strcasecmp(qos, "minrtt"))
2654 return rtp->rtcp->minrtt * 1000.0;
2655 if (!strcasecmp(qos, "normdevrtt"))
2656 return rtp->rtcp->normdevrtt * 1000.0;
2657 if (!strcasecmp(qos, "stdevrtt"))
2658 return sqrt(rtp->rtcp->stdevrtt) * 1000.0;
2665 int ast_rtp_get_qos(struct ast_rtp *rtp, const char *qos, char *buf, unsigned int buflen)
2670 value = __ast_rtp_get_qos(rtp, qos, &found);
2675 snprintf(buf, buflen, "%.0lf", value);
2680 void ast_rtp_set_vars(struct ast_channel *chan, struct ast_rtp *rtp) {
2682 char *audioqos_jitter;
2683 char *audioqos_loss;
2685 struct ast_channel *bridge;
2690 bridge = ast_bridged_channel(chan);
2692 audioqos = ast_rtp_get_quality(rtp, NULL, RTPQOS_SUMMARY);
2693 audioqos_jitter = ast_rtp_get_quality(rtp, NULL, RTPQOS_JITTER);
2694 audioqos_loss = ast_rtp_get_quality(rtp, NULL, RTPQOS_LOSS);
2695 audioqos_rtt = ast_rtp_get_quality(rtp, NULL, RTPQOS_RTT);
2697 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOS", audioqos);
2698 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSJITTER", audioqos_jitter);
2699 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSLOSS", audioqos_loss);
2700 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSRTT", audioqos_rtt);
2705 pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSBRIDGED", audioqos);
2706 pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSJITTERBRIDGED", audioqos_jitter);
2707 pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSLOSSBRIDGED", audioqos_loss);
2708 pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSRTTBRIDGED", audioqos_rtt);
2711 static char *__ast_rtp_get_quality_jitter(struct ast_rtp *rtp)
2715 *themssrc their ssrc
2717 *rxjitter our calculated jitter(rx)
2718 *rxcount no. received packets
2719 *txjitter reported jitter of the other end
2720 *txcount transmitted packets
2721 *rlp remote lost packets
2722 *rtt round trip time
2724 #define RTCP_JITTER_FORMAT1 \
2728 "stdevrxjitter=%f;" \
2729 "reported_minjitter=%f;" \
2730 "reported_maxjitter=%f;" \
2731 "reported_avgjitter=%f;" \
2732 "reported_stdevjitter=%f;"
2734 #define RTCP_JITTER_FORMAT2 \
2737 if (rtp->rtcp && rtp->rtcp->rtcp_info) {
2738 snprintf(rtp->rtcp->quality_jitter, sizeof(rtp->rtcp->quality_jitter), RTCP_JITTER_FORMAT1,
2739 rtp->rtcp->minrxjitter,
2740 rtp->rtcp->maxrxjitter,
2741 rtp->rtcp->normdev_rxjitter,
2742 sqrt(rtp->rtcp->stdev_rxjitter),
2743 rtp->rtcp->reported_minjitter,
2744 rtp->rtcp->reported_maxjitter,
2745 rtp->rtcp->reported_normdev_jitter,
2746 sqrt(rtp->rtcp->reported_stdev_jitter)
2749 snprintf(rtp->rtcp->quality_jitter, sizeof(rtp->rtcp->quality_jitter), RTCP_JITTER_FORMAT2,
2754 return rtp->rtcp->quality_jitter;
2756 #undef RTCP_JITTER_FORMAT1
2757 #undef RTCP_JITTER_FORMAT2
2760 static char *__ast_rtp_get_quality_loss(struct ast_rtp *rtp)
2763 unsigned int extended;
2764 unsigned int expected;
2767 #define RTCP_LOSS_FORMAT1 \
2772 "reported_minlost=%f;" \
2773 "reported_maxlost=%f;" \
2774 "reported_avglost=%f;" \
2775 "reported_stdevlost=%f;"
2777 #define RTCP_LOSS_FORMAT2 \
2781 if (rtp->rtcp && rtp->rtcp->rtcp_info && rtp->rtcp->maxrxlost > 0) {
2782 snprintf(rtp->rtcp->quality_loss, sizeof(rtp->rtcp->quality_loss), RTCP_LOSS_FORMAT1,
2783 rtp->rtcp->minrxlost,
2784 rtp->rtcp->maxrxlost,
2785 rtp->rtcp->normdev_rxlost,
2786 sqrt(rtp->rtcp->stdev_rxlost),
2787 rtp->rtcp->reported_minlost,
2788 rtp->rtcp->reported_maxlost,
2789 rtp->rtcp->reported_normdev_lost,
2790 sqrt(rtp->rtcp->reported_stdev_lost)
2793 extended = rtp->cycles + rtp->lastrxseqno;
2794 expected = extended - rtp->seedrxseqno + 1;
2795 if (rtp->rxcount > expected)
2796 expected += rtp->rxcount - expected;
2797 lost = expected - rtp->rxcount;
2799 if (!expected || lost <= 0)
2802 fraction = (lost << 8) / expected;
2804 snprintf(rtp->rtcp->quality_loss, sizeof(rtp->rtcp->quality_loss), RTCP_LOSS_FORMAT2,
2810 return rtp->rtcp->quality_loss;
2812 #undef RTCP_LOSS_FORMAT1
2813 #undef RTCP_LOSS_FORMAT2
2816 static char *__ast_rtp_get_quality_rtt(struct ast_rtp *rtp)
2818 if (rtp->rtcp && rtp->rtcp->rtcp_info) {
2819 snprintf(rtp->rtcp->quality_rtt, sizeof(rtp->rtcp->quality_rtt), "minrtt=%f;maxrtt=%f;avgrtt=%f;stdevrtt=%f;",
2822 rtp->rtcp->normdevrtt,
2823 sqrt(rtp->rtcp->stdevrtt)
2826 snprintf(rtp->rtcp->quality_rtt, sizeof(rtp->rtcp->quality_rtt), "Not available");
2829 return rtp->rtcp->quality_rtt;
2832 static char *__ast_rtp_get_quality(struct ast_rtp *rtp)
2836 *themssrc their ssrc
2838 *rxjitter our calculated jitter(rx)
2839 *rxcount no. received packets
2840 *txjitter reported jitter of the other end
2841 *txcount transmitted packets
2842 *rlp remote lost packets
2843 *rtt round trip time
2846 if (rtp->rtcp && rtp->rtcp->rtcp_info) {
2847 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality),
2848 "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
2851 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2854 (double)rtp->rtcp->reported_jitter / 65536.0,
2856 rtp->rtcp->reported_lost,
2860 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality), "ssrc=%u;themssrc=%u;rxjitter=%f;rxcount=%u;txcount=%u;",
2869 return rtp->rtcp->quality;
2872 char *ast_rtp_get_quality(struct ast_rtp *rtp, struct ast_rtp_quality *qual, enum ast_rtp_quality_type qtype)
2875 qual->local_ssrc = rtp->ssrc;
2876 qual->local_jitter = rtp->rxjitter;
2877 qual->local_count = rtp->rxcount;
2878 qual->remote_ssrc = rtp->themssrc;
2879 qual->remote_count = rtp->txcount;
2882 qual->local_lostpackets = rtp->rtcp->expected_prior - rtp->rtcp->received_prior;
2883 qual->remote_lostpackets = rtp->rtcp->reported_lost;
2884 qual->remote_jitter = rtp->rtcp->reported_jitter / 65536.0;
2885 qual->rtt = rtp->rtcp->rtt;
2890 case RTPQOS_SUMMARY:
2891 return __ast_rtp_get_quality(rtp);
2893 return __ast_rtp_get_quality_jitter(rtp);
2895 return __ast_rtp_get_quality_loss(rtp);
2897 return __ast_rtp_get_quality_rtt(rtp);
2903 void ast_rtp_destroy(struct ast_rtp *rtp)
2905 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
2906 /*Print some info on the call here */
2907 ast_verbose(" RTP-stats\n");
2908 ast_verbose("* Our Receiver:\n");
2909 ast_verbose(" SSRC: %u\n", rtp->themssrc);
2910 ast_verbose(" Received packets: %u\n", rtp->rxcount);
2911 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
2912 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
2913 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
2914 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
2915 ast_verbose("* Our Sender:\n");
2916 ast_verbose(" SSRC: %u\n", rtp->ssrc);
2917 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2918 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
2919 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter / (unsigned int)65536.0);
2920 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
2921 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
2924 manager_event(EVENT_FLAG_REPORTING, "RTPReceiverStat", "SSRC: %u\r\n"
2925 "ReceivedPackets: %u\r\n"
2926 "LostPackets: %u\r\n"
2932 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2935 rtp->rtcp->rr_count);
2936 manager_event(EVENT_FLAG_REPORTING, "RTPSenderStat", "SSRC: %u\r\n"
2937 "SentPackets: %u\r\n"
2938 "LostPackets: %u\r\n"
2944 rtp->rtcp->reported_lost,
2945 rtp->rtcp->reported_jitter,
2946 rtp->rtcp->sr_count,
2949 ast_smoother_free(rtp->smoother);
2951 ast_io_remove(rtp->io, rtp->ioid);
2955 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2956 close(rtp->rtcp->s);
2957 ast_free(rtp->rtcp);
2961 ast_mutex_destroy(&rtp->bridge_lock);
2966 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2970 if (ast_tvzero(rtp->txcore)) {
2971 rtp->txcore = ast_tvnow();
2972 /* Round to 20ms for nice, pretty timestamps */
2973 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2975 /* Use previous txcore if available */
2976 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2977 ms = ast_tvdiff_ms(t, rtp->txcore);
2980 /* Use what we just got for next time */
2982 return (unsigned int) ms;
2985 /*! \brief Send begin frames for DTMF */
2986 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
2988 unsigned int *rtpheader;
2989 int hdrlen = 12, res = 0, i = 0, payload = 0;
2992 if ((digit <= '9') && (digit >= '0'))
2994 else if (digit == '*')
2996 else if (digit == '#')
2998 else if ((digit >= 'A') && (digit <= 'D'))
2999 digit = digit - 'A' + 12;
3000 else if ((digit >= 'a') && (digit <= 'd'))
3001 digit = digit - 'a' + 12;
3003 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
3007 /* If we have no peer, return immediately */
3008 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
3011 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
3013 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
3014 rtp->send_duration = 160;
3016 /* Get a pointer to the header */
3017 rtpheader = (unsigned int *)data;
3018 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
3019 rtpheader[1] = htonl(rtp->lastdigitts);
3020 rtpheader[2] = htonl(rtp->ssrc);
3022 for (i = 0; i < 2; i++) {
3023 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
3024 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
3026 ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
3027 ast_inet_ntoa(rtp->them.sin_addr),
3028 ntohs(rtp->them.sin_port), strerror(errno));
3029 if (rtp_debug_test_addr(&rtp->them))
3030 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3031 ast_inet_ntoa(rtp->them.sin_addr),
3032 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
3033 /* Increment sequence number */
3035 /* Increment duration */
3036 rtp->send_duration += 160;
3037 /* Clear marker bit and set seqno */
3038 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
3041 /* Since we received a begin, we can safely store the digit and disable any compensation */
3042 rtp->sending_digit = 1;
3043 rtp->send_digit = digit;
3044 rtp->send_payload = payload;
3049 /*! \brief Send continuation frame for DTMF */
3050 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
3052 unsigned int *rtpheader;
3053 int hdrlen = 12, res = 0;
3056 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
3059 /* Setup packet to send */
3060 rtpheader = (unsigned int *)data;
3061 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
3062 rtpheader[1] = htonl(rtp->lastdigitts);
3063 rtpheader[2] = htonl(rtp->ssrc);
3064 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
3065 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
3068 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
3070 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
3071 ast_inet_ntoa(rtp->them.sin_addr),
3072 ntohs(rtp->them.sin_port), strerror(errno));
3073 if (rtp_debug_test_addr(&rtp->them))
3074 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3075 ast_inet_ntoa(rtp->them.sin_addr),
3076 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
3078 /* Increment sequence number */
3080 /* Increment duration */
3081 rtp->send_duration += 160;
3086 /*! \brief Send end packets for DTMF */
3087 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
3089 unsigned int *rtpheader;
3090 int hdrlen = 12, res = 0, i = 0;
3093 /* If no address, then bail out */
3094 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
3097 if ((digit <= '9') && (digit >= '0'))
3099 else if (digit == '*')
3101 else if (digit == '#')
3103 else if ((digit >= 'A') && (digit <= 'D'))
3104 digit = digit - 'A' + 12;
3105 else if ((digit >= 'a') && (digit <= 'd'))
3106 digit = digit - 'a' + 12;
3108 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
3112 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
3114 rtpheader = (unsigned int *)data;
3115 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
3116 rtpheader[1] = htonl(rtp->lastdigitts);
3117 rtpheader[2] = htonl(rtp->ssrc);
3118 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
3120 rtpheader[3] |= htonl((1 << 23));
3121 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
3122 /* Send 3 termination packets */
3123 for (i = 0; i < 3; i++) {
3124 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
3126 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
3127 ast_inet_ntoa(rtp->them.sin_addr),
3128 ntohs(rtp->them.sin_port), strerror(errno));
3129 if (rtp_debug_test_addr(&rtp->them))
3130 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3131 ast_inet_ntoa(rtp->them.sin_addr),
3132 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
3134 rtp->sending_digit = 0;
3135 rtp->send_digit = 0;
3136 /* Increment lastdigitts */
3137 rtp->lastdigitts += 960;
3143 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
3144 int ast_rtcp_send_h261fur(void *data)
3146 struct ast_rtp *rtp = data;
3149 rtp->rtcp->sendfur = 1;
3150 res = ast_rtcp_write(data);
3155 /*! \brief Send RTCP sender's report */
3156 static int ast_rtcp_write_sr(const void *data)
3158 struct ast_rtp *rtp = (struct ast_rtp *)data;
3162 unsigned int now_lsw;
3163 unsigned int now_msw;
3164 unsigned int *rtcpheader;
3166 unsigned int extended;
3167 unsigned int expected;
3168 unsigned int expected_interval;
3169 unsigned int received_interval;
3172 struct timeval dlsr;
3175 /* Commented condition is always not NULL if rtp->rtcp is not NULL */
3176 if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)