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$")
37 #include "asterisk/rtp.h"
38 #include "asterisk/frame.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/acl.h"
41 #include "asterisk/config.h"
42 #include "asterisk/lock.h"
43 #include "asterisk/utils.h"
44 #include "asterisk/netsock.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/manager.h"
47 #include "asterisk/unaligned.h"
49 #define MAX_TIMESTAMP_SKEW 640
51 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
52 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
53 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
54 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
56 #define RTCP_PT_FUR 192
57 #define RTCP_PT_SR 200
58 #define RTCP_PT_RR 201
59 #define RTCP_PT_SDES 202
60 #define RTCP_PT_BYE 203
61 #define RTCP_PT_APP 204
65 #define DEFAULT_DTMF_TIMEOUT 3000 /*!< samples */
67 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
69 static int rtpstart; /*!< First port for RTP sessions (set in rtp.conf) */
70 static int rtpend; /*!< Last port for RTP sessions (set in rtp.conf) */
71 static int rtpdebug; /*!< Are we debugging? */
72 static int rtcpdebug; /*!< Are we debugging RTCP? */
73 static int rtcpstats; /*!< Are we debugging RTCP? */
74 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
75 static int stundebug; /*!< Are we debugging stun? */
76 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
77 static struct sockaddr_in rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
79 static int nochecksums;
82 /* Uncomment this to enable more intense native bridging, but note: this is currently buggy */
83 /* #define P2P_INTENSE */
86 * \brief Structure representing a RTP session.
88 * 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 [...]"
91 /*! \brief The value of each payload format mapping: */
92 struct rtpPayloadType {
93 int isAstFormat; /*!< whether the following code is an AST_FORMAT */
98 /*! \brief RTP session description */
102 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
103 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
104 unsigned int themssrc; /*!< Their SSRC */
107 unsigned int lastrxts;
108 unsigned int lastividtimestamp;
109 unsigned int lastovidtimestamp;
110 unsigned int lastitexttimestamp;
111 unsigned int lastotexttimestamp;
112 unsigned int lasteventseqn;
113 int lastrxseqno; /*!< Last received sequence number */
114 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
115 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
116 unsigned int rxcount; /*!< How many packets have we received? */
117 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
118 unsigned int txcount; /*!< How many packets have we sent? */
119 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
120 unsigned int cycles; /*!< Shifted count of sequence number cycles */
121 double rxjitter; /*!< Interarrival jitter at the moment */
122 double rxtransit; /*!< Relative transit time for previous packet */
126 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
127 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
128 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
130 /* DTMF Reception Variables */
132 unsigned int lastevent;
134 unsigned int dtmfsamples;
135 /* DTMF Transmission Variables */
136 unsigned int lastdigitts;
137 char sending_digit; /*!< boolean - are we sending digits */
138 char send_digit; /*!< digit we are sending */
143 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
144 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
145 struct timeval rxcore;
146 struct timeval txcore;
147 double drxcore; /*!< The double representation of the first received packet */
148 struct timeval lastrx; /*!< timeval when we last received a packet */
149 struct timeval dtmfmute;
150 struct ast_smoother *smoother;
152 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
153 unsigned short rxseqno;
154 struct sched_context *sched;
155 struct io_context *io;
157 ast_rtp_callback callback;
159 ast_mutex_t bridge_lock;
161 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
162 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
163 int rtp_lookup_code_cache_code;
164 int rtp_lookup_code_cache_result;
165 struct ast_rtcp *rtcp;
166 struct ast_codec_pref pref;
167 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
170 /* Forward declarations */
171 static int ast_rtcp_write(const void *data);
172 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
173 static int ast_rtcp_write_sr(const void *data);
174 static int ast_rtcp_write_rr(const void *data);
175 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
176 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
177 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
179 #define FLAG_3389_WARNING (1 << 0)
180 #define FLAG_NAT_ACTIVE (3 << 1)
181 #define FLAG_NAT_INACTIVE (0 << 1)
182 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
183 #define FLAG_HAS_DTMF (1 << 3)
184 #define FLAG_P2P_SENT_MARK (1 << 4)
185 #define FLAG_P2P_NEED_DTMF (1 << 5)
186 #define FLAG_CALLBACK_MODE (1 << 6)
187 #define FLAG_DTMF_COMPENSATE (1 << 7)
188 #define FLAG_HAS_STUN (1 << 8)
191 * \brief Structure defining an RTCP session.
193 * The concept "RTCP session" is not defined in RFC 3550, but since
194 * this structure is analogous to ast_rtp, which tracks a RTP session,
195 * it is logical to think of this as a RTCP session.
197 * RTCP packet is defined on page 9 of RFC 3550.
201 int s; /*!< Socket */
202 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
203 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
204 unsigned int soc; /*!< What they told us */
205 unsigned int spc; /*!< What they told us */
206 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
207 struct timeval rxlsr; /*!< Time when we got their last SR */
208 struct timeval txlsr; /*!< Time when we sent or last SR*/
209 unsigned int expected_prior; /*!< no. packets in previous interval */
210 unsigned int received_prior; /*!< no. packets received in previous interval */
211 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
212 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
213 unsigned int sr_count; /*!< number of SRs we've sent */
214 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
215 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
216 double rtt; /*!< Last reported rtt */
217 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
218 unsigned int reported_lost; /*!< Reported lost packets in their RR */
219 char quality[AST_MAX_USER_FIELD];
228 * \brief STUN support code
230 * This code provides some support for doing STUN transactions.
231 * Eventually it should be moved elsewhere as other protocols
232 * than RTP can benefit from it - e.g. SIP.
233 * STUN is described in RFC3489 and it is based on the exchange
234 * of UDP packets between a client and one or more servers to
235 * determine the externally visible address (and port) of the client
236 * once it has gone through the NAT boxes that connect it to the
238 * The simplest request packet is just the header defined in
239 * struct stun_header, and from the response we may just look at
240 * one attribute, STUN_MAPPED_ADDRESS, that we find in the response.
241 * By doing more transactions with different server addresses we
242 * may determine more about the behaviour of the NAT boxes, of
243 * course - the details are in the RFC.
245 * All STUN packets start with a simple header made of a type,
246 * length (excluding the header) and a 16-byte random transaction id.
247 * Following the header we may have zero or more attributes, each
248 * structured as a type, length and a value (whose format depends
249 * on the type, but often contains addresses).
250 * Of course all fields are in network format.
253 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
256 unsigned short msgtype;
257 unsigned short msglen;
259 unsigned char ies[0];
260 } __attribute__((packed));
265 unsigned char value[0];
266 } __attribute__((packed));
269 * The format normally used for addresses carried by STUN messages.
272 unsigned char unused;
273 unsigned char family;
276 } __attribute__((packed));
278 #define STUN_IGNORE (0)
279 #define STUN_ACCEPT (1)
281 /*! \brief STUN message types
282 * 'BIND' refers to transactions used to determine the externally
283 * visible addresses. 'SEC' refers to transactions used to establish
284 * a session key for subsequent requests.
285 * 'SEC' functionality is not supported here.
288 #define STUN_BINDREQ 0x0001
289 #define STUN_BINDRESP 0x0101
290 #define STUN_BINDERR 0x0111
291 #define STUN_SECREQ 0x0002
292 #define STUN_SECRESP 0x0102
293 #define STUN_SECERR 0x0112
295 /*! \brief Basic attribute types in stun messages.
296 * Messages can also contain custom attributes (codes above 0x7fff)
298 #define STUN_MAPPED_ADDRESS 0x0001
299 #define STUN_RESPONSE_ADDRESS 0x0002
300 #define STUN_CHANGE_REQUEST 0x0003
301 #define STUN_SOURCE_ADDRESS 0x0004
302 #define STUN_CHANGED_ADDRESS 0x0005
303 #define STUN_USERNAME 0x0006
304 #define STUN_PASSWORD 0x0007
305 #define STUN_MESSAGE_INTEGRITY 0x0008
306 #define STUN_ERROR_CODE 0x0009
307 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
308 #define STUN_REFLECTED_FROM 0x000b
310 /*! \brief helper function to print message names */
311 static const char *stun_msg2str(int msg)
315 return "Binding Request";
317 return "Binding Response";
319 return "Binding Error Response";
321 return "Shared Secret Request";
323 return "Shared Secret Response";
325 return "Shared Secret Error Response";
327 return "Non-RFC3489 Message";
330 /*! \brief helper function to print attribute names */
331 static const char *stun_attr2str(int msg)
334 case STUN_MAPPED_ADDRESS:
335 return "Mapped Address";
336 case STUN_RESPONSE_ADDRESS:
337 return "Response Address";
338 case STUN_CHANGE_REQUEST:
339 return "Change Request";
340 case STUN_SOURCE_ADDRESS:
341 return "Source Address";
342 case STUN_CHANGED_ADDRESS:
343 return "Changed Address";
348 case STUN_MESSAGE_INTEGRITY:
349 return "Message Integrity";
350 case STUN_ERROR_CODE:
352 case STUN_UNKNOWN_ATTRIBUTES:
353 return "Unknown Attributes";
354 case STUN_REFLECTED_FROM:
355 return "Reflected From";
357 return "Non-RFC3489 Attribute";
360 /*! \brief here we store credentials extracted from a message */
362 const char *username;
363 const char *password;
366 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
369 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
370 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
371 switch (ntohs(attr->attr)) {
373 state->username = (const char *) (attr->value);
376 state->password = (const char *) (attr->value);
380 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
381 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
386 /*! \brief append a string to an STUN message */
387 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
389 int size = sizeof(**attr) + strlen(s);
391 (*attr)->attr = htons(attrval);
392 (*attr)->len = htons(strlen(s));
393 memcpy((*attr)->value, s, strlen(s));
394 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
400 /*! \brief append an address to an STUN message */
401 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
403 int size = sizeof(**attr) + 8;
404 struct stun_addr *addr;
406 (*attr)->attr = htons(attrval);
407 (*attr)->len = htons(8);
408 addr = (struct stun_addr *)((*attr)->value);
411 addr->port = sin->sin_port;
412 addr->addr = sin->sin_addr.s_addr;
413 (*attr) = (struct stun_attr *)((*attr)->value + 8);
419 /*! \brief wrapper to send an STUN message */
420 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
422 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
423 (struct sockaddr *)dst, sizeof(*dst));
426 /*! \brief helper function to generate a random request id */
427 static void stun_req_id(struct stun_header *req)
430 for (x = 0; x < 4; x++)
431 req->id.id[x] = ast_random();
434 size_t ast_rtp_alloc_size(void)
436 return sizeof(struct ast_rtp);
439 /*! \brief callback type to be invoked on stun responses. */
440 typedef int (stun_cb_f)(struct stun_attr *attr, void *arg);
442 /*! \brief handle an incoming STUN message.
444 * Do some basic sanity checks on packet size and content,
445 * try to extract a bit of information, and possibly reply.
446 * At the moment this only processes BIND requests, and returns
447 * the externally visible address of the request.
448 * If a callback is specified, invoke it with the attribute.
450 static int stun_handle_packet(int s, struct sockaddr_in *src,
451 unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
453 struct stun_header *hdr = (struct stun_header *)data;
454 struct stun_attr *attr;
455 struct stun_state st;
456 int ret = STUN_IGNORE;
459 /* On entry, 'len' is the length of the udp payload. After the
460 * initial checks it becomes the size of unprocessed options,
461 * while 'data' is advanced accordingly.
463 if (len < sizeof(struct stun_header)) {
464 ast_debug(1, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
467 len -= sizeof(struct stun_header);
468 data += sizeof(struct stun_header);
469 x = ntohs(hdr->msglen); /* len as advertised in the message */
471 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), x);
473 ast_debug(1, "Scrambled STUN packet length (got %d, expecting %d)\n", x, (int)len);
476 memset(&st, 0, sizeof(st));
478 if (len < sizeof(struct stun_attr)) {
479 ast_debug(1, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
482 attr = (struct stun_attr *)data;
483 /* compute total attribute length */
484 x = ntohs(attr->len) + sizeof(struct stun_attr);
486 ast_debug(1, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x, (int)len);
491 if (stun_process_attr(&st, attr)) {
492 ast_debug(1, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
495 /* Clear attribute id: in case previous entry was a string,
496 * this will act as the terminator for the string.
502 /* Null terminate any string.
503 * XXX NOTE, we write past the size of the buffer passed by the
504 * caller, so this is potentially dangerous. The only thing that
505 * saves us is that usually we read the incoming message in a
506 * much larger buffer in the struct ast_rtp
510 /* Now prepare to generate a reply, which at the moment is done
511 * only for properly formed (len == 0) STUN_BINDREQ messages.
514 unsigned char respdata[1024];
515 struct stun_header *resp = (struct stun_header *)respdata;
516 int resplen = 0; /* len excluding header */
517 int respleft = sizeof(respdata) - sizeof(struct stun_header);
522 attr = (struct stun_attr *)resp->ies;
523 switch (ntohs(hdr->msgtype)) {
526 ast_verbose("STUN Bind Request, username: %s\n",
527 st.username ? st.username : "<none>");
529 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
530 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
531 resp->msglen = htons(resplen);
532 resp->msgtype = htons(STUN_BINDRESP);
533 stun_send(s, src, resp);
538 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
544 /*! \brief Extract the STUN_MAPPED_ADDRESS from the stun response.
545 * This is used as a callback for stun_handle_response
546 * when called from ast_stun_request.
548 static int stun_get_mapped(struct stun_attr *attr, void *arg)
550 struct stun_addr *addr = (struct stun_addr *)(attr + 1);
551 struct sockaddr_in *sa = (struct sockaddr_in *)arg;
553 if (ntohs(attr->attr) != STUN_MAPPED_ADDRESS || ntohs(attr->len) != 8)
554 return 1; /* not us. */
555 sa->sin_port = addr->port;
556 sa->sin_addr.s_addr = addr->addr;
560 /*! \brief Generic STUN request
561 * Send a generic stun request to the server specified,
562 * possibly waiting for a reply and filling the 'reply' field with
563 * the externally visible address. Note that in this case the request
565 * (Note, the interface may change slightly in the future).
567 * \param s the socket used to send the request
568 * \param dst the address of the STUN server
569 * \param username if non null, add the username in the request
570 * \param answer if non null, the function waits for a response and
571 * puts here the externally visible address.
572 * \return 0 on success, other values on error.
574 int ast_stun_request(int s, struct sockaddr_in *dst,
575 const char *username, struct sockaddr_in *answer)
577 struct stun_header *req;
578 unsigned char reqdata[1024];
580 struct stun_attr *attr;
584 req = (struct stun_header *)reqdata;
587 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
590 attr = (struct stun_attr *)req->ies;
592 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
593 req->msglen = htons(reqlen);
594 req->msgtype = htons(STUN_BINDREQ);
595 for (retry = 0; retry < 3; retry++) { /* XXX make retries configurable */
596 /* send request, possibly wait for reply */
597 unsigned char reply_buf[1024];
599 struct timeval to = { 3, 0 }; /* timeout, make it configurable */
600 struct sockaddr_in src;
603 res = stun_send(s, dst, req);
605 ast_log(LOG_WARNING, "ast_stun_request send #%d failed error %d, retry\n",
613 res = ast_select(s + 1, &rfds, NULL, NULL, &to);
614 if (res <= 0) /* timeout or error */
616 bzero(&src, sizeof(src));
617 srclen = sizeof(src);
618 /* XXX pass -1 in the size, because stun_handle_packet might
619 * write past the end of the buffer.
621 res = recvfrom(s, reply_buf, sizeof(reply_buf) - 1,
622 0, (struct sockaddr *)&src, &srclen);
624 ast_log(LOG_WARNING, "ast_stun_request recvfrom #%d failed error %d, retry\n",
628 bzero(answer, sizeof(struct sockaddr_in));
629 stun_handle_packet(s, &src, reply_buf, res,
630 stun_get_mapped, answer);
631 res = 0; /* signal regular exit */
637 /*! \brief send a STUN BIND request to the given destination.
638 * Optionally, add a username if specified.
640 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
642 ast_stun_request(rtp->s, suggestion, username, NULL);
645 /*! \brief List of current sessions */
646 static AST_RWLIST_HEAD_STATIC(protos, ast_rtp_protocol);
648 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
650 unsigned int sec, usec, frac;
651 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
653 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
658 int ast_rtp_fd(struct ast_rtp *rtp)
663 int ast_rtcp_fd(struct ast_rtp *rtp)
670 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
672 unsigned int interval;
673 /*! \todo XXX Do a more reasonable calculation on this one
674 * Look in RFC 3550 Section A.7 for an example*/
675 interval = rtcpinterval;
679 /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
680 void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
682 rtp->rtptimeout = (-1) * rtp->rtptimeout;
683 rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
686 /*! \brief Set rtp timeout */
687 void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
689 rtp->rtptimeout = timeout;
692 /*! \brief Set rtp hold timeout */
693 void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
695 rtp->rtpholdtimeout = timeout;
698 /*! \brief set RTP keepalive interval */
699 void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
701 rtp->rtpkeepalive = period;
704 /*! \brief Get rtp timeout */
705 int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
707 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
709 return rtp->rtptimeout;
712 /*! \brief Get rtp hold timeout */
713 int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
715 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
717 return rtp->rtpholdtimeout;
720 /*! \brief Get RTP keepalive interval */
721 int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
723 return rtp->rtpkeepalive;
726 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
731 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
733 rtp->callback = callback;
736 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
741 int ast_rtp_getnat(struct ast_rtp *rtp)
743 return ast_test_flag(rtp, FLAG_NAT_ACTIVE);
746 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
748 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
751 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
753 ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
756 void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
758 ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
761 static void rtp_bridge_lock(struct ast_rtp *rtp)
764 ast_mutex_lock(&rtp->bridge_lock);
769 static void rtp_bridge_unlock(struct ast_rtp *rtp)
772 ast_mutex_unlock(&rtp->bridge_lock);
777 static struct ast_frame *send_dtmf(struct ast_rtp *rtp, enum ast_frame_type type)
779 if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
780 (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
781 ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
783 rtp->dtmfsamples = 0;
784 return &ast_null_frame;
786 ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
787 if (rtp->resp == 'X') {
788 rtp->f.frametype = AST_FRAME_CONTROL;
789 rtp->f.subclass = AST_CONTROL_FLASH;
791 rtp->f.frametype = type;
792 rtp->f.subclass = rtp->resp;
802 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
806 if (rtpdebugaddr.sin_addr.s_addr) {
807 if (((ntohs(rtpdebugaddr.sin_port) != 0)
808 && (rtpdebugaddr.sin_port != addr->sin_port))
809 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
815 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
819 if (rtcpdebugaddr.sin_addr.s_addr) {
820 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
821 && (rtcpdebugaddr.sin_port != addr->sin_port))
822 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
829 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
833 struct ast_frame *f = NULL;
838 /* We should have at least 4 bytes in RTP data */
842 /* The format of Cisco RTP DTMF packet looks like next:
843 +0 - sequence number of DTMF RTP packet (begins from 1,
846 +1 (bit 0) - flaps by different DTMF digits delimited by audio
847 or repeated digit without audio???
848 +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
849 then falls to 0 at its end)
850 +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
851 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
852 by each new packet and thus provides some redudancy.
854 Sample of Cisco RTP DTMF packet is (all data in hex):
855 19 07 00 02 12 02 20 02
856 showing end of DTMF digit '2'.
859 27 07 00 02 0A 02 20 02
860 28 06 20 02 00 02 0A 02
861 shows begin of new digit '2' with very short pause (20 ms) after
862 previous digit '2'. Bit +1.0 flips at begin of new digit.
864 Cisco RTP DTMF packets comes as replacement of audio RTP packets
865 so its uses the same sequencing and timestamping rules as replaced
866 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
867 on audio framing parameters. Marker bit isn't used within stream of
868 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
869 are not sequential at borders between DTMF and audio streams,
875 event = data[3] & 0x1f;
877 if (option_debug > 2 || rtpdebug)
878 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);
881 } else if (event < 11) {
883 } else if (event < 12) {
885 } else if (event < 16) {
886 resp = 'A' + (event - 12);
887 } else if (event < 17) {
890 if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
892 /* Why we should care on DTMF compensation at reception? */
893 if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
894 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
895 rtp->dtmfsamples = 0;
897 } else if ((rtp->resp == resp) && !power) {
898 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
899 f->samples = rtp->dtmfsamples * 8;
901 } else if (rtp->resp == resp)
902 rtp->dtmfsamples += 20 * 8;
903 rtp->dtmfcount = dtmftimeout;
908 * \brief Process RTP DTMF and events according to RFC 2833.
910 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
919 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp)
922 unsigned int event_end;
923 unsigned int samples;
925 struct ast_frame *f = NULL;
927 /* Figure out event, event end, and samples */
928 event = ntohl(*((unsigned int *)(data)));
930 event_end = ntohl(*((unsigned int *)(data)));
933 samples = ntohl(*((unsigned int *)(data)));
936 /* Print out debug if turned on */
937 if (rtpdebug || option_debug > 2)
938 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
940 /* Figure out what digit was pressed */
943 } else if (event < 11) {
945 } else if (event < 12) {
947 } else if (event < 16) {
948 resp = 'A' + (event - 12);
949 } else if (event < 17) { /* Event 16: Hook flash */
952 /* Not a supported event */
953 ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
954 return &ast_null_frame;
957 if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
958 if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
960 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
962 rtp->lastevent = timestamp;
965 if ((!(rtp->resp) && (!(event_end & 0x80))) || (rtp->resp && rtp->resp != resp)) {
967 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
968 } else if ((event_end & 0x80) && (rtp->lastevent != seqno) && rtp->resp) {
969 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
970 f->len = ast_tvdiff_ms(ast_samp2tv(samples, 8000), ast_tv(0, 0)); /* XXX hard coded 8kHz */
972 rtp->lastevent = seqno;
976 rtp->dtmfcount = dtmftimeout;
977 rtp->dtmfsamples = samples;
983 * \brief Process Comfort Noise RTP.
985 * This is incomplete at the moment.
988 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
990 struct ast_frame *f = NULL;
991 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
992 totally help us out becuase we don't have an engine to keep it going and we are not
993 guaranteed to have it every 20ms or anything */
995 ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
997 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
998 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
999 ast_inet_ntoa(rtp->them.sin_addr));
1000 ast_set_flag(rtp, FLAG_3389_WARNING);
1003 /* Must have at least one byte */
1007 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
1008 rtp->f.datalen = len - 1;
1009 rtp->f.offset = AST_FRIENDLY_OFFSET;
1010 memcpy(rtp->f.data, data + 1, len - 1);
1016 rtp->f.frametype = AST_FRAME_CNG;
1017 rtp->f.subclass = data[0] & 0x7f;
1018 rtp->f.datalen = len - 1;
1020 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
1025 static int rtpread(int *id, int fd, short events, void *cbdata)
1027 struct ast_rtp *rtp = cbdata;
1028 struct ast_frame *f;
1029 f = ast_rtp_read(rtp);
1032 rtp->callback(rtp, f, rtp->data);
1037 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
1040 int position, i, packetwords;
1042 struct sockaddr_in sin;
1043 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
1044 unsigned int *rtcpheader;
1047 unsigned int length;
1056 struct ast_frame *f = &ast_null_frame;
1058 if (!rtp || !rtp->rtcp)
1059 return &ast_null_frame;
1063 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
1064 0, (struct sockaddr *)&sin, &len);
1065 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
1070 if (errno != EAGAIN) {
1071 ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n", strerror(errno));
1074 return &ast_null_frame;
1077 packetwords = res / 4;
1080 /* Send to whoever sent to us */
1081 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1082 (rtp->rtcp->them.sin_port != sin.sin_port)) {
1083 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1084 if (option_debug || rtpdebug)
1085 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));
1089 ast_debug(1, "Got RTCP report of %d bytes\n", res);
1091 /* Process a compound packet */
1093 while (position < packetwords) {
1095 length = ntohl(rtcpheader[i]);
1096 pt = (length & 0xff0000) >> 16;
1097 rc = (length & 0x1f000000) >> 24;
1100 if ((i + length) > packetwords) {
1101 if (option_debug || rtpdebug)
1102 ast_log(LOG_DEBUG, "RTCP Read too short\n");
1103 return &ast_null_frame;
1106 if (rtcp_debug_test_addr(&sin)) {
1107 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1108 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
1109 ast_verbose("Reception reports: %d\n", rc);
1110 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
1113 i += 2; /* Advance past header and ssrc */
1117 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
1118 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
1119 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
1120 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
1122 if (rtcp_debug_test_addr(&sin)) {
1123 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
1124 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
1125 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
1130 /* Intentional fall through */
1132 /* Don't handle multiple reception reports (rc > 1) yet */
1133 /* Calculate RTT per RFC */
1134 gettimeofday(&now, NULL);
1135 timeval2ntp(now, &msw, &lsw);
1136 if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
1137 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
1138 lsr = ntohl(rtcpheader[i + 4]);
1139 dlsr = ntohl(rtcpheader[i + 5]);
1140 rtt = comp - lsr - dlsr;
1142 /* Convert end to end delay to usec (keeping the calculation in 64bit space)
1143 sess->ee_delay = (eedelay * 1000) / 65536; */
1145 rtt = (rtt * 1000000) >> 16;
1147 rtt = (rtt * 1000) >> 16;
1151 rttsec = rtt / 1000.;
1153 if (comp - dlsr >= lsr) {
1154 rtp->rtcp->accumulated_transit += rttsec;
1155 rtp->rtcp->rtt = rttsec;
1156 if (rtp->rtcp->maxrtt<rttsec)
1157 rtp->rtcp->maxrtt = rttsec;
1158 if (rtp->rtcp->minrtt>rttsec)
1159 rtp->rtcp->minrtt = rttsec;
1160 } else if (rtcp_debug_test_addr(&sin)) {
1161 ast_verbose("Internal RTCP NTP clock skew detected: "
1162 "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
1164 lsr, comp, dlsr, dlsr / 65536,
1165 (dlsr % 65536) * 1000 / 65536,
1166 dlsr - (comp - lsr));
1170 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
1171 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
1172 if (rtcp_debug_test_addr(&sin)) {
1173 ast_verbose(" Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
1174 ast_verbose(" Packets lost so far: %d\n", rtp->rtcp->reported_lost);
1175 ast_verbose(" Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
1176 ast_verbose(" Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
1177 ast_verbose(" Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
1178 ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
1179 ast_verbose(" DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
1181 ast_verbose(" RTT: %lu(sec)\n", (unsigned long) rtt);
1184 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From %s:%d\r\n"
1186 "ReceptionReports: %d\r\n"
1187 "SenderSSRC: %u\r\n"
1188 "FractionLost: %ld\r\n"
1189 "PacketsLost: %d\r\n"
1190 "HighestSequence: %ld\r\n"
1191 "SequenceNumberCycles: %ld\r\n"
1193 "LastSR: %lu.%010lu\r\n"
1194 "DLSR: %4.4f(sec)\r\n"
1195 "RTT: %llu(sec)\r\n",
1196 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
1197 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1200 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1201 rtp->rtcp->reported_lost,
1202 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1203 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1204 rtp->rtcp->reported_jitter,
1205 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1206 ntohl(rtcpheader[i + 5])/65536.0,
1207 (unsigned long long)rtt);
1209 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From %s:%d\r\n"
1211 "ReceptionReports: %d\r\n"
1212 "SenderSSRC: %u\r\n"
1213 "FractionLost: %ld\r\n"
1214 "PacketsLost: %d\r\n"
1215 "HighestSequence: %ld\r\n"
1216 "SequenceNumberCycles: %ld\r\n"
1218 "LastSR: %lu.%010lu\r\n"
1219 "DLSR: %4.4f(sec)\r\n",
1220 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
1221 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1224 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1225 rtp->rtcp->reported_lost,
1226 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1227 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1228 rtp->rtcp->reported_jitter,
1229 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
1230 ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1231 ntohl(rtcpheader[i + 5])/65536.0);
1235 if (rtcp_debug_test_addr(&sin))
1236 ast_verbose("Received an RTCP Fast Update Request\n");
1237 rtp->f.frametype = AST_FRAME_CONTROL;
1238 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
1246 if (rtcp_debug_test_addr(&sin))
1247 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1250 if (rtcp_debug_test_addr(&sin))
1251 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1254 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));
1257 position += (length + 1);
1263 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
1267 double current_time;
1272 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
1273 gettimeofday(&rtp->rxcore, NULL);
1274 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
1275 /* map timestamp to a real time */
1276 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
1277 rtp->rxcore.tv_sec -= timestamp / 8000;
1278 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
1279 /* Round to 0.1ms for nice, pretty timestamps */
1280 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
1281 if (rtp->rxcore.tv_usec < 0) {
1282 /* Adjust appropriately if necessary */
1283 rtp->rxcore.tv_usec += 1000000;
1284 rtp->rxcore.tv_sec -= 1;
1288 gettimeofday(&now,NULL);
1289 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
1290 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
1291 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
1292 if (tv->tv_usec >= 1000000) {
1293 tv->tv_usec -= 1000000;
1296 prog = (double)((timestamp-rtp->seedrxts)/8000.);
1297 dtv = (double)rtp->drxcore + (double)(prog);
1298 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
1299 transit = current_time - dtv;
1300 d = transit - rtp->rxtransit;
1301 rtp->rxtransit = transit;
1304 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1305 if (rtp->rtcp && rtp->rxjitter > rtp->rtcp->maxrxjitter)
1306 rtp->rtcp->maxrxjitter = rtp->rxjitter;
1307 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1308 rtp->rtcp->minrxjitter = rtp->rxjitter;
1311 /*! \brief Perform a Packet2Packet RTP write */
1312 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, struct ast_rtp *bridged, unsigned int *rtpheader, int len, int hdrlen)
1314 int res = 0, payload = 0, bridged_payload = 0, mark;
1315 struct rtpPayloadType rtpPT;
1316 int reconstruct = ntohl(rtpheader[0]);
1318 /* Get fields from packet */
1319 payload = (reconstruct & 0x7f0000) >> 16;
1320 mark = (((reconstruct & 0x800000) >> 23) != 0);
1322 /* Check what the payload value should be */
1323 rtpPT = ast_rtp_lookup_pt(rtp, payload);
1325 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
1326 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
1329 /* Otherwise adjust bridged payload to match */
1330 bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
1332 /* If the mark bit has not been sent yet... do it now */
1333 if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
1335 ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
1338 /* Reconstruct part of the packet */
1339 reconstruct &= 0xFF80FFFF;
1340 reconstruct |= (bridged_payload << 16);
1341 reconstruct |= (mark << 23);
1342 rtpheader[0] = htonl(reconstruct);
1344 /* Send the packet back out */
1345 res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
1347 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1348 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));
1349 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1350 if (option_debug || rtpdebug)
1351 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));
1352 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1355 } else if (rtp_debug_test_addr(&bridged->them))
1356 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);
1361 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
1364 struct sockaddr_in sin;
1375 unsigned int timestamp;
1376 unsigned int *rtpheader;
1377 struct rtpPayloadType rtpPT;
1378 struct ast_rtp *bridged = NULL;
1380 /* If time is up, kill it */
1381 if (rtp->sending_digit)
1382 ast_rtp_senddigit_continuation(rtp);
1386 /* Cache where the header will go */
1387 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
1388 0, (struct sockaddr *)&sin, &len);
1390 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
1394 if (errno != EAGAIN) {
1395 ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
1398 return &ast_null_frame;
1402 ast_log(LOG_WARNING, "RTP Read too short\n");
1403 return &ast_null_frame;
1407 seqno = ntohl(rtpheader[0]);
1409 /* Check RTP version */
1410 version = (seqno & 0xC0000000) >> 30;
1412 /* If the two high bits are 0, this might be a
1413 * STUN message, so process it. stun_handle_packet()
1414 * answers to requests, and it returns STUN_ACCEPT
1415 * if the request is valid.
1417 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == STUN_ACCEPT) &&
1418 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
1419 memcpy(&rtp->them, &sin, sizeof(rtp->them));
1421 return &ast_null_frame;
1424 #if 0 /* Allow to receive RTP stream with closed transmission path */
1425 /* If we don't have the other side's address, then ignore this */
1426 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1427 return &ast_null_frame;
1430 /* Send to whoever send to us if NAT is turned on */
1432 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1433 (rtp->them.sin_port != sin.sin_port)) {
1436 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1437 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1440 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1441 if (option_debug || rtpdebug)
1442 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));
1446 /* If we are bridged to another RTP stream, send direct */
1447 if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
1448 return &ast_null_frame;
1451 return &ast_null_frame;
1453 payloadtype = (seqno & 0x7f0000) >> 16;
1454 padding = seqno & (1 << 29);
1455 mark = seqno & (1 << 23);
1456 ext = seqno & (1 << 28);
1457 cc = (seqno & 0xF000000) >> 24;
1459 timestamp = ntohl(rtpheader[1]);
1460 ssrc = ntohl(rtpheader[2]);
1462 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1463 if (option_debug || rtpdebug)
1464 ast_debug(0, "Forcing Marker bit, because SSRC has changed\n");
1471 /* Remove padding bytes */
1472 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1476 /* CSRC fields present */
1481 /* RTP Extension present */
1482 hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
1486 profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
1487 if (profile == 0x505a)
1488 ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
1490 ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
1495 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1496 return &ast_null_frame;
1499 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1501 if (rtp->rxcount==1) {
1502 /* This is the first RTP packet successfully received from source */
1503 rtp->seedrxseqno = seqno;
1506 /* Do not schedule RR if RTCP isn't run */
1507 if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
1508 /* Schedule transmission of Receiver Report */
1509 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1511 if ( (int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
1512 rtp->cycles += RTP_SEQ_MOD;
1514 rtp->lastrxseqno = seqno;
1516 if (rtp->themssrc==0)
1517 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1519 if (rtp_debug_test_addr(&sin))
1520 ast_verbose("Got RTP packet from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1521 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1523 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1524 if (!rtpPT.isAstFormat) {
1525 struct ast_frame *f = NULL;
1527 /* This is special in-band data that's not one of our codecs */
1528 if (rtpPT.code == AST_RTP_DTMF) {
1529 /* It's special -- rfc2833 process it */
1530 if (rtp_debug_test_addr(&sin)) {
1531 unsigned char *data;
1533 unsigned int event_end;
1534 unsigned int duration;
1535 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1536 event = ntohl(*((unsigned int *)(data)));
1538 event_end = ntohl(*((unsigned int *)(data)));
1541 duration = ntohl(*((unsigned int *)(data)));
1543 ast_verbose("Got RTP RFC2833 from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
1545 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp);
1546 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1547 /* It's really special -- process it the Cisco way */
1548 if (rtp->lastevent <= seqno || (rtp->lastevent >= 65530 && seqno <= 6)) {
1549 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1550 rtp->lastevent = seqno;
1552 } else if (rtpPT.code == AST_RTP_CN) {
1554 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1556 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1558 return f ? f : &ast_null_frame;
1560 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1561 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;
1564 rtp->lastrxts = timestamp;
1566 rtp->rxseqno = seqno;
1568 /* Record received timestamp as last received now */
1569 rtp->lastrxts = timestamp;
1572 rtp->f.datalen = res - hdrlen;
1573 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1574 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1575 rtp->f.seqno = seqno;
1576 if (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) {
1577 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1578 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1579 ast_frame_byteswap_be(&rtp->f);
1580 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1581 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1582 rtp->f.has_timing_info = 1;
1583 rtp->f.ts = timestamp / 8;
1584 rtp->f.len = rtp->f.samples / 8;
1585 } else if(rtp->f.subclass & AST_FORMAT_VIDEO_MASK) {
1586 /* Video -- samples is # of samples vs. 90000 */
1587 if (!rtp->lastividtimestamp)
1588 rtp->lastividtimestamp = timestamp;
1589 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1590 rtp->lastividtimestamp = timestamp;
1591 rtp->f.delivery.tv_sec = 0;
1592 rtp->f.delivery.tv_usec = 0;
1593 /* Pass the RTP marker bit as bit 0 in the subclass field.
1594 * This is ok because subclass is actually a bitmask, and
1595 * the low bits represent audio formats, that are not
1596 * involved here since we deal with video.
1599 rtp->f.subclass |= 0x1;
1601 /* TEXT -- samples is # of samples vs. 1000 */
1602 if (!rtp->lastitexttimestamp)
1603 rtp->lastitexttimestamp = timestamp;
1604 rtp->f.samples = timestamp - rtp->lastitexttimestamp;
1605 rtp->lastitexttimestamp = timestamp;
1606 rtp->f.delivery.tv_sec = 0;
1607 rtp->f.delivery.tv_usec = 0;
1613 /* The following array defines the MIME Media type (and subtype) for each
1614 of our codecs, or RTP-specific data type. */
1616 struct rtpPayloadType payloadType;
1620 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1621 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1622 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1623 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1624 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1625 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1626 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1627 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1628 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1629 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1630 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1631 {{1, AST_FORMAT_G722}, "audio", "G722"},
1632 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
1633 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1634 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1635 {{0, AST_RTP_CN}, "audio", "CN"},
1636 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1637 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1638 {{1, AST_FORMAT_H261}, "video", "H261"},
1639 {{1, AST_FORMAT_H263}, "video", "H263"},
1640 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1641 {{1, AST_FORMAT_H264}, "video", "H264"},
1642 {{1, AST_FORMAT_MP4_VIDEO}, "video", "MP4V-ES"},
1643 {{1, AST_FORMAT_T140}, "text", "T140"},
1647 * \brief Mapping between Asterisk codecs and rtp payload types
1649 * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1650 * also, our own choices for dynamic payload types. This is our master
1651 * table for transmission
1653 * See http://www.iana.org/assignments/rtp-parameters for a list of
1656 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1657 [0] = {1, AST_FORMAT_ULAW},
1658 #ifdef USE_DEPRECATED_G726
1659 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1661 [3] = {1, AST_FORMAT_GSM},
1662 [4] = {1, AST_FORMAT_G723_1},
1663 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1664 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1665 [7] = {1, AST_FORMAT_LPC10},
1666 [8] = {1, AST_FORMAT_ALAW},
1667 [9] = {1, AST_FORMAT_G722},
1668 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1669 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1670 [13] = {0, AST_RTP_CN},
1671 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1672 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1673 [18] = {1, AST_FORMAT_G729A},
1674 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1675 [26] = {1, AST_FORMAT_JPEG},
1676 [31] = {1, AST_FORMAT_H261},
1677 [34] = {1, AST_FORMAT_H263},
1678 [97] = {1, AST_FORMAT_ILBC},
1679 [98] = {1, AST_FORMAT_H263_PLUS},
1680 [99] = {1, AST_FORMAT_H264},
1681 [101] = {0, AST_RTP_DTMF},
1682 [102] = {1, AST_FORMAT_T140}, /* Real time text chat */
1683 [103] = {1, AST_FORMAT_H263_PLUS},
1684 [104] = {1, AST_FORMAT_MP4_VIDEO},
1685 [110] = {1, AST_FORMAT_SPEEX},
1686 [111] = {1, AST_FORMAT_G726},
1687 [112] = {1, AST_FORMAT_G726_AAL2},
1688 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1691 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1698 rtp_bridge_lock(rtp);
1700 for (i = 0; i < MAX_RTP_PT; ++i) {
1701 rtp->current_RTP_PT[i].isAstFormat = 0;
1702 rtp->current_RTP_PT[i].code = 0;
1705 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1706 rtp->rtp_lookup_code_cache_code = 0;
1707 rtp->rtp_lookup_code_cache_result = 0;
1709 rtp_bridge_unlock(rtp);
1712 void ast_rtp_pt_default(struct ast_rtp* rtp)
1716 rtp_bridge_lock(rtp);
1718 /* Initialize to default payload types */
1719 for (i = 0; i < MAX_RTP_PT; ++i) {
1720 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1721 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1724 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1725 rtp->rtp_lookup_code_cache_code = 0;
1726 rtp->rtp_lookup_code_cache_result = 0;
1728 rtp_bridge_unlock(rtp);
1731 void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
1735 rtp_bridge_lock(dest);
1736 rtp_bridge_lock(src);
1738 for (i=0; i < MAX_RTP_PT; ++i) {
1739 dest->current_RTP_PT[i].isAstFormat =
1740 src->current_RTP_PT[i].isAstFormat;
1741 dest->current_RTP_PT[i].code =
1742 src->current_RTP_PT[i].code;
1744 dest->rtp_lookup_code_cache_isAstFormat = 0;
1745 dest->rtp_lookup_code_cache_code = 0;
1746 dest->rtp_lookup_code_cache_result = 0;
1748 rtp_bridge_unlock(src);
1749 rtp_bridge_unlock(dest);
1752 /*! \brief Get channel driver interface structure */
1753 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1755 struct ast_rtp_protocol *cur = NULL;
1757 AST_RWLIST_RDLOCK(&protos);
1758 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1759 if (cur->type == chan->tech->type)
1762 AST_RWLIST_UNLOCK(&protos);
1767 int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1769 // dest = c0, src = c1
1770 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1771 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1772 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
1773 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1774 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;
1775 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;
1776 int srccodec, destcodec, nat_active = 0;
1779 ast_channel_lock(c0);
1781 while (ast_channel_trylock(c1)) {
1782 ast_channel_unlock(c0);
1784 ast_channel_lock(c0);
1788 /* Find channel driver interfaces */
1789 destpr = get_proto(c0);
1791 srcpr = get_proto(c1);
1793 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c0->name);
1794 ast_channel_unlock(c0);
1796 ast_channel_unlock(c1);
1800 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
1801 ast_channel_unlock(c0);
1803 ast_channel_unlock(c1);
1807 /* Get audio, video and text interface (if native bridge is possible) */
1808 audio_dest_res = destpr->get_rtp_info(c0, &destp);
1809 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
1810 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(c0, &tdestp) : AST_RTP_GET_FAILED;
1812 audio_src_res = srcpr->get_rtp_info(c1, &srcp);
1813 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
1814 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(c1, &tsrcp) : AST_RTP_GET_FAILED;
1817 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1818 if (audio_dest_res != AST_RTP_TRY_NATIVE) {
1819 /* Somebody doesn't want to play... */
1820 ast_channel_unlock(c0);
1822 ast_channel_unlock(c1);
1825 if (audio_src_res == AST_RTP_TRY_NATIVE && srcpr->get_codec)
1826 srccodec = srcpr->get_codec(c1);
1829 if (audio_dest_res == AST_RTP_TRY_NATIVE && destpr->get_codec)
1830 destcodec = destpr->get_codec(c0);
1833 /* Ensure we have at least one matching codec */
1834 if (!(srccodec & destcodec)) {
1835 ast_channel_unlock(c0);
1837 ast_channel_unlock(c1);
1840 /* Consider empty media as non-existant */
1841 if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
1843 if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1845 /* Bridge media early */
1846 if (destpr->set_rtp_peer(c0, srcp, vsrcp, tsrcp, srccodec, nat_active))
1847 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1848 ast_channel_unlock(c0);
1850 ast_channel_unlock(c1);
1851 ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1855 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1857 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1858 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1859 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
1860 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1861 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;
1862 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;
1863 int srccodec, destcodec;
1866 ast_channel_lock(dest);
1867 while (ast_channel_trylock(src)) {
1868 ast_channel_unlock(dest);
1870 ast_channel_lock(dest);
1873 /* Find channel driver interfaces */
1874 if (!(destpr = get_proto(dest))) {
1875 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1876 ast_channel_unlock(dest);
1877 ast_channel_unlock(src);
1880 if (!(srcpr = get_proto(src))) {
1881 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", src->name);
1882 ast_channel_unlock(dest);
1883 ast_channel_unlock(src);
1887 /* Get audio and video interface (if native bridge is possible) */
1888 audio_dest_res = destpr->get_rtp_info(dest, &destp);
1889 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
1890 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(dest, &tdestp) : AST_RTP_GET_FAILED;
1891 audio_src_res = srcpr->get_rtp_info(src, &srcp);
1892 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
1893 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(src, &tsrcp) : AST_RTP_GET_FAILED;
1895 /* Ensure we have at least one matching codec */
1896 if (srcpr->get_codec)
1897 srccodec = srcpr->get_codec(src);
1900 if (destpr->get_codec)
1901 destcodec = destpr->get_codec(dest);
1905 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1906 if (audio_dest_res != AST_RTP_TRY_NATIVE || audio_src_res != AST_RTP_TRY_NATIVE || !(srccodec & destcodec)) {
1907 /* Somebody doesn't want to play... */
1908 ast_channel_unlock(dest);
1909 ast_channel_unlock(src);
1912 ast_rtp_pt_copy(destp, srcp);
1913 if (vdestp && vsrcp)
1914 ast_rtp_pt_copy(vdestp, vsrcp);
1915 if (tdestp && tsrcp)
1916 ast_rtp_pt_copy(tdestp, tsrcp);
1919 if (destpr->set_rtp_peer(dest, srcp, vsrcp, tsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1920 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1922 ast_channel_unlock(dest);
1923 ast_channel_unlock(src);
1924 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1928 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1929 * By default, use the well-known value for this type (although it may
1930 * still be set to a different value by a subsequent "a=rtpmap:" line)
1932 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1934 if (pt < 0 || pt > MAX_RTP_PT || static_RTP_PT[pt].code == 0)
1935 return; /* bogus payload type */
1937 rtp_bridge_lock(rtp);
1938 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1939 rtp_bridge_unlock(rtp);
1942 /*! \brief remove setting from payload type list if the rtpmap header indicates
1943 an unknown media type */
1944 void ast_rtp_unset_m_type(struct ast_rtp* rtp, int pt)
1946 rtp_bridge_lock(rtp);
1947 rtp->current_RTP_PT[pt].isAstFormat = 0;
1948 rtp->current_RTP_PT[pt].code = 0;
1949 rtp_bridge_unlock(rtp);
1952 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1953 * an SDP "a=rtpmap:" line.
1954 * \return 0 if the MIME type was found and set, -1 if it wasn't found
1956 int ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
1957 char *mimeType, char *mimeSubtype,
1958 enum ast_rtp_options options)
1963 if (pt < 0 || pt > MAX_RTP_PT)
1964 return -1; /* bogus payload type */
1966 rtp_bridge_lock(rtp);
1968 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1969 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1970 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1972 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1973 if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
1974 mimeTypes[i].payloadType.isAstFormat &&
1975 (options & AST_RTP_OPT_G726_NONSTANDARD))
1976 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
1981 rtp_bridge_unlock(rtp);
1983 return (found ? 0 : -1);
1986 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
1987 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1988 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1989 int* astFormats, int* nonAstFormats)
1993 rtp_bridge_lock(rtp);
1995 *astFormats = *nonAstFormats = 0;
1996 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1997 if (rtp->current_RTP_PT[pt].isAstFormat) {
1998 *astFormats |= rtp->current_RTP_PT[pt].code;
2000 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
2004 rtp_bridge_unlock(rtp);
2009 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
2011 struct rtpPayloadType result;
2013 result.isAstFormat = result.code = 0;
2015 if (pt < 0 || pt > MAX_RTP_PT)
2016 return result; /* bogus payload type */
2018 /* Start with negotiated codecs */
2019 rtp_bridge_lock(rtp);
2020 result = rtp->current_RTP_PT[pt];
2021 rtp_bridge_unlock(rtp);
2023 /* If it doesn't exist, check our static RTP type list, just in case */
2025 result = static_RTP_PT[pt];
2030 /*! \brief Looks up an RTP code out of our *static* outbound list */
2031 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
2035 rtp_bridge_lock(rtp);
2037 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
2038 code == rtp->rtp_lookup_code_cache_code) {
2039 /* Use our cached mapping, to avoid the overhead of the loop below */
2040 pt = rtp->rtp_lookup_code_cache_result;
2041 rtp_bridge_unlock(rtp);
2045 /* Check the dynamic list first */
2046 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2047 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
2048 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2049 rtp->rtp_lookup_code_cache_code = code;
2050 rtp->rtp_lookup_code_cache_result = pt;
2051 rtp_bridge_unlock(rtp);
2056 /* Then the static list */
2057 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2058 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
2059 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2060 rtp->rtp_lookup_code_cache_code = code;
2061 rtp->rtp_lookup_code_cache_result = pt;
2062 rtp_bridge_unlock(rtp);
2067 rtp_bridge_unlock(rtp);
2072 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
2073 enum ast_rtp_options options)
2077 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
2078 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
2080 (code == AST_FORMAT_G726_AAL2) &&
2081 (options & AST_RTP_OPT_G726_NONSTANDARD))
2084 return mimeTypes[i].subtype;
2091 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
2092 const int isAstFormat, enum ast_rtp_options options)
2102 snprintf(end, size, "0x%x (", capability);
2109 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
2110 if (capability & format) {
2111 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
2113 snprintf(end, size, "%s|", name);
2121 ast_copy_string(start, "nothing)", size);
2128 /*! \brief Open RTP or RTCP socket for a session.
2129 * Print a message on failure.
2131 static int rtp_socket(const char *type)
2133 int s = socket(AF_INET, SOCK_DGRAM, 0);
2137 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
2139 long flags = fcntl(s, F_GETFL);
2140 fcntl(s, F_SETFL, flags | O_NONBLOCK);
2143 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
2150 * \brief Initialize a new RTCP session.
2152 * \returns The newly initialized RTCP session.
2154 static struct ast_rtcp *ast_rtcp_new(void)
2156 struct ast_rtcp *rtcp;
2158 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
2160 rtcp->s = rtp_socket("RTCP");
2161 rtcp->us.sin_family = AF_INET;
2162 rtcp->them.sin_family = AF_INET;
2173 * \brief Initialize a new RTP structure.
2176 void ast_rtp_new_init(struct ast_rtp *rtp)
2179 ast_mutex_init(&rtp->bridge_lock);
2182 rtp->them.sin_family = AF_INET;
2183 rtp->us.sin_family = AF_INET;
2184 rtp->ssrc = ast_random();
2185 rtp->seqno = ast_random() & 0xffff;
2186 ast_set_flag(rtp, FLAG_HAS_DTMF);
2191 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
2193 struct ast_rtp *rtp;
2197 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
2200 ast_rtp_new_init(rtp);
2202 rtp->s = rtp_socket("RTP");
2205 if (sched && rtcpenable) {
2207 rtp->rtcp = ast_rtcp_new();
2211 * Try to bind the RTP port, x, and possibly the RTCP port, x+1 as well.
2212 * Start from a random (even, by RTP spec) port number, and
2213 * iterate until success or no ports are available.
2214 * Note that the requirement of RTP port being even, or RTCP being the
2215 * next one, cannot be enforced in presence of a NAT box because the
2216 * mapping is not under our control.
2218 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
2219 x = x & ~1; /* make it an even number */
2220 startplace = x; /* remember the starting point */
2221 /* this is constant across the loop */
2222 rtp->us.sin_addr = addr;
2224 rtp->rtcp->us.sin_addr = addr;
2226 rtp->us.sin_port = htons(x);
2227 if (!bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) {
2228 /* bind succeeded, if no rtcp then we are done */
2231 /* have rtcp, try to bind it */
2232 rtp->rtcp->us.sin_port = htons(x + 1);
2233 if (!bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us)))
2234 break; /* success again, we are really done */
2236 * RTCP bind failed, so close and recreate the
2237 * already bound RTP socket for the next round.
2240 rtp->s = rtp_socket("RTP");
2245 * If we get here, there was an error in one of the bind()
2246 * calls, so make sure it is nothing unexpected.
2248 if (errno != EADDRINUSE) {
2249 /* We got an error that wasn't expected, abort! */
2250 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
2254 * One of the ports is in use. For the next iteration,
2255 * increment by two and handle wraparound.
2256 * If we reach the starting point, then declare failure.
2260 x = (rtpstart + 1) & ~1;
2261 if (x == startplace) {
2262 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
2269 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
2270 ast_set_flag(rtp, FLAG_CALLBACK_MODE);
2272 ast_rtp_pt_default(rtp);
2279 close(rtp->rtcp->s);
2280 ast_free(rtp->rtcp);
2286 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
2290 memset(&ia, 0, sizeof(ia));
2291 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
2294 int ast_rtp_setqos(struct ast_rtp *rtp, int tos, int cos)
2296 return ast_netsock_set_qos(rtp->s, tos, cos);
2299 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2301 rtp->them.sin_port = them->sin_port;
2302 rtp->them.sin_addr = them->sin_addr;
2304 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
2305 rtp->rtcp->them.sin_addr = them->sin_addr;
2310 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2312 if ((them->sin_family != AF_INET) ||
2313 (them->sin_port != rtp->them.sin_port) ||
2314 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
2315 them->sin_family = AF_INET;
2316 them->sin_port = rtp->them.sin_port;
2317 them->sin_addr = rtp->them.sin_addr;
2323 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
2328 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
2330 struct ast_rtp *bridged = NULL;
2332 rtp_bridge_lock(rtp);
2333 bridged = rtp->bridged;
2334 rtp_bridge_unlock(rtp);
2339 void ast_rtp_stop(struct ast_rtp *rtp)
2341 if (rtp->rtcp && rtp->rtcp->schedid > 0) {
2342 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2343 rtp->rtcp->schedid = -1;
2346 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
2347 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
2349 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
2350 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
2353 ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
2356 void ast_rtp_reset(struct ast_rtp *rtp)
2358 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
2359 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
2360 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
2362 rtp->lastdigitts = 0;
2364 rtp->lastividtimestamp = 0;
2365 rtp->lastovidtimestamp = 0;
2366 rtp->lastitexttimestamp = 0;
2367 rtp->lastotexttimestamp = 0;
2368 rtp->lasteventseqn = 0;
2370 rtp->lasttxformat = 0;
2371 rtp->lastrxformat = 0;
2373 rtp->dtmfsamples = 0;
2378 char *ast_rtp_get_quality(struct ast_rtp *rtp, struct ast_rtp_quality *qual)
2382 *themssrc their ssrc
2384 *rxjitter our calculated jitter(rx)
2385 *rxcount no. received packets
2386 *txjitter reported jitter of the other end
2387 *txcount transmitted packets
2388 *rlp remote lost packets
2389 *rtt round trip time
2393 qual->local_ssrc = rtp->ssrc;
2394 qual->local_jitter = rtp->rxjitter;
2395 qual->local_count = rtp->rxcount;
2396 qual->remote_ssrc = rtp->themssrc;
2397 qual->remote_count = rtp->txcount;
2399 qual->local_lostpackets = rtp->rtcp->expected_prior - rtp->rtcp->received_prior;
2400 qual->remote_lostpackets = rtp->rtcp->reported_lost;
2401 qual->remote_jitter = rtp->rtcp->reported_jitter / 65536.0;
2402 qual->rtt = rtp->rtcp->rtt;
2406 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality),
2407 "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
2410 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2413 (double)rtp->rtcp->reported_jitter / 65536.0,
2415 rtp->rtcp->reported_lost,
2417 return rtp->rtcp->quality;
2419 return "<Unknown> - RTP/RTCP has already been destroyed";
2422 void ast_rtp_destroy(struct ast_rtp *rtp)
2424 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
2425 /*Print some info on the call here */
2426 ast_verbose(" RTP-stats\n");
2427 ast_verbose("* Our Receiver:\n");
2428 ast_verbose(" SSRC: %u\n", rtp->themssrc);
2429 ast_verbose(" Received packets: %u\n", rtp->rxcount);
2430 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
2431 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
2432 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
2433 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
2434 ast_verbose("* Our Sender:\n");
2435 ast_verbose(" SSRC: %u\n", rtp->ssrc);
2436 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2437 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
2438 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter / (unsigned int)65536.0);
2439 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
2440 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
2443 manager_event(EVENT_FLAG_REPORTING, "RTPReceiverStat", "SSRC: %u\r\n"
2444 "ReceivedPackets: %u\r\n"
2445 "LostPackets: %u\r\n"
2451 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2454 rtp->rtcp->rr_count);
2455 manager_event(EVENT_FLAG_REPORTING, "RTPSenderStat", "SSRC: %u\r\n"
2456 "SentPackets: %u\r\n"
2457 "LostPackets: %u\r\n"
2463 rtp->rtcp->reported_lost,
2464 rtp->rtcp->reported_jitter,
2465 rtp->rtcp->sr_count,
2468 ast_smoother_free(rtp->smoother);
2470 ast_io_remove(rtp->io, rtp->ioid);
2474 if (rtp->rtcp->schedid > 0)
2475 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2476 close(rtp->rtcp->s);
2477 ast_free(rtp->rtcp);
2481 ast_mutex_destroy(&rtp->bridge_lock);
2486 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2490 if (ast_tvzero(rtp->txcore)) {
2491 rtp->txcore = ast_tvnow();
2492 /* Round to 20ms for nice, pretty timestamps */
2493 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2495 /* Use previous txcore if available */
2496 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2497 ms = ast_tvdiff_ms(t, rtp->txcore);
2500 /* Use what we just got for next time */
2502 return (unsigned int) ms;
2505 /*! \brief Send begin frames for DTMF */
2506 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
2508 unsigned int *rtpheader;
2509 int hdrlen = 12, res = 0, i = 0, payload = 0;
2512 if ((digit <= '9') && (digit >= '0'))
2514 else if (digit == '*')
2516 else if (digit == '#')
2518 else if ((digit >= 'A') && (digit <= 'D'))
2519 digit = digit - 'A' + 12;
2520 else if ((digit >= 'a') && (digit <= 'd'))
2521 digit = digit - 'a' + 12;
2523 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2527 /* If we have no peer, return immediately */
2528 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2531 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
2533 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2534 rtp->send_duration = 160;
2536 /* Get a pointer to the header */
2537 rtpheader = (unsigned int *)data;
2538 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2539 rtpheader[1] = htonl(rtp->lastdigitts);
2540 rtpheader[2] = htonl(rtp->ssrc);
2542 for (i = 0; i < 2; i++) {
2543 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2544 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2546 ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
2547 ast_inet_ntoa(rtp->them.sin_addr),
2548 ntohs(rtp->them.sin_port), strerror(errno));
2549 if (rtp_debug_test_addr(&rtp->them))
2550 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2551 ast_inet_ntoa(rtp->them.sin_addr),
2552 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2553 /* Increment sequence number */
2555 /* Increment duration */
2556 rtp->send_duration += 160;
2557 /* Clear marker bit and set seqno */
2558 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2561 /* Since we received a begin, we can safely store the digit and disable any compensation */
2562 rtp->sending_digit = 1;
2563 rtp->send_digit = digit;
2564 rtp->send_payload = payload;
2569 /*! \brief Send continuation frame for DTMF */
2570 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
2572 unsigned int *rtpheader;
2573 int hdrlen = 12, res = 0;
2576 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2579 /* Setup packet to send */
2580 rtpheader = (unsigned int *)data;
2581 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2582 rtpheader[1] = htonl(rtp->lastdigitts);
2583 rtpheader[2] = htonl(rtp->ssrc);
2584 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2585 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2588 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2590 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2591 ast_inet_ntoa(rtp->them.sin_addr),
2592 ntohs(rtp->them.sin_port), strerror(errno));
2593 if (rtp_debug_test_addr(&rtp->them))
2594 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2595 ast_inet_ntoa(rtp->them.sin_addr),
2596 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2598 /* Increment sequence number */
2600 /* Increment duration */
2601 rtp->send_duration += 160;
2606 /*! \brief Send end packets for DTMF */
2607 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
2609 unsigned int *rtpheader;
2610 int hdrlen = 12, res = 0, i = 0;
2613 /* If no address, then bail out */
2614 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2617 if ((digit <= '9') && (digit >= '0'))
2619 else if (digit == '*')
2621 else if (digit == '#')
2623 else if ((digit >= 'A') && (digit <= 'D'))
2624 digit = digit - 'A' + 12;
2625 else if ((digit >= 'a') && (digit <= 'd'))
2626 digit = digit - 'a' + 12;
2628 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2632 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2634 rtpheader = (unsigned int *)data;
2635 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2636 rtpheader[1] = htonl(rtp->lastdigitts);
2637 rtpheader[2] = htonl(rtp->ssrc);
2638 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2640 rtpheader[3] |= htonl((1 << 23));
2641 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2642 /* Send 3 termination packets */
2643 for (i = 0; i < 3; i++) {
2644 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2646 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2647 ast_inet_ntoa(rtp->them.sin_addr),
2648 ntohs(rtp->them.sin_port), strerror(errno));
2649 if (rtp_debug_test_addr(&rtp->them))
2650 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2651 ast_inet_ntoa(rtp->them.sin_addr),
2652 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2654 rtp->sending_digit = 0;
2655 rtp->send_digit = 0;
2656 /* Increment lastdigitts */
2657 rtp->lastdigitts += 960;
2663 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
2664 int ast_rtcp_send_h261fur(void *data)
2666 struct ast_rtp *rtp = data;
2669 rtp->rtcp->sendfur = 1;
2670 res = ast_rtcp_write(data);
2675 /*! \brief Send RTCP sender's report */
2676 static int ast_rtcp_write_sr(const void *data)
2678 struct ast_rtp *rtp = (struct ast_rtp *)data;
2682 unsigned int now_lsw;
2683 unsigned int now_msw;
2684 unsigned int *rtcpheader;
2686 unsigned int extended;
2687 unsigned int expected;
2688 unsigned int expected_interval;
2689 unsigned int received_interval;
2692 struct timeval dlsr;
2695 /* Commented condition is always not NULL if rtp->rtcp is not NULL */
2696 if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
2699 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
2700 ast_verbose("RTCP SR transmission error, rtcp halted\n");
2701 if (rtp->rtcp->schedid > 0)
2702 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2703 rtp->rtcp->schedid = -1;
2707 gettimeofday(&now, NULL);
2708 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
2709 rtcpheader = (unsigned int *)bdata;
2710 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
2711 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
2712 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
2713 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
2714 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
2715 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
2718 extended = rtp->cycles + rtp->lastrxseqno;
2719 expected = extended - rtp->seedrxseqno + 1;
2720 if (rtp->rxcount > expected)
2721 expected += rtp->rxcount - expected;
2722 lost = expected - rtp->rxcount;
2723 expected_interval = expected - rtp->rtcp->expected_prior;
2724 rtp->rtcp->expected_prior = expected;
2725 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2726 rtp->rtcp->received_prior = rtp->rxcount;
2727 lost_interval = expected_interval - received_interval;
2728 if (expected_interval == 0 || lost_interval <= 0)
2731 fraction = (lost_interval << 8) / expected_interval;
2732 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2733 rtcpheader[7] = htonl(rtp->themssrc);
2734 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2735 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2736 rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
2737 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2738 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2741 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2743 if (rtp->rtcp->sendfur) {
2744 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2745 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
2747 rtp->rtcp->sendfur = 0;
2750 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2751 /* it can change mid call, and SDES can't) */
2752 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2753 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2754 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2757 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2759 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));
2760 if (rtp->rtcp->schedid > 0)
2761 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2762 rtp->rtcp->schedid = -1;
2766 /* FIXME Don't need to get a new one */
2767 gettimeofday(&rtp->rtcp->txlsr, NULL);
2768 rtp->rtcp->sr_count++;
2770 rtp->rtcp->lastsrtxcount = rtp->txcount;
2772 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2773 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2774 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
2775 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2776 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
2777 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2778 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
2779 ast_verbose(" Report block:\n");
2780 ast_verbose(" Fraction lost: %u\n", fraction);
2781 ast_verbose(" Cumulative loss: %u\n", lost);
2782 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
2783 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
2784 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2786 manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To %s:%d\r\n"
2788 "SentNTP: %u.%010u\r\n"
2790 "SentPackets: %u\r\n"
2791 "SentOctets: %u\r\n"
2793 "FractionLost: %u\r\n"
2794 "CumulativeLoss: %u\r\n"
2795 "IAJitter: %.4f\r\n"
2796 "TheirLastSR: %u\r\n"
2797 "DLSR: %4.4f (sec)\r\n",
2798 ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port),
2800 (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
2807 rtp->rtcp->themrxlsr,
2808 (double)(ntohl(rtcpheader[12])/65536.0));
2812 /*! \brief Send RTCP recipient's report */
2813 static int ast_rtcp_write_rr(const void *data)
2815 struct ast_rtp *rtp = (struct ast_rtp *)data;
2819 unsigned int extended;
2820 unsigned int expected;
2821 unsigned int expected_interval;
2822 unsigned int received_interval;
2825 unsigned int *rtcpheader;
2827 struct timeval dlsr;
2830 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2833 if (!rtp->rtcp->them.sin_addr.s_addr) {
2834 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
2835 if (rtp->rtcp->schedid > 0)
2836 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2837 rtp->rtcp->schedid = -1;
2841 extended = rtp->cycles + rtp->lastrxseqno;
2842 expected = extended - rtp->seedrxseqno + 1;
2843 lost = expected - rtp->rxcount;
2844 expected_interval = expected - rtp->rtcp->expected_prior;
2845 rtp->rtcp->expected_prior = expected;
2846 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2847 rtp->rtcp->received_prior = rtp->rxcount;
2848 lost_interval = expected_interval - received_interval;
2849 if (expected_interval == 0 || lost_interval <= 0)
2852 fraction = (lost_interval << 8) / expected_interval;
2853 gettimeofday(&now, NULL);
2854 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2855 rtcpheader = (unsigned int *)bdata;
2856 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2857 rtcpheader[1] = htonl(rtp->ssrc);
2858 rtcpheader[2] = htonl(rtp->themssrc);
2859 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2860 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2861 rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
2862 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2863 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2865 if (rtp->rtcp->sendfur) {
2866 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2867 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
2869 rtp->rtcp->sendfur = 0;
2872 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2873 it can change mid call, and SDES can't) */
2874 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2875 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2876 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2879 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2882 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2883 /* Remove the scheduler */
2884 if (rtp->rtcp->schedid > 0)
2885 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2886 rtp->rtcp->schedid = -1;
2890 rtp->rtcp->rr_count++;
2892 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2893 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2894 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2895 " IA jitter: %.4f\n"
2896 " Their last SR: %u\n"
2897 " DLSR: %4.4f (sec)\n\n",
2898 ast_inet_ntoa(rtp->rtcp->them.sin_addr),
2899 ntohs(rtp->rtcp->them.sin_port),
2900 rtp->ssrc, rtp->themssrc, fraction, lost,
2902 rtp->rtcp->themrxlsr,
2903 (double)(ntohl(rtcpheader[7])/65536.0));
2909 /*! \brief Write and RTCP packet to the far end
2910 * \note Decide if we are going to send an SR (with Reception Block) or RR
2911 * RR is sent if we have not sent any rtp packets in the previous interval */
2912 static int ast_rtcp_write(const void *data)
2914 struct ast_rtp *rtp = (struct ast_rtp *)data;
2917 if (!rtp || !rtp->rtcp)
2920 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2921 res = ast_rtcp_write_sr(data);
2923 res = ast_rtcp_write_rr(data);
2928 /*! \brief generate comfort noice (CNG) */
2929 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2931 unsigned int *rtpheader;
2936 level = 127 - (level & 0x7f);
2937 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2939 /* If we have no peer, return immediately */
2940 if (!rtp->them.sin_addr.s_addr)
2943 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2945 /* Get a pointer to the header */
2946 rtpheader = (unsigned int *)data;
2947 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2948 rtpheader[1] = htonl(rtp->lastts);
2949 rtpheader[2] = htonl(rtp->ssrc);
2951 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2952 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2954 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));
2955 if (rtp_debug_test_addr(&rtp->them))
2956 ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
2957 , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
2963 /*! \brief Write RTP packet with audio or video media frames into UDP packet */
2964 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2966 unsigned char *rtpheader;
2973 ms = calc_txstamp(rtp, &f->delivery);
2974 /* Default prediction */
2975 if (f->subclass & AST_FORMAT_AUDIO_MASK) {
2976 pred = rtp->lastts + f->samples;
2978 /* Re-calculate last TS */
2979 rtp->lastts = rtp->lastts + ms * 8;
2980 if (ast_tvzero(f->delivery)) {
2981 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
2982 and if so, go with our prediction */
2983 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
2986 ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2990 } else if(f->subclass & AST_FORMAT_VIDEO_MASK) {
2991 mark = f->subclass & 0x1;
2992 pred = rtp->lastovidtimestamp + f->samples;
2993 /* Re-calculate last TS */
2994 rtp->lastts = rtp->lastts + ms * 90;
2995 /* If it's close to our prediction, go for it */
2996 if (ast_tvzero(f->delivery)) {
2997 if (abs(rtp->lastts - pred) < 7200) {
2999 rtp->lastovidtimestamp += f->samples;
3001 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);
3002 rtp->lastovidtimestamp = rtp->lastts;
3006 pred = rtp->lastotexttimestamp + f->samples;
3007 /* Re-calculate last TS */
3008 rtp->lastts = rtp->lastts + ms * 90;
3009 /* If it's close to our prediction, go for it */
3010 if (ast_tvzero(f->delivery)) {
3011 if (abs(rtp->lastts - pred) < 7200) {
3013 rtp->lastotexttimestamp += f->samples;
3015 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);
3016 rtp->lastotexttimestamp = rtp->lastts;
3020 /* If the timestamp for non-digit packets has moved beyond the timestamp
3021 for digits, update the digit timestamp.
3023 if (rtp->lastts > rtp->lastdigitts)
3024 rtp->lastdigitts = rtp->lastts;
3026 if (f->has_timing_info)
3027 rtp->lastts = f->ts * 8;
3029 /* Get a pointer to the header */
3030 rtpheader = (unsigned char *)(f->data - hdrlen);
3032 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
3033 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
3034 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
3036 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
3037 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
3039 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
3040 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));
3041 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
3042 /* Only give this error message once if we are not RTP debugging */
3043 if (option_debug || rtpdebug)
3044 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));
3045 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
3049 rtp->txoctetcount +=(res - hdrlen);
3051 if (rtp->rtcp && rtp->rtcp->schedid < 1)
3052 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
3055 if (rtp_debug_test_addr(&rtp->them))
3056 ast_verbose("Sent RTP packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3057 ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
3065 int ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
3068 for (x = 0; x < 32; x++) { /* Ugly way */
3069 rtp->pref.order[x] = prefs->order[x];
3070 rtp->pref.framing[x] = prefs->framing[x];
3073 ast_smoother_free(rtp->smoother);
3074 rtp->smoother = NULL;
3078 struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
3083 int ast_rtp_codec_getformat(int pt)
3085 if (pt < 0 || pt > MAX_RTP_PT)
3086 return 0; /* bogus payload type */
3088 if (static_RTP_PT[pt].isAstFormat)
3089 return static_RTP_PT[pt].code;
3094 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
3096 struct ast_frame *f;
3102 /* If we have no peer, return immediately */
3103 if (!rtp->them.sin_addr.s_addr)
3106 /* If there is no data length, return immediately */
3110 /* Make sure we have enough space for RTP header */
3111 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO) && (_f->frametype != AST_FRAME_TEXT)) {
3112 ast_log(LOG_WARNING, "RTP can only send voice, video and text\n");
3116 /* The bottom bit of a video subclass contains the marker bit */
3117 subclass = _f->subclass;
3118 if (_f->frametype == AST_FRAME_VIDEO)
3121 codec = ast_rtp_lookup_code(rtp, 1, subclass);
3123 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
3127 if (rtp->lasttxformat != subclass) {
3128 /* New format, reset the smoother */
3129 ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
3130 rtp->lasttxformat = subclass;
3132 ast_smoother_free(rtp->smoother);
3133 rtp->smoother = NULL;
3136 if (!rtp->smoother && subclass != AST_FORMAT_SPEEX && subclass != AST_FORMAT_G723_1) {
3137 struct ast_format_list fmt = ast_codec_pref_getsize(&rtp->pref, subclass);
3138 if (fmt.inc_ms) { /* if codec parameters is set / avoid division by zero */
3139 if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {