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 = 5000; /*!< First port for RTP sessions (set in rtp.conf) */
72 static int rtpend = 31000; /*!< 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 [...]"
101 /*! \brief RTP session description */
105 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
106 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
107 unsigned int themssrc; /*!< Their SSRC */
110 unsigned int lastrxts;
111 unsigned int lastividtimestamp;
112 unsigned int lastovidtimestamp;
113 unsigned int lastitexttimestamp;
114 unsigned int lastotexttimestamp;
115 unsigned int lasteventseqn;
116 int lastrxseqno; /*!< Last received sequence number */
117 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
118 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
119 unsigned int rxcount; /*!< How many packets have we received? */
120 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
121 unsigned int txcount; /*!< How many packets have we sent? */
122 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
123 unsigned int cycles; /*!< Shifted count of sequence number cycles */
124 double rxjitter; /*!< Interarrival jitter at the moment */
125 double rxtransit; /*!< Relative transit time for previous packet */
129 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
130 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
131 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
133 /* DTMF Reception Variables */
135 unsigned int lastevent;
137 unsigned int dtmfsamples;
138 /* DTMF Transmission Variables */
139 unsigned int lastdigitts;
140 char sending_digit; /*!< boolean - are we sending digits */
141 char send_digit; /*!< digit we are sending */
146 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
147 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
148 struct timeval rxcore;
149 struct timeval txcore;
150 double drxcore; /*!< The double representation of the first received packet */
151 struct timeval lastrx; /*!< timeval when we last received a packet */
152 struct timeval dtmfmute;
153 struct ast_smoother *smoother;
155 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
156 unsigned short rxseqno;
157 struct sched_context *sched;
158 struct io_context *io;
160 ast_rtp_callback callback;
162 ast_mutex_t bridge_lock;
164 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
165 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
166 int rtp_lookup_code_cache_code;
167 int rtp_lookup_code_cache_result;
168 struct ast_rtcp *rtcp;
169 struct ast_codec_pref pref;
170 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
172 enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
173 struct sockaddr_in strict_rtp_address; /*!< Remote address information for strict RTP purposes */
175 int set_marker_bit:1; /*!< Whether to set the marker bit or not */
179 static struct ast_frame *red_t140_to_red(struct rtp_red *red);
180 static int red_write(const void *data);
183 struct ast_frame t140; /*!< Primary data */
184 struct ast_frame t140red; /*!< Redundant t140*/
185 unsigned char pt[RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
186 unsigned char ts[RED_MAX_GENERATION]; /*!< Time stamps */
187 unsigned char len[RED_MAX_GENERATION]; /*!< length of each generation */
188 int num_gen; /*!< Number of generations */
189 int schedid; /*!< Timer id */
190 int ti; /*!< How long to buffer data before send */
191 unsigned char t140red_data[64000];
192 unsigned char buf_data[64000]; /*!< buffered primary data */
197 /* Forward declarations */
198 static int ast_rtcp_write(const void *data);
199 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
200 static int ast_rtcp_write_sr(const void *data);
201 static int ast_rtcp_write_rr(const void *data);
202 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
203 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
204 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
206 #define FLAG_3389_WARNING (1 << 0)
207 #define FLAG_NAT_ACTIVE (3 << 1)
208 #define FLAG_NAT_INACTIVE (0 << 1)
209 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
210 #define FLAG_HAS_DTMF (1 << 3)
211 #define FLAG_P2P_SENT_MARK (1 << 4)
212 #define FLAG_P2P_NEED_DTMF (1 << 5)
213 #define FLAG_CALLBACK_MODE (1 << 6)
214 #define FLAG_DTMF_COMPENSATE (1 << 7)
215 #define FLAG_HAS_STUN (1 << 8)
218 * \brief Structure defining an RTCP session.
220 * The concept "RTCP session" is not defined in RFC 3550, but since
221 * this structure is analogous to ast_rtp, which tracks a RTP session,
222 * it is logical to think of this as a RTCP session.
224 * RTCP packet is defined on page 9 of RFC 3550.
229 int s; /*!< Socket */
230 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
231 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
232 unsigned int soc; /*!< What they told us */
233 unsigned int spc; /*!< What they told us */
234 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
235 struct timeval rxlsr; /*!< Time when we got their last SR */
236 struct timeval txlsr; /*!< Time when we sent or last SR*/
237 unsigned int expected_prior; /*!< no. packets in previous interval */
238 unsigned int received_prior; /*!< no. packets received in previous interval */
239 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
240 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
241 unsigned int sr_count; /*!< number of SRs we've sent */
242 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
243 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
244 double rtt; /*!< Last reported rtt */
245 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
246 unsigned int reported_lost; /*!< Reported lost packets in their RR */
247 char quality[AST_MAX_USER_FIELD];
248 char quality_jitter[AST_MAX_USER_FIELD];
249 char quality_loss[AST_MAX_USER_FIELD];
250 char quality_rtt[AST_MAX_USER_FIELD];
252 double reported_maxjitter;
253 double reported_minjitter;
254 double reported_normdev_jitter;
255 double reported_stdev_jitter;
256 unsigned int reported_jitter_count;
258 double reported_maxlost;
259 double reported_minlost;
260 double reported_normdev_lost;
261 double reported_stdev_lost;
266 double normdev_rxlost;
268 unsigned int rxlost_count;
272 double normdev_rxjitter;
273 double stdev_rxjitter;
274 unsigned int rxjitter_count;
279 unsigned int rtt_count;
284 * \brief STUN support code
286 * This code provides some support for doing STUN transactions.
287 * Eventually it should be moved elsewhere as other protocols
288 * than RTP can benefit from it - e.g. SIP.
289 * STUN is described in RFC3489 and it is based on the exchange
290 * of UDP packets between a client and one or more servers to
291 * determine the externally visible address (and port) of the client
292 * once it has gone through the NAT boxes that connect it to the
294 * The simplest request packet is just the header defined in
295 * struct stun_header, and from the response we may just look at
296 * one attribute, STUN_MAPPED_ADDRESS, that we find in the response.
297 * By doing more transactions with different server addresses we
298 * may determine more about the behaviour of the NAT boxes, of
299 * course - the details are in the RFC.
301 * All STUN packets start with a simple header made of a type,
302 * length (excluding the header) and a 16-byte random transaction id.
303 * Following the header we may have zero or more attributes, each
304 * structured as a type, length and a value (whose format depends
305 * on the type, but often contains addresses).
306 * Of course all fields are in network format.
309 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
312 unsigned short msgtype;
313 unsigned short msglen;
315 unsigned char ies[0];
316 } __attribute__((packed));
321 unsigned char value[0];
322 } __attribute__((packed));
325 * The format normally used for addresses carried by STUN messages.
328 unsigned char unused;
329 unsigned char family;
332 } __attribute__((packed));
334 #define STUN_IGNORE (0)
335 #define STUN_ACCEPT (1)
337 /*! \brief STUN message types
338 * 'BIND' refers to transactions used to determine the externally
339 * visible addresses. 'SEC' refers to transactions used to establish
340 * a session key for subsequent requests.
341 * 'SEC' functionality is not supported here.
344 #define STUN_BINDREQ 0x0001
345 #define STUN_BINDRESP 0x0101
346 #define STUN_BINDERR 0x0111
347 #define STUN_SECREQ 0x0002
348 #define STUN_SECRESP 0x0102
349 #define STUN_SECERR 0x0112
351 /*! \brief Basic attribute types in stun messages.
352 * Messages can also contain custom attributes (codes above 0x7fff)
354 #define STUN_MAPPED_ADDRESS 0x0001
355 #define STUN_RESPONSE_ADDRESS 0x0002
356 #define STUN_CHANGE_REQUEST 0x0003
357 #define STUN_SOURCE_ADDRESS 0x0004
358 #define STUN_CHANGED_ADDRESS 0x0005
359 #define STUN_USERNAME 0x0006
360 #define STUN_PASSWORD 0x0007
361 #define STUN_MESSAGE_INTEGRITY 0x0008
362 #define STUN_ERROR_CODE 0x0009
363 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
364 #define STUN_REFLECTED_FROM 0x000b
366 /*! \brief helper function to print message names */
367 static const char *stun_msg2str(int msg)
371 return "Binding Request";
373 return "Binding Response";
375 return "Binding Error Response";
377 return "Shared Secret Request";
379 return "Shared Secret Response";
381 return "Shared Secret Error Response";
383 return "Non-RFC3489 Message";
386 /*! \brief helper function to print attribute names */
387 static const char *stun_attr2str(int msg)
390 case STUN_MAPPED_ADDRESS:
391 return "Mapped Address";
392 case STUN_RESPONSE_ADDRESS:
393 return "Response Address";
394 case STUN_CHANGE_REQUEST:
395 return "Change Request";
396 case STUN_SOURCE_ADDRESS:
397 return "Source Address";
398 case STUN_CHANGED_ADDRESS:
399 return "Changed Address";
404 case STUN_MESSAGE_INTEGRITY:
405 return "Message Integrity";
406 case STUN_ERROR_CODE:
408 case STUN_UNKNOWN_ATTRIBUTES:
409 return "Unknown Attributes";
410 case STUN_REFLECTED_FROM:
411 return "Reflected From";
413 return "Non-RFC3489 Attribute";
416 /*! \brief here we store credentials extracted from a message */
418 const char *username;
419 const char *password;
422 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
425 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
426 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
427 switch (ntohs(attr->attr)) {
429 state->username = (const char *) (attr->value);
432 state->password = (const char *) (attr->value);
436 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
437 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
442 /*! \brief append a string to an STUN message */
443 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
445 int size = sizeof(**attr) + strlen(s);
447 (*attr)->attr = htons(attrval);
448 (*attr)->len = htons(strlen(s));
449 memcpy((*attr)->value, s, strlen(s));
450 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
456 /*! \brief append an address to an STUN message */
457 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sock_in, int *len, int *left)
459 int size = sizeof(**attr) + 8;
460 struct stun_addr *addr;
462 (*attr)->attr = htons(attrval);
463 (*attr)->len = htons(8);
464 addr = (struct stun_addr *)((*attr)->value);
467 addr->port = sock_in->sin_port;
468 addr->addr = sock_in->sin_addr.s_addr;
469 (*attr) = (struct stun_attr *)((*attr)->value + 8);
475 /*! \brief wrapper to send an STUN message */
476 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
478 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
479 (struct sockaddr *)dst, sizeof(*dst));
482 /*! \brief helper function to generate a random request id */
483 static void stun_req_id(struct stun_header *req)
486 for (x = 0; x < 4; x++)
487 req->id.id[x] = ast_random();
490 size_t ast_rtp_alloc_size(void)
492 return sizeof(struct ast_rtp);
495 /*! \brief callback type to be invoked on stun responses. */
496 typedef int (stun_cb_f)(struct stun_attr *attr, void *arg);
498 /*! \brief handle an incoming STUN message.
500 * Do some basic sanity checks on packet size and content,
501 * try to extract a bit of information, and possibly reply.
502 * At the moment this only processes BIND requests, and returns
503 * the externally visible address of the request.
504 * If a callback is specified, invoke it with the attribute.
506 static int stun_handle_packet(int s, struct sockaddr_in *src,
507 unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
509 struct stun_header *hdr = (struct stun_header *)data;
510 struct stun_attr *attr;
511 struct stun_state st;
512 int ret = STUN_IGNORE;
515 /* On entry, 'len' is the length of the udp payload. After the
516 * initial checks it becomes the size of unprocessed options,
517 * while 'data' is advanced accordingly.
519 if (len < sizeof(struct stun_header)) {
520 ast_debug(1, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
523 len -= sizeof(struct stun_header);
524 data += sizeof(struct stun_header);
525 x = ntohs(hdr->msglen); /* len as advertised in the message */
527 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), x);
529 ast_debug(1, "Scrambled STUN packet length (got %d, expecting %d)\n", x, (int)len);
532 memset(&st, 0, sizeof(st));
534 if (len < sizeof(struct stun_attr)) {
535 ast_debug(1, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
538 attr = (struct stun_attr *)data;
539 /* compute total attribute length */
540 x = ntohs(attr->len) + sizeof(struct stun_attr);
542 ast_debug(1, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x, (int)len);
547 if (stun_process_attr(&st, attr)) {
548 ast_debug(1, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
551 /* Clear attribute id: in case previous entry was a string,
552 * this will act as the terminator for the string.
558 /* Null terminate any string.
559 * XXX NOTE, we write past the size of the buffer passed by the
560 * caller, so this is potentially dangerous. The only thing that
561 * saves us is that usually we read the incoming message in a
562 * much larger buffer in the struct ast_rtp
566 /* Now prepare to generate a reply, which at the moment is done
567 * only for properly formed (len == 0) STUN_BINDREQ messages.
570 unsigned char respdata[1024];
571 struct stun_header *resp = (struct stun_header *)respdata;
572 int resplen = 0; /* len excluding header */
573 int respleft = sizeof(respdata) - sizeof(struct stun_header);
578 attr = (struct stun_attr *)resp->ies;
579 switch (ntohs(hdr->msgtype)) {
582 ast_verbose("STUN Bind Request, username: %s\n",
583 st.username ? st.username : "<none>");
585 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
586 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
587 resp->msglen = htons(resplen);
588 resp->msgtype = htons(STUN_BINDRESP);
589 stun_send(s, src, resp);
594 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
600 /*! \brief Extract the STUN_MAPPED_ADDRESS from the stun response.
601 * This is used as a callback for stun_handle_response
602 * when called from ast_stun_request.
604 static int stun_get_mapped(struct stun_attr *attr, void *arg)
606 struct stun_addr *addr = (struct stun_addr *)(attr + 1);
607 struct sockaddr_in *sa = (struct sockaddr_in *)arg;
609 if (ntohs(attr->attr) != STUN_MAPPED_ADDRESS || ntohs(attr->len) != 8)
610 return 1; /* not us. */
611 sa->sin_port = addr->port;
612 sa->sin_addr.s_addr = addr->addr;
616 /*! \brief Generic STUN request
617 * Send a generic stun request to the server specified,
618 * possibly waiting for a reply and filling the 'reply' field with
619 * the externally visible address. Note that in this case the request
621 * (Note, the interface may change slightly in the future).
623 * \param s the socket used to send the request
624 * \param dst the address of the STUN server
625 * \param username if non null, add the username in the request
626 * \param answer if non null, the function waits for a response and
627 * puts here the externally visible address.
628 * \return 0 on success, other values on error.
630 int ast_stun_request(int s, struct sockaddr_in *dst,
631 const char *username, struct sockaddr_in *answer)
633 struct stun_header *req;
634 unsigned char reqdata[1024];
636 struct stun_attr *attr;
640 req = (struct stun_header *)reqdata;
643 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
646 attr = (struct stun_attr *)req->ies;
648 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
649 req->msglen = htons(reqlen);
650 req->msgtype = htons(STUN_BINDREQ);
651 for (retry = 0; retry < 3; retry++) { /* XXX make retries configurable */
652 /* send request, possibly wait for reply */
653 unsigned char reply_buf[1024];
655 struct timeval to = { 3, 0 }; /* timeout, make it configurable */
656 struct sockaddr_in src;
659 res = stun_send(s, dst, req);
661 ast_log(LOG_WARNING, "ast_stun_request send #%d failed error %d, retry\n",
669 res = ast_select(s + 1, &rfds, NULL, NULL, &to);
670 if (res <= 0) /* timeout or error */
672 memset(&src, '\0', sizeof(src));
673 srclen = sizeof(src);
674 /* XXX pass -1 in the size, because stun_handle_packet might
675 * write past the end of the buffer.
677 res = recvfrom(s, reply_buf, sizeof(reply_buf) - 1,
678 0, (struct sockaddr *)&src, &srclen);
680 ast_log(LOG_WARNING, "ast_stun_request recvfrom #%d failed error %d, retry\n",
684 memset(answer, '\0', sizeof(struct sockaddr_in));
685 stun_handle_packet(s, &src, reply_buf, res,
686 stun_get_mapped, answer);
687 res = 0; /* signal regular exit */
693 /*! \brief send a STUN BIND request to the given destination.
694 * Optionally, add a username if specified.
696 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
698 ast_stun_request(rtp->s, suggestion, username, NULL);
701 /*! \brief List of current sessions */
702 static AST_RWLIST_HEAD_STATIC(protos, ast_rtp_protocol);
704 static void timeval2ntp(struct timeval when, unsigned int *msw, unsigned int *lsw)
706 unsigned int sec, usec, frac;
707 sec = when.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
709 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
714 int ast_rtp_fd(struct ast_rtp *rtp)
719 int ast_rtcp_fd(struct ast_rtp *rtp)
726 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
728 unsigned int interval;
729 /*! \todo XXX Do a more reasonable calculation on this one
730 * Look in RFC 3550 Section A.7 for an example*/
731 interval = rtcpinterval;
735 /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
736 void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
738 rtp->rtptimeout = (-1) * rtp->rtptimeout;
739 rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
742 /*! \brief Set rtp timeout */
743 void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
745 rtp->rtptimeout = timeout;
748 /*! \brief Set rtp hold timeout */
749 void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
751 rtp->rtpholdtimeout = timeout;
754 /*! \brief set RTP keepalive interval */
755 void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
757 rtp->rtpkeepalive = period;
760 /*! \brief Get rtp timeout */
761 int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
763 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
765 return rtp->rtptimeout;
768 /*! \brief Get rtp hold timeout */
769 int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
771 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
773 return rtp->rtpholdtimeout;
776 /*! \brief Get RTP keepalive interval */
777 int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
779 return rtp->rtpkeepalive;
782 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
787 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
789 rtp->callback = callback;
792 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
797 int ast_rtp_getnat(struct ast_rtp *rtp)
799 return ast_test_flag(rtp, FLAG_NAT_ACTIVE);
802 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
804 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
807 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
809 ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
812 void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
814 ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
817 static void rtp_bridge_lock(struct ast_rtp *rtp)
820 ast_mutex_lock(&rtp->bridge_lock);
825 static void rtp_bridge_unlock(struct ast_rtp *rtp)
828 ast_mutex_unlock(&rtp->bridge_lock);
833 /*! \brief Calculate normal deviation */
834 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
836 normdev = normdev * sample_count + sample;
839 return normdev / sample_count;
842 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
845 for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
846 return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
847 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
850 #define SQUARE(x) ((x) * (x))
852 stddev = sample_count * stddev;
856 ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
857 ( SQUARE(sample - normdev_curent) / sample_count );
862 static struct ast_frame *send_dtmf(struct ast_rtp *rtp, enum ast_frame_type type)
864 if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
865 (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
866 ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
868 rtp->dtmfsamples = 0;
869 return &ast_null_frame;
871 ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
872 if (rtp->resp == 'X') {
873 rtp->f.frametype = AST_FRAME_CONTROL;
874 rtp->f.subclass = AST_CONTROL_FLASH;
876 rtp->f.frametype = type;
877 rtp->f.subclass = rtp->resp;
887 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
891 if (rtpdebugaddr.sin_addr.s_addr) {
892 if (((ntohs(rtpdebugaddr.sin_port) != 0)
893 && (rtpdebugaddr.sin_port != addr->sin_port))
894 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
900 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
904 if (rtcpdebugaddr.sin_addr.s_addr) {
905 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
906 && (rtcpdebugaddr.sin_port != addr->sin_port))
907 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
914 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
918 struct ast_frame *f = NULL;
923 /* We should have at least 4 bytes in RTP data */
927 /* The format of Cisco RTP DTMF packet looks like next:
928 +0 - sequence number of DTMF RTP packet (begins from 1,
931 +1 (bit 0) - flaps by different DTMF digits delimited by audio
932 or repeated digit without audio???
933 +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
934 then falls to 0 at its end)
935 +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
936 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
937 by each new packet and thus provides some redudancy.
939 Sample of Cisco RTP DTMF packet is (all data in hex):
940 19 07 00 02 12 02 20 02
941 showing end of DTMF digit '2'.
944 27 07 00 02 0A 02 20 02
945 28 06 20 02 00 02 0A 02
946 shows begin of new digit '2' with very short pause (20 ms) after
947 previous digit '2'. Bit +1.0 flips at begin of new digit.
949 Cisco RTP DTMF packets comes as replacement of audio RTP packets
950 so its uses the same sequencing and timestamping rules as replaced
951 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
952 on audio framing parameters. Marker bit isn't used within stream of
953 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
954 are not sequential at borders between DTMF and audio streams,
960 event = data[3] & 0x1f;
962 if (option_debug > 2 || rtpdebug)
963 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);
966 } else if (event < 11) {
968 } else if (event < 12) {
970 } else if (event < 16) {
971 resp = 'A' + (event - 12);
972 } else if (event < 17) {
975 if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
977 /* Why we should care on DTMF compensation at reception? */
978 if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
979 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
980 rtp->dtmfsamples = 0;
982 } else if ((rtp->resp == resp) && !power) {
983 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
984 f->samples = rtp->dtmfsamples * 8;
986 } else if (rtp->resp == resp)
987 rtp->dtmfsamples += 20 * 8;
988 rtp->dtmfcount = dtmftimeout;
993 * \brief Process RTP DTMF and events according to RFC 2833.
995 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
1004 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp)
1007 unsigned int event_end;
1008 unsigned int samples;
1010 struct ast_frame *f = NULL;
1012 /* Figure out event, event end, and samples */
1013 event = ntohl(*((unsigned int *)(data)));
1015 event_end = ntohl(*((unsigned int *)(data)));
1018 samples = ntohl(*((unsigned int *)(data)));
1021 /* Print out debug if turned on */
1022 if (rtpdebug || option_debug > 2)
1023 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
1025 /* Figure out what digit was pressed */
1028 } else if (event < 11) {
1030 } else if (event < 12) {
1032 } else if (event < 16) {
1033 resp = 'A' + (event - 12);
1034 } else if (event < 17) { /* Event 16: Hook flash */
1037 /* Not a supported event */
1038 ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
1039 return &ast_null_frame;
1042 if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
1043 if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
1045 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
1047 rtp->lastevent = timestamp;
1050 if ((!(rtp->resp) && (!(event_end & 0x80))) || (rtp->resp && rtp->resp != resp)) {
1052 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
1053 } else if ((event_end & 0x80) && (rtp->lastevent != seqno) && rtp->resp) {
1054 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
1055 f->len = ast_tvdiff_ms(ast_samp2tv(samples, 8000), ast_tv(0, 0)); /* XXX hard coded 8kHz */
1057 rtp->lastevent = seqno;
1061 rtp->dtmfcount = dtmftimeout;
1062 rtp->dtmfsamples = samples;
1068 * \brief Process Comfort Noise RTP.
1070 * This is incomplete at the moment.
1073 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
1075 struct ast_frame *f = NULL;
1076 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
1077 totally help us out becuase we don't have an engine to keep it going and we are not
1078 guaranteed to have it every 20ms or anything */
1080 ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
1082 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
1083 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
1084 ast_inet_ntoa(rtp->them.sin_addr));
1085 ast_set_flag(rtp, FLAG_3389_WARNING);
1088 /* Must have at least one byte */
1092 rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
1093 rtp->f.datalen = len - 1;
1094 rtp->f.offset = AST_FRIENDLY_OFFSET;
1095 memcpy(rtp->f.data.ptr, data + 1, len - 1);
1097 rtp->f.data.ptr = NULL;
1101 rtp->f.frametype = AST_FRAME_CNG;
1102 rtp->f.subclass = data[0] & 0x7f;
1103 rtp->f.datalen = len - 1;
1105 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
1110 static int rtpread(int *id, int fd, short events, void *cbdata)
1112 struct ast_rtp *rtp = cbdata;
1113 struct ast_frame *f;
1114 f = ast_rtp_read(rtp);
1117 rtp->callback(rtp, f, rtp->data);
1122 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
1125 int position, i, packetwords;
1127 struct sockaddr_in sock_in;
1128 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
1129 unsigned int *rtcpheader;
1132 unsigned int length;
1141 struct ast_frame *f = &ast_null_frame;
1143 double reported_jitter;
1144 double reported_normdev_jitter_current;
1145 double normdevrtt_current;
1146 double reported_lost;
1147 double reported_normdev_lost_current;
1149 if (!rtp || !rtp->rtcp)
1150 return &ast_null_frame;
1152 len = sizeof(sock_in);
1154 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
1155 0, (struct sockaddr *)&sock_in, &len);
1156 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
1159 ast_assert(errno != EBADF);
1160 if (errno != EAGAIN) {
1161 ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n", strerror(errno));
1164 return &ast_null_frame;
1167 packetwords = res / 4;
1170 /* Send to whoever sent to us */
1171 if ((rtp->rtcp->them.sin_addr.s_addr != sock_in.sin_addr.s_addr) ||
1172 (rtp->rtcp->them.sin_port != sock_in.sin_port)) {
1173 memcpy(&rtp->rtcp->them, &sock_in, sizeof(rtp->rtcp->them));
1174 if (option_debug || rtpdebug)
1175 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));
1179 ast_debug(1, "Got RTCP report of %d bytes\n", res);
1181 /* Process a compound packet */
1183 while (position < packetwords) {
1185 length = ntohl(rtcpheader[i]);
1186 pt = (length & 0xff0000) >> 16;
1187 rc = (length & 0x1f000000) >> 24;
1190 if ((i + length) > packetwords) {
1191 if (option_debug || rtpdebug)
1192 ast_log(LOG_DEBUG, "RTCP Read too short\n");
1193 return &ast_null_frame;
1196 if (rtcp_debug_test_addr(&sock_in)) {
1197 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port));
1198 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
1199 ast_verbose("Reception reports: %d\n", rc);
1200 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
1203 i += 2; /* Advance past header and ssrc */
1207 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
1208 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
1209 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
1210 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
1212 if (rtcp_debug_test_addr(&sock_in)) {
1213 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
1214 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
1215 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
1220 /* Intentional fall through */
1222 /* Don't handle multiple reception reports (rc > 1) yet */
1223 /* Calculate RTT per RFC */
1224 gettimeofday(&now, NULL);
1225 timeval2ntp(now, &msw, &lsw);
1226 if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
1227 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
1228 lsr = ntohl(rtcpheader[i + 4]);
1229 dlsr = ntohl(rtcpheader[i + 5]);
1230 rtt = comp - lsr - dlsr;
1232 /* Convert end to end delay to usec (keeping the calculation in 64bit space)
1233 sess->ee_delay = (eedelay * 1000) / 65536; */
1235 rtt = (rtt * 1000000) >> 16;
1237 rtt = (rtt * 1000) >> 16;
1241 rttsec = rtt / 1000.;
1242 rtp->rtcp->rtt = rttsec;
1244 if (comp - dlsr >= lsr) {
1245 rtp->rtcp->accumulated_transit += rttsec;
1247 if (rtp->rtcp->rtt_count == 0)
1248 rtp->rtcp->minrtt = rttsec;
1250 if (rtp->rtcp->maxrtt<rttsec)
1251 rtp->rtcp->maxrtt = rttsec;
1253 if (rtp->rtcp->minrtt>rttsec)
1254 rtp->rtcp->minrtt = rttsec;
1256 normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt, rttsec, rtp->rtcp->rtt_count);
1258 rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt, rttsec, rtp->rtcp->normdevrtt, normdevrtt_current, rtp->rtcp->rtt_count);
1260 rtp->rtcp->normdevrtt = normdevrtt_current;
1262 rtp->rtcp->rtt_count++;
1263 } else if (rtcp_debug_test_addr(&sock_in)) {
1264 ast_verbose("Internal RTCP NTP clock skew detected: "
1265 "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
1267 lsr, comp, dlsr, dlsr / 65536,
1268 (dlsr % 65536) * 1000 / 65536,
1269 dlsr - (comp - lsr));
1273 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
1274 reported_jitter = (double) rtp->rtcp->reported_jitter;
1276 if (rtp->rtcp->reported_jitter_count == 0)
1277 rtp->rtcp->reported_minjitter = reported_jitter;
1279 if (reported_jitter < rtp->rtcp->reported_minjitter)
1280 rtp->rtcp->reported_minjitter = reported_jitter;
1282 if (reported_jitter > rtp->rtcp->reported_maxjitter)
1283 rtp->rtcp->reported_maxjitter = reported_jitter;
1285 reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);
1287 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);
1289 rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;
1291 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
1293 reported_lost = (double) rtp->rtcp->reported_lost;
1295 /* using same counter as for jitter */
1296 if (rtp->rtcp->reported_jitter_count == 0)
1297 rtp->rtcp->reported_minlost = reported_lost;
1299 if (reported_lost < rtp->rtcp->reported_minlost)
1300 rtp->rtcp->reported_minlost = reported_lost;
1302 if (reported_lost > rtp->rtcp->reported_maxlost)
1303 rtp->rtcp->reported_maxlost = reported_lost;
1305 reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);
1307 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);
1309 rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;
1311 rtp->rtcp->reported_jitter_count++;
1313 if (rtcp_debug_test_addr(&sock_in)) {
1314 ast_verbose(" Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
1315 ast_verbose(" Packets lost so far: %d\n", rtp->rtcp->reported_lost);
1316 ast_verbose(" Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
1317 ast_verbose(" Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
1318 ast_verbose(" Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
1319 ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
1320 ast_verbose(" DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
1322 ast_verbose(" RTT: %lu(sec)\n", (unsigned long) rtt);
1326 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s:%d\r\n"
1328 "ReceptionReports: %d\r\n"
1329 "SenderSSRC: %u\r\n"
1330 "FractionLost: %ld\r\n"
1331 "PacketsLost: %d\r\n"
1332 "HighestSequence: %ld\r\n"
1333 "SequenceNumberCycles: %ld\r\n"
1335 "LastSR: %lu.%010lu\r\n"
1336 "DLSR: %4.4f(sec)\r\n"
1337 "RTT: %llu(sec)\r\n",
1338 ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port),
1339 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1342 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1343 rtp->rtcp->reported_lost,
1344 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1345 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1346 rtp->rtcp->reported_jitter,
1347 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1348 ntohl(rtcpheader[i + 5])/65536.0,
1349 (unsigned long long)rtt);
1351 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s:%d\r\n"
1353 "ReceptionReports: %d\r\n"
1354 "SenderSSRC: %u\r\n"
1355 "FractionLost: %ld\r\n"
1356 "PacketsLost: %d\r\n"
1357 "HighestSequence: %ld\r\n"
1358 "SequenceNumberCycles: %ld\r\n"
1360 "LastSR: %lu.%010lu\r\n"
1361 "DLSR: %4.4f(sec)\r\n",
1362 ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port),
1363 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1366 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1367 rtp->rtcp->reported_lost,
1368 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1369 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1370 rtp->rtcp->reported_jitter,
1371 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
1372 ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1373 ntohl(rtcpheader[i + 5])/65536.0);
1377 if (rtcp_debug_test_addr(&sock_in))
1378 ast_verbose("Received an RTCP Fast Update Request\n");
1379 rtp->f.frametype = AST_FRAME_CONTROL;
1380 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
1388 if (rtcp_debug_test_addr(&sock_in))
1389 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1392 if (rtcp_debug_test_addr(&sock_in))
1393 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1396 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));
1399 position += (length + 1);
1401 rtp->rtcp->rtcp_info = 1;
1405 static void calc_rxstamp(struct timeval *when, struct ast_rtp *rtp, unsigned int timestamp, int mark)
1409 double current_time;
1414 double normdev_rxjitter_current;
1415 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
1416 gettimeofday(&rtp->rxcore, NULL);
1417 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
1418 /* map timestamp to a real time */
1419 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
1420 rtp->rxcore.tv_sec -= timestamp / 8000;
1421 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
1422 /* Round to 0.1ms for nice, pretty timestamps */
1423 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
1424 if (rtp->rxcore.tv_usec < 0) {
1425 /* Adjust appropriately if necessary */
1426 rtp->rxcore.tv_usec += 1000000;
1427 rtp->rxcore.tv_sec -= 1;
1431 gettimeofday(&now,NULL);
1432 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
1433 when->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
1434 when->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
1435 if (when->tv_usec >= 1000000) {
1436 when->tv_usec -= 1000000;
1439 prog = (double)((timestamp-rtp->seedrxts)/8000.);
1440 dtv = (double)rtp->drxcore + (double)(prog);
1441 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
1442 transit = current_time - dtv;
1443 d = transit - rtp->rxtransit;
1444 rtp->rxtransit = transit;
1447 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1448 if (rtp->rtcp && rtp->rxjitter > rtp->rtcp->maxrxjitter)
1449 rtp->rtcp->maxrxjitter = rtp->rxjitter;
1450 if (rtp->rtcp->rxjitter_count == 1)
1451 rtp->rtcp->minrxjitter = rtp->rxjitter;
1452 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1453 rtp->rtcp->minrxjitter = rtp->rxjitter;
1455 normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
1456 rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
1458 rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
1459 rtp->rtcp->rxjitter_count++;
1462 /*! \brief Perform a Packet2Packet RTP write */
1463 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, struct ast_rtp *bridged, unsigned int *rtpheader, int len, int hdrlen)
1465 int res = 0, payload = 0, bridged_payload = 0, mark;
1466 struct rtpPayloadType rtpPT;
1467 int reconstruct = ntohl(rtpheader[0]);
1469 /* Get fields from packet */
1470 payload = (reconstruct & 0x7f0000) >> 16;
1471 mark = (((reconstruct & 0x800000) >> 23) != 0);
1473 /* Check what the payload value should be */
1474 rtpPT = ast_rtp_lookup_pt(rtp, payload);
1476 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
1477 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
1480 /* Otherwise adjust bridged payload to match */
1481 bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
1483 /* 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 */
1484 if (!bridged->current_RTP_PT[bridged_payload].code)
1488 /* If the mark bit has not been sent yet... do it now */
1489 if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
1491 ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
1494 /* Reconstruct part of the packet */
1495 reconstruct &= 0xFF80FFFF;
1496 reconstruct |= (bridged_payload << 16);
1497 reconstruct |= (mark << 23);
1498 rtpheader[0] = htonl(reconstruct);
1500 /* Send the packet back out */
1501 res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
1503 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1504 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));
1505 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1506 if (option_debug || rtpdebug)
1507 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));
1508 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1511 } else if (rtp_debug_test_addr(&bridged->them))
1512 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);
1517 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
1520 struct sockaddr_in sock_in;
1531 unsigned int timestamp;
1532 unsigned int *rtpheader;
1533 struct rtpPayloadType rtpPT;
1534 struct ast_rtp *bridged = NULL;
1537 /* If time is up, kill it */
1538 if (rtp->sending_digit)
1539 ast_rtp_senddigit_continuation(rtp);
1541 len = sizeof(sock_in);
1543 /* Cache where the header will go */
1544 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
1545 0, (struct sockaddr *)&sock_in, &len);
1547 /* If strict RTP protection is enabled see if we need to learn this address or if the packet should be dropped */
1548 if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
1549 /* Copy over address that this packet was received on */
1550 memcpy(&rtp->strict_rtp_address, &sock_in, sizeof(rtp->strict_rtp_address));
1551 /* Now move over to actually protecting the RTP port */
1552 rtp->strict_rtp_state = STRICT_RTP_CLOSED;
1553 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));
1554 } else if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
1555 /* If the address we previously learned doesn't match the address this packet came in on simply drop it */
1556 if ((rtp->strict_rtp_address.sin_addr.s_addr != sock_in.sin_addr.s_addr) || (rtp->strict_rtp_address.sin_port != sock_in.sin_port)) {
1557 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(sock_in.sin_addr), ntohs(sock_in.sin_port), ast_inet_ntoa(rtp->strict_rtp_address.sin_addr), ntohs(rtp->strict_rtp_address.sin_port));
1558 return &ast_null_frame;
1562 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
1564 ast_assert(errno != EBADF);
1565 if (errno != EAGAIN) {
1566 ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
1569 return &ast_null_frame;
1573 ast_log(LOG_WARNING, "RTP Read too short\n");
1574 return &ast_null_frame;
1578 seqno = ntohl(rtpheader[0]);
1580 /* Check RTP version */
1581 version = (seqno & 0xC0000000) >> 30;
1583 /* If the two high bits are 0, this might be a
1584 * STUN message, so process it. stun_handle_packet()
1585 * answers to requests, and it returns STUN_ACCEPT
1586 * if the request is valid.
1588 if ((stun_handle_packet(rtp->s, &sock_in, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == STUN_ACCEPT) &&
1589 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
1590 memcpy(&rtp->them, &sock_in, sizeof(rtp->them));
1592 return &ast_null_frame;
1595 #if 0 /* Allow to receive RTP stream with closed transmission path */
1596 /* If we don't have the other side's address, then ignore this */
1597 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1598 return &ast_null_frame;
1601 /* Send to whoever send to us if NAT is turned on */
1603 if ((rtp->them.sin_addr.s_addr != sock_in.sin_addr.s_addr) ||
1604 (rtp->them.sin_port != sock_in.sin_port)) {
1605 rtp->them = sock_in;
1608 memcpy(&rtp->rtcp->them, &sock_in, sizeof(rtp->rtcp->them));
1609 h = ntohs(rtp->them.sin_port);
1610 rtp->rtcp->them.sin_port = htons(h + 1);
1613 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1614 if (option_debug || rtpdebug)
1615 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));
1619 /* If we are bridged to another RTP stream, send direct */
1620 if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
1621 return &ast_null_frame;
1624 return &ast_null_frame;
1626 payloadtype = (seqno & 0x7f0000) >> 16;
1627 padding = seqno & (1 << 29);
1628 mark = seqno & (1 << 23);
1629 ext = seqno & (1 << 28);
1630 cc = (seqno & 0xF000000) >> 24;
1632 timestamp = ntohl(rtpheader[1]);
1633 ssrc = ntohl(rtpheader[2]);
1635 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1636 if (option_debug || rtpdebug)
1637 ast_debug(0, "Forcing Marker bit, because SSRC has changed\n");
1644 /* Remove padding bytes */
1645 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1649 /* CSRC fields present */
1654 /* RTP Extension present */
1655 hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
1659 profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
1660 if (profile == 0x505a)
1661 ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
1663 ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
1668 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1669 return &ast_null_frame;
1672 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1674 if (rtp->rxcount==1) {
1675 /* This is the first RTP packet successfully received from source */
1676 rtp->seedrxseqno = seqno;
1679 /* Do not schedule RR if RTCP isn't run */
1680 if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
1681 /* Schedule transmission of Receiver Report */
1682 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1684 if ((int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
1685 rtp->cycles += RTP_SEQ_MOD;
1687 prev_seqno = rtp->lastrxseqno;
1689 rtp->lastrxseqno = seqno;
1692 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1694 if (rtp_debug_test_addr(&sock_in))
1695 ast_verbose("Got RTP packet from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1696 ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1698 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1699 if (!rtpPT.isAstFormat) {
1700 struct ast_frame *f = NULL;
1702 /* This is special in-band data that's not one of our codecs */
1703 if (rtpPT.code == AST_RTP_DTMF) {
1704 /* It's special -- rfc2833 process it */
1705 if (rtp_debug_test_addr(&sock_in)) {
1706 unsigned char *data;
1708 unsigned int event_end;
1709 unsigned int duration;
1710 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1711 event = ntohl(*((unsigned int *)(data)));
1713 event_end = ntohl(*((unsigned int *)(data)));
1716 duration = ntohl(*((unsigned int *)(data)));
1718 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(sock_in.sin_addr), ntohs(sock_in.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
1720 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp);
1721 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1722 /* It's really special -- process it the Cisco way */
1723 if (rtp->lastevent <= seqno || (rtp->lastevent >= 65530 && seqno <= 6)) {
1724 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1725 rtp->lastevent = seqno;
1727 } else if (rtpPT.code == AST_RTP_CN) {
1729 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1731 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1733 return f ? f : &ast_null_frame;
1735 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1736 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;
1739 rtp->lastrxts = timestamp;
1741 rtp->rxseqno = seqno;
1743 /* Record received timestamp as last received now */
1744 rtp->lastrxts = timestamp;
1746 if (rtp->dtmfcount) {
1747 rtp->dtmfcount -= (timestamp - rtp->lastrxts);
1749 if (rtp->dtmfcount < 0) {
1753 if (rtp->resp && !rtp->dtmfcount) {
1754 struct ast_frame *f;
1755 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
1762 rtp->f.datalen = res - hdrlen;
1763 rtp->f.data.ptr = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1764 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1765 rtp->f.seqno = seqno;
1767 if (rtp->f.subclass == AST_FORMAT_T140 && (int)seqno - (prev_seqno+1) > 0 && (int)seqno - (prev_seqno+1) < 10) {
1768 unsigned char *data = rtp->f.data.ptr;
1770 memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
1777 if (rtp->f.subclass == AST_FORMAT_T140RED) {
1778 unsigned char *data = rtp->f.data.ptr;
1779 unsigned char *header_end;
1780 int num_generations;
1783 int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
1786 rtp->f.subclass = AST_FORMAT_T140;
1787 header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
1790 header_length = header_end - data;
1791 num_generations = header_length / 4;
1792 length = header_length;
1795 for (x = 0; x < num_generations; x++)
1796 length += data[x * 4 + 3];
1798 if (!(rtp->f.datalen - length))
1799 return &ast_null_frame;
1801 rtp->f.data.ptr += length;
1802 rtp->f.datalen -= length;
1803 } else if (diff > num_generations && diff < 10) {
1805 rtp->f.data.ptr += length;
1806 rtp->f.datalen -= length;
1808 data = rtp->f.data.ptr;
1813 for ( x = 0; x < num_generations - diff; x++)
1814 length += data[x * 4 + 3];
1816 rtp->f.data.ptr += length;
1817 rtp->f.datalen -= length;
1821 if (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) {
1822 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1823 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1824 ast_frame_byteswap_be(&rtp->f);
1825 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1826 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1827 ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
1828 rtp->f.ts = timestamp / 8;
1829 rtp->f.len = rtp->f.samples / ((ast_format_rate(rtp->f.subclass) / 1000));
1830 } else if (rtp->f.subclass & AST_FORMAT_VIDEO_MASK) {
1831 /* Video -- samples is # of samples vs. 90000 */
1832 if (!rtp->lastividtimestamp)
1833 rtp->lastividtimestamp = timestamp;
1834 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1835 rtp->lastividtimestamp = timestamp;
1836 rtp->f.delivery.tv_sec = 0;
1837 rtp->f.delivery.tv_usec = 0;
1838 /* Pass the RTP marker bit as bit 0 in the subclass field.
1839 * This is ok because subclass is actually a bitmask, and
1840 * the low bits represent audio formats, that are not
1841 * involved here since we deal with video.
1844 rtp->f.subclass |= 0x1;
1846 /* TEXT -- samples is # of samples vs. 1000 */
1847 if (!rtp->lastitexttimestamp)
1848 rtp->lastitexttimestamp = timestamp;
1849 rtp->f.samples = timestamp - rtp->lastitexttimestamp;
1850 rtp->lastitexttimestamp = timestamp;
1851 rtp->f.delivery.tv_sec = 0;
1852 rtp->f.delivery.tv_usec = 0;
1858 /* The following array defines the MIME Media type (and subtype) for each
1859 of our codecs, or RTP-specific data type. */
1860 static const struct mimeType {
1861 struct rtpPayloadType payloadType;
1864 unsigned int sample_rate;
1866 {{1, AST_FORMAT_G723_1}, "audio", "G723", 8000},
1867 {{1, AST_FORMAT_GSM}, "audio", "GSM", 8000},
1868 {{1, AST_FORMAT_ULAW}, "audio", "PCMU", 8000},
1869 {{1, AST_FORMAT_ULAW}, "audio", "G711U", 8000},
1870 {{1, AST_FORMAT_ALAW}, "audio", "PCMA", 8000},
1871 {{1, AST_FORMAT_ALAW}, "audio", "G711A", 8000},
1872 {{1, AST_FORMAT_G726}, "audio", "G726-32", 8000},
1873 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4", 8000},
1874 {{1, AST_FORMAT_SLINEAR}, "audio", "L16", 8000},
1875 {{1, AST_FORMAT_LPC10}, "audio", "LPC", 8000},
1876 {{1, AST_FORMAT_G729A}, "audio", "G729", 8000},
1877 {{1, AST_FORMAT_G729A}, "audio", "G729A", 8000},
1878 {{1, AST_FORMAT_G729A}, "audio", "G.729", 8000},
1879 {{1, AST_FORMAT_SPEEX}, "audio", "speex", 8000},
1880 {{1, AST_FORMAT_ILBC}, "audio", "iLBC", 8000},
1881 /* this is the sample rate listed in the RTP profile for the G.722
1882 codec, *NOT* the actual sample rate of the media stream
1884 {{1, AST_FORMAT_G722}, "audio", "G722", 8000},
1885 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32", 8000},
1886 {{0, AST_RTP_DTMF}, "audio", "telephone-event", 8000},
1887 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event", 8000},
1888 {{0, AST_RTP_CN}, "audio", "CN", 8000},
1889 {{1, AST_FORMAT_JPEG}, "video", "JPEG", 90000},
1890 {{1, AST_FORMAT_PNG}, "video", "PNG", 90000},
1891 {{1, AST_FORMAT_H261}, "video", "H261", 90000},
1892 {{1, AST_FORMAT_H263}, "video", "H263", 90000},
1893 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998", 90000},
1894 {{1, AST_FORMAT_H264}, "video", "H264", 90000},
1895 {{1, AST_FORMAT_MP4_VIDEO}, "video", "MP4V-ES", 90000},
1896 {{1, AST_FORMAT_T140RED}, "text", "RED", 1000},
1897 {{1, AST_FORMAT_T140}, "text", "T140", 1000},
1898 {{1, AST_FORMAT_SIREN7}, "audio", "G7221", 16000},
1899 {{1, AST_FORMAT_SIREN14}, "audio", "G7221", 32000},
1903 * \brief Mapping between Asterisk codecs and rtp payload types
1905 * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1906 * also, our own choices for dynamic payload types. This is our master
1907 * table for transmission
1909 * See http://www.iana.org/assignments/rtp-parameters for a list of
1912 static const struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1913 [0] = {1, AST_FORMAT_ULAW},
1914 #ifdef USE_DEPRECATED_G726
1915 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1917 [3] = {1, AST_FORMAT_GSM},
1918 [4] = {1, AST_FORMAT_G723_1},
1919 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1920 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1921 [7] = {1, AST_FORMAT_LPC10},
1922 [8] = {1, AST_FORMAT_ALAW},
1923 [9] = {1, AST_FORMAT_G722},
1924 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1925 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1926 [13] = {0, AST_RTP_CN},
1927 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1928 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1929 [18] = {1, AST_FORMAT_G729A},
1930 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1931 [26] = {1, AST_FORMAT_JPEG},
1932 [31] = {1, AST_FORMAT_H261},
1933 [34] = {1, AST_FORMAT_H263},
1934 [97] = {1, AST_FORMAT_ILBC},
1935 [98] = {1, AST_FORMAT_H263_PLUS},
1936 [99] = {1, AST_FORMAT_H264},
1937 [101] = {0, AST_RTP_DTMF},
1938 [102] = {1, AST_FORMAT_SIREN7},
1939 [103] = {1, AST_FORMAT_H263_PLUS},
1940 [104] = {1, AST_FORMAT_MP4_VIDEO},
1941 [105] = {1, AST_FORMAT_T140RED}, /* Real time text chat (with redundancy encoding) */
1942 [106] = {1, AST_FORMAT_T140}, /* Real time text chat */
1943 [110] = {1, AST_FORMAT_SPEEX},
1944 [111] = {1, AST_FORMAT_G726},
1945 [112] = {1, AST_FORMAT_G726_AAL2},
1946 [115] = {1, AST_FORMAT_SIREN14},
1947 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1950 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1957 rtp_bridge_lock(rtp);
1959 for (i = 0; i < MAX_RTP_PT; ++i) {
1960 rtp->current_RTP_PT[i].isAstFormat = 0;
1961 rtp->current_RTP_PT[i].code = 0;
1964 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1965 rtp->rtp_lookup_code_cache_code = 0;
1966 rtp->rtp_lookup_code_cache_result = 0;
1968 rtp_bridge_unlock(rtp);
1971 void ast_rtp_pt_default(struct ast_rtp* rtp)
1975 rtp_bridge_lock(rtp);
1977 /* Initialize to default payload types */
1978 for (i = 0; i < MAX_RTP_PT; ++i) {
1979 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1980 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1983 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1984 rtp->rtp_lookup_code_cache_code = 0;
1985 rtp->rtp_lookup_code_cache_result = 0;
1987 rtp_bridge_unlock(rtp);
1990 void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
1994 rtp_bridge_lock(dest);
1995 rtp_bridge_lock(src);
1997 for (i = 0; i < MAX_RTP_PT; ++i) {
1998 dest->current_RTP_PT[i].isAstFormat =
1999 src->current_RTP_PT[i].isAstFormat;
2000 dest->current_RTP_PT[i].code =
2001 src->current_RTP_PT[i].code;
2003 dest->rtp_lookup_code_cache_isAstFormat = 0;
2004 dest->rtp_lookup_code_cache_code = 0;
2005 dest->rtp_lookup_code_cache_result = 0;
2007 rtp_bridge_unlock(src);
2008 rtp_bridge_unlock(dest);
2011 /*! \brief Get channel driver interface structure */
2012 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
2014 struct ast_rtp_protocol *cur = NULL;
2016 AST_RWLIST_RDLOCK(&protos);
2017 AST_RWLIST_TRAVERSE(&protos, cur, list) {
2018 if (cur->type == chan->tech->type)
2021 AST_RWLIST_UNLOCK(&protos);
2026 int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
2028 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
2029 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
2030 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
2031 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
2032 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;
2033 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;
2034 int srccodec, destcodec, nat_active = 0;
2037 ast_channel_lock(c0);
2039 while (ast_channel_trylock(c1)) {
2040 ast_channel_unlock(c0);
2042 ast_channel_lock(c0);
2046 /* Find channel driver interfaces */
2047 destpr = get_proto(c0);
2049 srcpr = get_proto(c1);
2051 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c0->name);
2052 ast_channel_unlock(c0);
2054 ast_channel_unlock(c1);
2058 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
2059 ast_channel_unlock(c0);
2061 ast_channel_unlock(c1);
2065 /* Get audio, video and text interface (if native bridge is possible) */
2066 audio_dest_res = destpr->get_rtp_info(c0, &destp);
2067 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
2068 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(c0, &tdestp) : AST_RTP_GET_FAILED;
2070 audio_src_res = srcpr->get_rtp_info(c1, &srcp);
2071 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
2072 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(c1, &tsrcp) : AST_RTP_GET_FAILED;
2075 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
2076 if (audio_dest_res != AST_RTP_TRY_NATIVE || (video_dest_res != AST_RTP_GET_FAILED && video_dest_res != AST_RTP_TRY_NATIVE)) {
2077 /* Somebody doesn't want to play... */
2078 ast_channel_unlock(c0);
2080 ast_channel_unlock(c1);
2083 if (audio_src_res == AST_RTP_TRY_NATIVE && (video_src_res == AST_RTP_GET_FAILED || video_src_res == AST_RTP_TRY_NATIVE) && srcpr->get_codec)
2084 srccodec = srcpr->get_codec(c1);
2087 if (audio_dest_res == AST_RTP_TRY_NATIVE && (video_dest_res == AST_RTP_GET_FAILED || video_dest_res == AST_RTP_TRY_NATIVE) && destpr->get_codec)
2088 destcodec = destpr->get_codec(c0);
2091 /* Ensure we have at least one matching codec */
2092 if (srcp && !(srccodec & destcodec)) {
2093 ast_channel_unlock(c0);
2094 ast_channel_unlock(c1);
2097 /* Consider empty media as non-existent */
2098 if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
2100 if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
2102 /* Bridge media early */
2103 if (destpr->set_rtp_peer(c0, srcp, vsrcp, tsrcp, srccodec, nat_active))
2104 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
2105 ast_channel_unlock(c0);
2107 ast_channel_unlock(c1);
2108 ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
2112 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
2114 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
2115 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
2116 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
2117 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
2118 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;
2119 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;
2120 int srccodec, destcodec;
2123 ast_channel_lock(dest);
2124 while (ast_channel_trylock(src)) {
2125 ast_channel_unlock(dest);
2127 ast_channel_lock(dest);
2130 /* Find channel driver interfaces */
2131 if (!(destpr = get_proto(dest))) {
2132 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", dest->name);
2133 ast_channel_unlock(dest);
2134 ast_channel_unlock(src);
2137 if (!(srcpr = get_proto(src))) {
2138 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", src->name);
2139 ast_channel_unlock(dest);
2140 ast_channel_unlock(src);
2144 /* Get audio and video interface (if native bridge is possible) */
2145 audio_dest_res = destpr->get_rtp_info(dest, &destp);
2146 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
2147 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(dest, &tdestp) : AST_RTP_GET_FAILED;
2148 audio_src_res = srcpr->get_rtp_info(src, &srcp);
2149 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
2150 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(src, &tsrcp) : AST_RTP_GET_FAILED;
2152 /* Ensure we have at least one matching codec */
2153 if (srcpr->get_codec)
2154 srccodec = srcpr->get_codec(src);
2157 if (destpr->get_codec)
2158 destcodec = destpr->get_codec(dest);
2162 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
2163 if (audio_dest_res != AST_RTP_TRY_NATIVE || (video_dest_res != AST_RTP_GET_FAILED && video_dest_res != AST_RTP_TRY_NATIVE) || audio_src_res != AST_RTP_TRY_NATIVE || (video_src_res != AST_RTP_GET_FAILED && video_src_res != AST_RTP_TRY_NATIVE) || !(srccodec & destcodec)) {
2164 /* Somebody doesn't want to play... */
2165 ast_channel_unlock(dest);
2166 ast_channel_unlock(src);
2169 ast_rtp_pt_copy(destp, srcp);
2170 if (vdestp && vsrcp)
2171 ast_rtp_pt_copy(vdestp, vsrcp);
2172 if (tdestp && tsrcp)
2173 ast_rtp_pt_copy(tdestp, tsrcp);
2176 if (destpr->set_rtp_peer(dest, srcp, vsrcp, tsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
2177 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
2179 ast_channel_unlock(dest);
2180 ast_channel_unlock(src);
2181 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
2185 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
2186 * By default, use the well-known value for this type (although it may
2187 * still be set to a different value by a subsequent "a=rtpmap:" line)
2189 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
2191 if (pt < 0 || pt > MAX_RTP_PT || static_RTP_PT[pt].code == 0)
2192 return; /* bogus payload type */
2194 rtp_bridge_lock(rtp);
2195 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
2196 rtp_bridge_unlock(rtp);
2199 /*! \brief remove setting from payload type list if the rtpmap header indicates
2200 an unknown media type */
2201 void ast_rtp_unset_m_type(struct ast_rtp* rtp, int pt)
2203 if (pt < 0 || pt > MAX_RTP_PT)
2204 return; /* bogus payload type */
2206 rtp_bridge_lock(rtp);
2207 rtp->current_RTP_PT[pt].isAstFormat = 0;
2208 rtp->current_RTP_PT[pt].code = 0;
2209 rtp_bridge_unlock(rtp);
2212 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
2213 * an SDP "a=rtpmap:" line.
2214 * \return 0 if the MIME type was found and set, -1 if it wasn't found
2216 int ast_rtp_set_rtpmap_type_rate(struct ast_rtp *rtp, int pt,
2217 char *mimeType, char *mimeSubtype,
2218 enum ast_rtp_options options,
2219 unsigned int sample_rate)
2224 if (pt < 0 || pt > MAX_RTP_PT)
2225 return -1; /* bogus payload type */
2227 rtp_bridge_lock(rtp);
2229 for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
2230 const struct mimeType *t = &mimeTypes[i];
2232 if (strcasecmp(mimeSubtype, t->subtype)) {
2236 if (strcasecmp(mimeType, t->type)) {
2240 /* if both sample rates have been supplied, and they don't match,
2241 then this not a match; if one has not been supplied, then the
2242 rates are not compared */
2243 if (sample_rate && t->sample_rate &&
2244 (sample_rate != t->sample_rate)) {
2249 rtp->current_RTP_PT[pt] = t->payloadType;
2251 if ((t->payloadType.code == AST_FORMAT_G726) &&
2252 t->payloadType.isAstFormat &&
2253 (options & AST_RTP_OPT_G726_NONSTANDARD)) {
2254 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
2260 rtp_bridge_unlock(rtp);
2262 return (found ? 0 : -2);
2265 int ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
2266 char *mimeType, char *mimeSubtype,
2267 enum ast_rtp_options options)
2269 return ast_rtp_set_rtpmap_type_rate(rtp, pt, mimeType, mimeSubtype, options, 0);
2272 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
2273 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
2274 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
2275 int* astFormats, int* nonAstFormats)
2279 rtp_bridge_lock(rtp);
2281 *astFormats = *nonAstFormats = 0;
2282 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2283 if (rtp->current_RTP_PT[pt].isAstFormat) {
2284 *astFormats |= rtp->current_RTP_PT[pt].code;
2286 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
2290 rtp_bridge_unlock(rtp);
2293 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
2295 struct rtpPayloadType result;
2297 result.isAstFormat = result.code = 0;
2299 if (pt < 0 || pt > MAX_RTP_PT)
2300 return result; /* bogus payload type */
2302 /* Start with negotiated codecs */
2303 rtp_bridge_lock(rtp);
2304 result = rtp->current_RTP_PT[pt];
2305 rtp_bridge_unlock(rtp);
2307 /* If it doesn't exist, check our static RTP type list, just in case */
2309 result = static_RTP_PT[pt];
2314 /*! \brief Looks up an RTP code out of our *static* outbound list */
2315 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
2319 rtp_bridge_lock(rtp);
2321 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
2322 code == rtp->rtp_lookup_code_cache_code) {
2323 /* Use our cached mapping, to avoid the overhead of the loop below */
2324 pt = rtp->rtp_lookup_code_cache_result;
2325 rtp_bridge_unlock(rtp);
2329 /* Check the dynamic list first */
2330 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2331 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
2332 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2333 rtp->rtp_lookup_code_cache_code = code;
2334 rtp->rtp_lookup_code_cache_result = pt;
2335 rtp_bridge_unlock(rtp);
2340 /* Then the static list */
2341 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2342 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
2343 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2344 rtp->rtp_lookup_code_cache_code = code;
2345 rtp->rtp_lookup_code_cache_result = pt;
2346 rtp_bridge_unlock(rtp);
2351 rtp_bridge_unlock(rtp);
2356 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
2357 enum ast_rtp_options options)
2361 for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
2362 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
2364 (code == AST_FORMAT_G726_AAL2) &&
2365 (options & AST_RTP_OPT_G726_NONSTANDARD))
2368 return mimeTypes[i].subtype;
2375 unsigned int ast_rtp_lookup_sample_rate(int isAstFormat, int code)
2379 for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
2380 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
2381 return mimeTypes[i].sample_rate;
2388 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
2389 const int isAstFormat, enum ast_rtp_options options)
2399 snprintf(end, size, "0x%x (", capability);
2406 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
2407 if (capability & format) {
2408 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
2410 snprintf(end, size, "%s|", name);
2418 ast_copy_string(start, "nothing)", size);
2425 /*! \brief Open RTP or RTCP socket for a session.
2426 * Print a message on failure.
2428 static int rtp_socket(const char *type)
2430 int s = socket(AF_INET, SOCK_DGRAM, 0);
2434 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
2436 long flags = fcntl(s, F_GETFL);
2437 fcntl(s, F_SETFL, flags | O_NONBLOCK);
2440 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
2447 * \brief Initialize a new RTCP session.
2449 * \returns The newly initialized RTCP session.
2451 static struct ast_rtcp *ast_rtcp_new(void)
2453 struct ast_rtcp *rtcp;
2455 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
2457 rtcp->s = rtp_socket("RTCP");
2458 rtcp->us.sin_family = AF_INET;
2459 rtcp->them.sin_family = AF_INET;
2471 * \brief Initialize a new RTP structure.
2474 void ast_rtp_new_init(struct ast_rtp *rtp)
2477 ast_mutex_init(&rtp->bridge_lock);
2480 rtp->them.sin_family = AF_INET;
2481 rtp->us.sin_family = AF_INET;
2482 rtp->ssrc = ast_random();
2483 rtp->seqno = ast_random() & 0xffff;
2484 ast_set_flag(rtp, FLAG_HAS_DTMF);
2485 rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
2488 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
2490 struct ast_rtp *rtp;
2494 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
2497 ast_rtp_new_init(rtp);
2499 rtp->s = rtp_socket("RTP");
2502 if (sched && rtcpenable) {
2504 rtp->rtcp = ast_rtcp_new();
2508 * Try to bind the RTP port, x, and possibly the RTCP port, x+1 as well.
2509 * Start from a random (even, by RTP spec) port number, and
2510 * iterate until success or no ports are available.
2511 * Note that the requirement of RTP port being even, or RTCP being the
2512 * next one, cannot be enforced in presence of a NAT box because the
2513 * mapping is not under our control.
2515 x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
2516 x = x & ~1; /* make it an even number */
2517 startplace = x; /* remember the starting point */
2518 /* this is constant across the loop */
2519 rtp->us.sin_addr = addr;
2521 rtp->rtcp->us.sin_addr = addr;
2523 rtp->us.sin_port = htons(x);
2524 if (!bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) {
2525 /* bind succeeded, if no rtcp then we are done */
2528 /* have rtcp, try to bind it */
2529 rtp->rtcp->us.sin_port = htons(x + 1);
2530 if (!bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us)))
2531 break; /* success again, we are really done */
2533 * RTCP bind failed, so close and recreate the
2534 * already bound RTP socket for the next round.
2537 rtp->s = rtp_socket("RTP");
2542 * If we get here, there was an error in one of the bind()
2543 * calls, so make sure it is nothing unexpected.
2545 if (errno != EADDRINUSE) {
2546 /* We got an error that wasn't expected, abort! */
2547 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
2551 * One of the ports is in use. For the next iteration,
2552 * increment by two and handle wraparound.
2553 * If we reach the starting point, then declare failure.
2557 x = (rtpstart + 1) & ~1;
2558 if (x == startplace) {
2559 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
2566 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
2567 ast_set_flag(rtp, FLAG_CALLBACK_MODE);
2569 ast_rtp_pt_default(rtp);
2576 close(rtp->rtcp->s);
2577 ast_free(rtp->rtcp);
2583 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
2587 memset(&ia, 0, sizeof(ia));
2588 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
2591 int ast_rtp_setqos(struct ast_rtp *rtp, int type_of_service, int class_of_service, char *desc)
2593 return ast_netsock_set_qos(rtp->s, type_of_service, class_of_service, desc);
2596 void ast_rtp_new_source(struct ast_rtp *rtp)
2599 rtp->set_marker_bit = 1;
2604 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2606 rtp->them.sin_port = them->sin_port;
2607 rtp->them.sin_addr = them->sin_addr;
2609 int h = ntohs(them->sin_port);
2610 rtp->rtcp->them.sin_port = htons(h + 1);
2611 rtp->rtcp->them.sin_addr = them->sin_addr;
2614 /* If strict RTP protection is enabled switch back to the learn state so we don't drop packets from above */
2616 rtp->strict_rtp_state = STRICT_RTP_LEARN;
2619 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2621 if ((them->sin_family != AF_INET) ||
2622 (them->sin_port != rtp->them.sin_port) ||
2623 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
2624 them->sin_family = AF_INET;
2625 them->sin_port = rtp->them.sin_port;
2626 them->sin_addr = rtp->them.sin_addr;
2632 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
2637 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
2639 struct ast_rtp *bridged = NULL;
2641 rtp_bridge_lock(rtp);
2642 bridged = rtp->bridged;
2643 rtp_bridge_unlock(rtp);
2648 void ast_rtp_stop(struct ast_rtp *rtp)
2651 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
2654 AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
2659 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
2660 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
2662 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
2663 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
2666 ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
2669 void ast_rtp_reset(struct ast_rtp *rtp)
2671 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
2672 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
2673 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
2675 rtp->lastdigitts = 0;
2677 rtp->lastividtimestamp = 0;
2678 rtp->lastovidtimestamp = 0;
2679 rtp->lastitexttimestamp = 0;
2680 rtp->lastotexttimestamp = 0;
2681 rtp->lasteventseqn = 0;
2683 rtp->lasttxformat = 0;
2684 rtp->lastrxformat = 0;
2686 rtp->dtmfsamples = 0;
2691 /*! Get QoS values from RTP and RTCP data (used in "sip show channelstats") */
2692 unsigned int ast_rtp_get_qosvalue(struct ast_rtp *rtp, enum ast_rtp_qos_vars value)
2695 if (option_debug > 1)
2696 ast_log(LOG_DEBUG, "NO RTP Structure? Kidding me? \n");
2699 if (option_debug > 1 && rtp->rtcp == NULL) {
2700 ast_log(LOG_DEBUG, "NO RTCP structure. Maybe in RTP p2p bridging mode? \n");
2704 case AST_RTP_TXCOUNT:
2705 return (unsigned int) rtp->txcount;
2706 case AST_RTP_RXCOUNT:
2707 return (unsigned int) rtp->rxcount;
2708 case AST_RTP_TXJITTER:
2709 return (unsigned int) (rtp->rxjitter * 100.0);
2710 case AST_RTP_RXJITTER:
2711 return (unsigned int) (rtp->rtcp ? (rtp->rtcp->reported_jitter / (unsigned int) 65536.0) : 0);
2712 case AST_RTP_RXPLOSS:
2713 return rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0;
2714 case AST_RTP_TXPLOSS:
2715 return rtp->rtcp ? rtp->rtcp->reported_lost : 0;
2717 return (unsigned int) (rtp->rtcp ? (rtp->rtcp->rtt * 100) : 0);
2719 return 0; /* To make the compiler happy */
2722 static double __ast_rtp_get_qos(struct ast_rtp *rtp, const char *qos, int *found)
2726 if (!strcasecmp(qos, "remote_maxjitter"))
2727 return rtp->rtcp->reported_maxjitter * 1000.0;
2728 if (!strcasecmp(qos, "remote_minjitter"))
2729 return rtp->rtcp->reported_minjitter * 1000.0;
2730 if (!strcasecmp(qos, "remote_normdevjitter"))
2731 return rtp->rtcp->reported_normdev_jitter * 1000.0;
2732 if (!strcasecmp(qos, "remote_stdevjitter"))
2733 return sqrt(rtp->rtcp->reported_stdev_jitter) * 1000.0;
2735 if (!strcasecmp(qos, "local_maxjitter"))
2736 return rtp->rtcp->maxrxjitter * 1000.0;
2737 if (!strcasecmp(qos, "local_minjitter"))
2738 return rtp->rtcp->minrxjitter * 1000.0;
2739 if (!strcasecmp(qos, "local_normdevjitter"))
2740 return rtp->rtcp->normdev_rxjitter * 1000.0;
2741 if (!strcasecmp(qos, "local_stdevjitter"))
2742 return sqrt(rtp->rtcp->stdev_rxjitter) * 1000.0;
2744 if (!strcasecmp(qos, "maxrtt"))
2745 return rtp->rtcp->maxrtt * 1000.0;
2746 if (!strcasecmp(qos, "minrtt"))
2747 return rtp->rtcp->minrtt * 1000.0;
2748 if (!strcasecmp(qos, "normdevrtt"))
2749 return rtp->rtcp->normdevrtt * 1000.0;
2750 if (!strcasecmp(qos, "stdevrtt"))
2751 return sqrt(rtp->rtcp->stdevrtt) * 1000.0;
2758 int ast_rtp_get_qos(struct ast_rtp *rtp, const char *qos, char *buf, unsigned int buflen)
2763 value = __ast_rtp_get_qos(rtp, qos, &found);
2768 snprintf(buf, buflen, "%.0lf", value);
2773 void ast_rtp_set_vars(struct ast_channel *chan, struct ast_rtp *rtp) {
2775 char *audioqos_jitter;
2776 char *audioqos_loss;
2778 struct ast_channel *bridge;
2783 bridge = ast_bridged_channel(chan);
2785 audioqos = ast_rtp_get_quality(rtp, NULL, RTPQOS_SUMMARY);
2786 audioqos_jitter = ast_rtp_get_quality(rtp, NULL, RTPQOS_JITTER);
2787 audioqos_loss = ast_rtp_get_quality(rtp, NULL, RTPQOS_LOSS);
2788 audioqos_rtt = ast_rtp_get_quality(rtp, NULL, RTPQOS_RTT);
2790 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOS", audioqos);
2791 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSJITTER", audioqos_jitter);
2792 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSLOSS", audioqos_loss);
2793 pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSRTT", audioqos_rtt);
2798 pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSBRIDGED", audioqos);
2799 pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSJITTERBRIDGED", audioqos_jitter);
2800 pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSLOSSBRIDGED", audioqos_loss);
2801 pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSRTTBRIDGED", audioqos_rtt);
2804 static char *__ast_rtp_get_quality_jitter(struct ast_rtp *rtp)
2808 *themssrc their ssrc
2810 *rxjitter our calculated jitter(rx)
2811 *rxcount no. received packets
2812 *txjitter reported jitter of the other end
2813 *txcount transmitted packets
2814 *rlp remote lost packets
2815 *rtt round trip time
2817 #define RTCP_JITTER_FORMAT1 \
2821 "stdevrxjitter=%f;" \
2822 "reported_minjitter=%f;" \
2823 "reported_maxjitter=%f;" \
2824 "reported_avgjitter=%f;" \
2825 "reported_stdevjitter=%f;"
2827 #define RTCP_JITTER_FORMAT2 \
2830 if (rtp->rtcp && rtp->rtcp->rtcp_info) {
2831 snprintf(rtp->rtcp->quality_jitter, sizeof(rtp->rtcp->quality_jitter), RTCP_JITTER_FORMAT1,
2832 rtp->rtcp->minrxjitter,
2833 rtp->rtcp->maxrxjitter,
2834 rtp->rtcp->normdev_rxjitter,
2835 sqrt(rtp->rtcp->stdev_rxjitter),
2836 rtp->rtcp->reported_minjitter,
2837 rtp->rtcp->reported_maxjitter,
2838 rtp->rtcp->reported_normdev_jitter,
2839 sqrt(rtp->rtcp->reported_stdev_jitter)
2842 snprintf(rtp->rtcp->quality_jitter, sizeof(rtp->rtcp->quality_jitter), RTCP_JITTER_FORMAT2,
2847 return rtp->rtcp->quality_jitter;
2849 #undef RTCP_JITTER_FORMAT1
2850 #undef RTCP_JITTER_FORMAT2
2853 static char *__ast_rtp_get_quality_loss(struct ast_rtp *rtp)
2856 unsigned int extended;
2857 unsigned int expected;
2860 #define RTCP_LOSS_FORMAT1 \
2865 "reported_minlost=%f;" \
2866 "reported_maxlost=%f;" \
2867 "reported_avglost=%f;" \
2868 "reported_stdevlost=%f;"
2870 #define RTCP_LOSS_FORMAT2 \
2874 if (rtp->rtcp && rtp->rtcp->rtcp_info && rtp->rtcp->maxrxlost > 0) {
2875 snprintf(rtp->rtcp->quality_loss, sizeof(rtp->rtcp->quality_loss), RTCP_LOSS_FORMAT1,
2876 rtp->rtcp->minrxlost,
2877 rtp->rtcp->maxrxlost,
2878 rtp->rtcp->normdev_rxlost,
2879 sqrt(rtp->rtcp->stdev_rxlost),
2880 rtp->rtcp->reported_minlost,
2881 rtp->rtcp->reported_maxlost,
2882 rtp->rtcp->reported_normdev_lost,
2883 sqrt(rtp->rtcp->reported_stdev_lost)
2886 extended = rtp->cycles + rtp->lastrxseqno;
2887 expected = extended - rtp->seedrxseqno + 1;
2888 if (rtp->rxcount > expected)
2889 expected += rtp->rxcount - expected;
2890 lost = expected - rtp->rxcount;
2892 if (!expected || lost <= 0)
2895 fraction = (lost << 8) / expected;
2897 snprintf(rtp->rtcp->quality_loss, sizeof(rtp->rtcp->quality_loss), RTCP_LOSS_FORMAT2,
2903 return rtp->rtcp->quality_loss;
2905 #undef RTCP_LOSS_FORMAT1
2906 #undef RTCP_LOSS_FORMAT2
2909 static char *__ast_rtp_get_quality_rtt(struct ast_rtp *rtp)
2911 if (rtp->rtcp && rtp->rtcp->rtcp_info) {
2912 snprintf(rtp->rtcp->quality_rtt, sizeof(rtp->rtcp->quality_rtt), "minrtt=%f;maxrtt=%f;avgrtt=%f;stdevrtt=%f;",
2915 rtp->rtcp->normdevrtt,
2916 sqrt(rtp->rtcp->stdevrtt)
2919 snprintf(rtp->rtcp->quality_rtt, sizeof(rtp->rtcp->quality_rtt), "Not available");
2922 return rtp->rtcp->quality_rtt;
2925 static char *__ast_rtp_get_quality(struct ast_rtp *rtp)
2929 *themssrc their ssrc
2931 *rxjitter our calculated jitter(rx)
2932 *rxcount no. received packets
2933 *txjitter reported jitter of the other end
2934 *txcount transmitted packets
2935 *rlp remote lost packets
2936 *rtt round trip time
2939 if (rtp->rtcp && rtp->rtcp->rtcp_info) {
2940 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality),
2941 "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
2944 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2947 (double)rtp->rtcp->reported_jitter / 65536.0,
2949 rtp->rtcp->reported_lost,
2953 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality), "ssrc=%u;themssrc=%u;rxjitter=%f;rxcount=%u;txcount=%u;",
2962 return rtp->rtcp->quality;
2965 char *ast_rtp_get_quality(struct ast_rtp *rtp, struct ast_rtp_quality *qual, enum ast_rtp_quality_type qtype)
2968 qual->local_ssrc = rtp->ssrc;
2969 qual->local_jitter = rtp->rxjitter;
2970 qual->local_count = rtp->rxcount;
2971 qual->remote_ssrc = rtp->themssrc;
2972 qual->remote_count = rtp->txcount;
2975 qual->local_lostpackets = rtp->rtcp->expected_prior - rtp->rtcp->received_prior;
2976 qual->remote_lostpackets = rtp->rtcp->reported_lost;
2977 qual->remote_jitter = rtp->rtcp->reported_jitter / 65536.0;
2978 qual->rtt = rtp->rtcp->rtt;
2983 case RTPQOS_SUMMARY:
2984 return __ast_rtp_get_quality(rtp);
2986 return __ast_rtp_get_quality_jitter(rtp);
2988 return __ast_rtp_get_quality_loss(rtp);
2990 return __ast_rtp_get_quality_rtt(rtp);
2996 void ast_rtp_destroy(struct ast_rtp *rtp)
2998 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
2999 /*Print some info on the call here */
3000 ast_verbose(" RTP-stats\n");
3001 ast_verbose("* Our Receiver:\n");
3002 ast_verbose(" SSRC: %u\n", rtp->themssrc);
3003 ast_verbose(" Received packets: %u\n", rtp->rxcount);
3004 ast_verbose(" Lost packets: %u\n", rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0);
3005 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
3006 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
3007 ast_verbose(" RR-count: %u\n", rtp->rtcp ? rtp->rtcp->rr_count : 0);
3008 ast_verbose("* Our Sender:\n");
3009 ast_verbose(" SSRC: %u\n", rtp->ssrc);
3010 ast_verbose(" Sent packets: %u\n", rtp->txcount);
3011 ast_verbose(" Lost packets: %u\n", rtp->rtcp ? rtp->rtcp->reported_lost : 0);
3012 ast_verbose(" Jitter: %u\n", rtp->rtcp ? (rtp->rtcp->reported_jitter / (unsigned int)65536.0) : 0);
3013 ast_verbose(" SR-count: %u\n", rtp->rtcp ? rtp->rtcp->sr_count : 0);
3014 ast_verbose(" RTT: %f\n", rtp->rtcp ? rtp->rtcp->rtt : 0);
3017 manager_event(EVENT_FLAG_REPORTING, "RTPReceiverStat", "SSRC: %u\r\n"
3018 "ReceivedPackets: %u\r\n"
3019 "LostPackets: %u\r\n"
3025 rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0,
3028 rtp->rtcp ? rtp->rtcp->rr_count : 0);
3029 manager_event(EVENT_FLAG_REPORTING, "RTPSenderStat", "SSRC: %u\r\n"
3030 "SentPackets: %u\r\n"
3031 "LostPackets: %u\r\n"
3037 rtp->rtcp ? rtp->rtcp->reported_lost : 0,
3038 rtp->rtcp ? rtp->rtcp->reported_jitter : 0,
3039 rtp->rtcp ? rtp->rtcp->sr_count : 0,
3040 rtp->rtcp ? rtp->rtcp->rtt : 0);
3042 ast_smoother_free(rtp->smoother);
3044 ast_io_remove(rtp->io, rtp->ioid);
3048 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
3049 close(rtp->rtcp->s);
3050 ast_free(rtp->rtcp);
3054 ast_mutex_destroy(&rtp->bridge_lock);
3059 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
3063 if (ast_tvzero(rtp->txcore)) {
3064 rtp->txcore = ast_tvnow();
3065 /* Round to 20ms for nice, pretty timestamps */
3066 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
3068 /* Use previous txcore if available */
3069 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
3070 ms = ast_tvdiff_ms(t, rtp->txcore);
3073 /* Use what we just got for next time */
3075 return (unsigned int) ms;
3078 /*! \brief Send begin frames for DTMF */
3079 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
3081 unsigned int *rtpheader;
3082 int hdrlen = 12, res = 0, i = 0, payload = 0;
3085 if ((digit <= '9') && (digit >= '0'))
3087 else if (digit == '*')
3089 else if (digit == '#')
3091 else if ((digit >= 'A') && (digit <= 'D'))
3092 digit = digit - 'A' + 12;
3093 else if ((digit >= 'a') && (digit <= 'd'))
3094 digit = digit - 'a' + 12;
3096 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
3100 /* If we have no peer, return immediately */
3101 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
3104 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
3106 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
3107 rtp->send_duration = 160;
3108 rtp->lastdigitts = rtp->lastts + rtp->send_duration;
3110 /* Get a pointer to the header */
3111 rtpheader = (unsigned int *)data;
3112 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
3113 rtpheader[1] = htonl(rtp->lastdigitts);
3114 rtpheader[2] = htonl(rtp->ssrc);
3116 for (i = 0; i < 2; i++) {
3117 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
3118 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
3120 ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
3121 ast_inet_ntoa(rtp->them.sin_addr),
3122 ntohs(rtp->them.sin_port), strerror(errno));
3123 if (rtp_debug_test_addr(&rtp->them))
3124 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3125 ast_inet_ntoa(rtp->them.sin_addr),
3126 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
3127 /* Increment sequence number */
3129 /* Increment duration */
3130 rtp->send_duration += 160;
3131 /* Clear marker bit and set seqno */
3132 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
3135 /* Since we received a begin, we can safely store the digit and disable any compensation */
3136 rtp->sending_digit = 1;
3137 rtp->send_digit = digit;
3138 rtp->send_payload = payload;
3143 /*! \brief Send continuation frame for DTMF */
3144 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
3146 unsigned int *rtpheader;
3147 int hdrlen = 12, res = 0;
3150 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
3153 /* Setup packet to send */
3154 rtpheader = (unsigned int *)data;
3155 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
3156 rtpheader[1] = htonl(rtp->lastdigitts);
3157 rtpheader[2] = htonl(rtp->ssrc);
3158 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
3159 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
3162 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
3164 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
3165 ast_inet_ntoa(rtp->them.sin_addr),
3166 ntohs(rtp->them.sin_port), strerror(errno));
3167 if (rtp_debug_test_addr(&rtp->them))
3168 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3169 ast_inet_ntoa(rtp->them.sin_addr),
3170 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
3172 /* Increment sequence number */
3174 /* Increment duration */
3175 rtp->send_duration += 160;
3180 /*! \brief Send end packets for DTMF */
3181 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
3183 unsigned int *rtpheader;
3184 int hdrlen = 12, res = 0, i = 0;
3187 /* If no address, then bail out */
3188 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
3191 if ((digit <= '9') && (digit >= '0'))
3193 else if (digit == '*')
3195 else if (digit == '#')
3197 else if ((digit >= 'A') && (digit <= 'D'))
3198 digit = digit - 'A' + 12;
3199 else if ((digit >= 'a') && (digit <= 'd'))
3200 digit = digit - 'a' + 12;
3202 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
3206 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
3208 rtpheader = (unsigned int *)data;
3209 rtpheader[1] = htonl(rtp->lastdigitts);
3210 rtpheader[2] = htonl(rtp->ssrc);
3211 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
3213 rtpheader[3] |= htonl((1 << 23));
3215 /* Send 3 termination packets */
3216 for (i = 0; i < 3; i++) {
3217 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
3218 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
3221 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
3222 ast_inet_ntoa(rtp->them.sin_addr),
3223 ntohs(rtp->them.sin_port), strerror(errno));
3224 if (rtp_debug_test_addr(&rtp->them))
3225 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3226 ast_inet_ntoa(rtp->them.sin_addr),
3227 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
3229 rtp->lastts += rtp->send_duration;
3230 rtp->sending_digit = 0;
3231 rtp->send_digit = 0;
3236 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
3237 int ast_rtcp_send_h261fur(void *data)
3239 struct ast_rtp *rtp = data;
3242 rtp->rtcp->sendfur = 1;
3243 res = ast_rtcp_write(data);
3248 /*! \brief Send RTCP sender's report */
3249 static int ast_rtcp_write_sr(const void *data)
3251 struct ast_rtp *rtp = (struct ast_rtp *)data;
3255 unsigned int now_lsw;
3256 unsigned int now_msw;
3257 unsigned int *rtcpheader;
3259 unsigned int extended;
3260 unsigned int expected;
3261 unsigned int expected_interval;
3262 unsigned int received_interval;
3265 struct timeval dlsr;
3268 /* Commented condition is always not NULL if rtp->rtcp is not NULL */
3269 if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
3272 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
3273 ast_verbose("RTCP SR transmission error, rtcp halted\n");
3274 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
3278 gettimeofday(&now, NULL);
3279 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
3280 rtcpheader = (unsigned int *)bdata;
3281 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
3282 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
3283 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
3284 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
3285 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
3286 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
3289 extended = rtp->cycles + rtp->lastrxseqno;
3290 expected = extended - rtp->seedrxseqno + 1;
3291 if (rtp->rxcount > expected)
3292 expected += rtp->rxcount - expected;
3293 lost = expected - rtp->rxcount;
3294 expected_interval = expected - rtp->rtcp->expected_prior;
3295 rtp->rtcp->expected_prior = expected;
3296 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
3297 rtp->rtcp->received_prior = rtp->rxcount;
3298 lost_interval = expected_interval - received_interval;
3299 if (expected_interval == 0 || lost_interval <= 0)
3302 fraction = (lost_interval << 8) / expected_interval;
3303 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
3304 rtcpheader[7] = htonl(rtp->themssrc);
3305 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
3306 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
3307 rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
3308 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
3309 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
3312 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
3314 if (rtp->rtcp->sendfur) {
3315 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
3316 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
3318 rtp->rtcp->sendfur = 0;
3321 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
3322 /* it can change mid call, and SDES can't) */
3323 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
3324 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
3325 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
3328 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
3330 ast_log(LOG_ERROR, "RTCP SR transmission error to %s:%d, rtcp halted %s\n",ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port), strerror(errno));
3331 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
3335 /* FIXME Don't need to get a new one */
3336 gettimeofday(&rtp->rtcp->txlsr, NULL);
3337 rtp->rtcp->sr_count++;
3339 rtp->rtcp->lastsrtxcount = rtp->txcount;
3341 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
3342 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
3343 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
3344 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
3345 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
3346 ast_verbose(" Sent packets: %u\n", rtp->txcount);
3347 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
3348 ast_verbose(" Report block:\n");
3349 ast_verbose(" Fraction lost: %u\n", fraction);
3350 ast_verbose(" Cumulative loss: %u\n", lost);
3351 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
3352 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
3353 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
3355 manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To: %s:%d\r\n"
3357 "SentNTP: %u.%010u\r\n"
3359 "SentPackets: %u\r\n"
3360 "SentOctets: %u\r\n"
3362 "FractionLost: %u\r\n"
3363 "CumulativeLoss: %u\r\n"
3364 "IAJitter: %.4f\r\n"
3365 "TheirLastSR: %u\r\n"
3366 "DLSR: %4.4f (sec)\r\n",
3367 ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port),
3369 (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
3376 rtp->rtcp->themrxlsr,
3377 (double)(ntohl(rtcpheader[12])/65536.0));
3381 /*! \brief Send RTCP recipient's report */
3382 static int ast_rtcp_write_rr(const void *data)
3384 struct ast_rtp *rtp = (struct ast_rtp *)data;
3388 unsigned int extended;
3389 unsigned int expected;
3390 unsigned int expected_interval;
3391 unsigned int received_interval;
3394 unsigned int *rtcpheader;
3396 struct timeval dlsr;
3399 double rxlost_current;
3401 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
3404 if (!rtp->rtcp->them.sin_addr.s_addr) {
3405 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
3406 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
3410 extended = rtp->cycles + rtp->lastrxseqno;
3411 expected = extended - rtp->seedrxseqno + 1;
3412 lost = expected - rtp->rxcount;
3413 expected_interval = expected - rtp->rtcp->expected_prior;
3414 rtp->rtcp->expected_prior = expected;
3415 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
3416 rtp->rtcp->received_prior = rtp->rxcount;
3417 lost_interval = expected_interval - received_interval;
3419 if (lost_interval <= 0)
3420 rtp->rtcp->rxlost = 0;
3421 else rtp->rtcp->rxlost = rtp->rtcp->rxlost;
3422 if (rtp->rtcp->rxlost_count == 0)
3423 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
3424 if (lost_interval < rtp->rtcp->minrxlost)
3425 rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
3426 if (lost_interval > rtp->rtcp->maxrxlost)
3427 rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
3429 rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->rxlost_count);
3430 rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->normdev_rxlost, rxlost_current, rtp->rtcp->rxlost_count);
3431 rtp->rtcp->normdev_rxlost = rxlost_current;
3432 rtp->rtcp->rxlost_count++;
3434 if (expected_interval == 0 || lost_interval <= 0)
3437 fraction = (lost_interval << 8) / expected_interval;
3438 gettimeofday(&now, NULL);
3439 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
3440 rtcpheader = (unsigned int *)bdata;
3441 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
3442 rtcpheader[1] = htonl(rtp->ssrc);
3443 rtcpheader[2] = htonl(rtp->themssrc);
3444 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
3445 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
3446 rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
3447 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
3448 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
3450 if (rtp->rtcp->sendfur) {
3451 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
3452 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
3454 rtp->rtcp->sendfur = 0;
3457 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
3458 it can change mid call, and SDES can't) */
3459 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
3460 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
3461 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
3464 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
3467 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
3468 /* Remove the scheduler */
3469 AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
3473 rtp->rtcp->rr_count++;
3475 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
3476 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
3477 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
3478 " IA jitter: %.4f\n"
3479 " Their last SR: %u\n"
3480 " DLSR: %4.4f (sec)\n\n",
3481 ast_inet_ntoa(rtp->rtcp->them.sin_addr),
3482 ntohs(rtp->rtcp->them.sin_port),
3483 rtp->ssrc, rtp->themssrc, fraction, lost,
3485 rtp->rtcp->themrxlsr,
3486 (double)(ntohl(rtcpheader[7])/65536.0));
3492 /*! \brief Write and RTCP packet to the far end
3493 * \note Decide if we are going to send an SR (with Reception Block) or RR
3494 * RR is sent if we have not sent any rtp packets in the previous interval */
3495 static int ast_rtcp_write(const void *data)
3497 struct ast_rtp *rtp = (struct ast_rtp *)data;
3500 if (!rtp || !rtp->rtcp)
3503 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
3504 res = ast_rtcp_write_sr(data);
3506 res = ast_rtcp_write_rr(data);
3511 /*! \brief generate comfort noice (CNG) */
3512 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
3514 unsigned int *rtpheader;
3519 level = 127 - (level & 0x7f);
3520 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
3522 /* If we have no peer, return immediately */
3523 if (!rtp->them.sin_addr.s_addr)
3526 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
3528 /* Get a pointer to the header */
3529 rtpheader = (unsigned int *)data;
3530 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
3531 rtpheader[1] = htonl(rtp->lastts);
3532 rtpheader[2] = htonl(rtp->ssrc);
3534 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
3535 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
3537 ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s:%d: %s\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
3538 if (rtp_debug_test_addr(&rtp->them))
3539 ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
3540 , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
3546 /*! \brief Write RTP packet with audio or video media frames into UDP packet */
3547 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
3549 unsigned char *rtpheader;
3556 if (rtp->sending_digit) {
3560 ms = calc_txstamp(rtp, &f->delivery);
3561 /* Default prediction */
3562 if (f->frametype == AST_FRAME_VOICE) {
3563 pred = rtp->lastts + f->samples;
3565 /* Re-calculate last TS */
3566 rtp->lastts = rtp->lastts + ms * 8;
3567 if (ast_tvzero(f->delivery)) {
3568 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
3569 and if so, go with our prediction */
3570 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
3573 ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
3577 } else if (f->frametype == AST_FRAME_VIDEO) {
3578 mark = f->subclass & 0x1;
3579 pred = rtp->lastovidtimestamp + f->samples;
3580 /* Re-calculate last TS */
3581 rtp->lastts = rtp->lastts + ms * 90;
3582 /* If it's close to our prediction, go for it */
3583 if (ast_tvzero(f->delivery)) {
3584 if (abs(rtp->lastts - pred) < 7200) {
3586 rtp->lastovidtimestamp += f->samples;
3588 ast_debug(3, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, f->samples);
3589 rtp->lastovidtimestamp = rtp->lastts;
3593 pred = rtp->lastotexttimestamp + f->samples;
3594 /* Re-calculate last TS */
3595 rtp->lastts = rtp->lastts + ms * 90;
3596 /* If it's close to our prediction, go for it */
3597 if (ast_tvzero(f->delivery)) {
3598 if (abs(rtp->lastts - pred) < 7200) {
3600 rtp->lastotexttimestamp += f->samples;
3602 ast_debug(3, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, f->samples);
3603 rtp->lastotexttimestamp = rtp->lastts;
3608 /* If we have been explicitly told to set the marker bit do so */
3609 if (rtp->set_marker_bit) {
3611 rtp->set_marker_bit = 0;
3614 /* If the timestamp for non-digit packets has moved beyond the timestamp
3615 for digits, update the digit timestamp.
3617 if (rtp->lastts > rtp->lastdigitts)
3618 rtp->lastdigitts = rtp->lastts;
3620 if (ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO))
3621 rtp->lastts = f->ts * 8;
3623 /* Get a pointer to the header */
3624 rtpheader = (unsigned char *)(f->data.ptr - hdrlen);
3626 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
3627 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
3628 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
3630 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
3631 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
3633 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
3634 ast_debug(1, "RTP Transmission error of packet %d to %s:%d: %s\n", rtp->seqno, ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
3635 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
3636 /* Only give this error message once if we are not RTP debugging */
3637 if (option_debug || rtpdebug)
3638 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(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
3639 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);