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 coming in is not one of the negotiated ones then send it to the core, this will cause formats to change and the bridge to break */
1326 if (!bridged->current_RTP_PT[payload].code)
1329 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
1330 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
1333 /* Otherwise adjust bridged payload to match */
1334 bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
1336 /* If the mark bit has not been sent yet... do it now */
1337 if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
1339 ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
1342 /* Reconstruct part of the packet */
1343 reconstruct &= 0xFF80FFFF;
1344 reconstruct |= (bridged_payload << 16);
1345 reconstruct |= (mark << 23);
1346 rtpheader[0] = htonl(reconstruct);
1348 /* Send the packet back out */
1349 res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
1351 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1352 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));
1353 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1354 if (option_debug || rtpdebug)
1355 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));
1356 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1359 } else if (rtp_debug_test_addr(&bridged->them))
1360 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);
1365 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
1368 struct sockaddr_in sin;
1379 unsigned int timestamp;
1380 unsigned int *rtpheader;
1381 struct rtpPayloadType rtpPT;
1382 struct ast_rtp *bridged = NULL;
1384 /* If time is up, kill it */
1385 if (rtp->sending_digit)
1386 ast_rtp_senddigit_continuation(rtp);
1390 /* Cache where the header will go */
1391 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
1392 0, (struct sockaddr *)&sin, &len);
1394 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
1398 if (errno != EAGAIN) {
1399 ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
1402 return &ast_null_frame;
1406 ast_log(LOG_WARNING, "RTP Read too short\n");
1407 return &ast_null_frame;
1411 seqno = ntohl(rtpheader[0]);
1413 /* Check RTP version */
1414 version = (seqno & 0xC0000000) >> 30;
1416 /* If the two high bits are 0, this might be a
1417 * STUN message, so process it. stun_handle_packet()
1418 * answers to requests, and it returns STUN_ACCEPT
1419 * if the request is valid.
1421 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == STUN_ACCEPT) &&
1422 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
1423 memcpy(&rtp->them, &sin, sizeof(rtp->them));
1425 return &ast_null_frame;
1428 #if 0 /* Allow to receive RTP stream with closed transmission path */
1429 /* If we don't have the other side's address, then ignore this */
1430 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1431 return &ast_null_frame;
1434 /* Send to whoever send to us if NAT is turned on */
1436 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1437 (rtp->them.sin_port != sin.sin_port)) {
1440 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1441 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1444 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1445 if (option_debug || rtpdebug)
1446 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));
1450 /* If we are bridged to another RTP stream, send direct */
1451 if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
1452 return &ast_null_frame;
1455 return &ast_null_frame;
1457 payloadtype = (seqno & 0x7f0000) >> 16;
1458 padding = seqno & (1 << 29);
1459 mark = seqno & (1 << 23);
1460 ext = seqno & (1 << 28);
1461 cc = (seqno & 0xF000000) >> 24;
1463 timestamp = ntohl(rtpheader[1]);
1464 ssrc = ntohl(rtpheader[2]);
1466 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1467 if (option_debug || rtpdebug)
1468 ast_debug(0, "Forcing Marker bit, because SSRC has changed\n");
1475 /* Remove padding bytes */
1476 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1480 /* CSRC fields present */
1485 /* RTP Extension present */
1486 hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
1490 profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
1491 if (profile == 0x505a)
1492 ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
1494 ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
1499 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1500 return &ast_null_frame;
1503 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1505 if (rtp->rxcount==1) {
1506 /* This is the first RTP packet successfully received from source */
1507 rtp->seedrxseqno = seqno;
1510 /* Do not schedule RR if RTCP isn't run */
1511 if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
1512 /* Schedule transmission of Receiver Report */
1513 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1515 if ( (int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
1516 rtp->cycles += RTP_SEQ_MOD;
1518 rtp->lastrxseqno = seqno;
1520 if (rtp->themssrc==0)
1521 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1523 if (rtp_debug_test_addr(&sin))
1524 ast_verbose("Got RTP packet from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1525 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1527 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1528 if (!rtpPT.isAstFormat) {
1529 struct ast_frame *f = NULL;
1531 /* This is special in-band data that's not one of our codecs */
1532 if (rtpPT.code == AST_RTP_DTMF) {
1533 /* It's special -- rfc2833 process it */
1534 if (rtp_debug_test_addr(&sin)) {
1535 unsigned char *data;
1537 unsigned int event_end;
1538 unsigned int duration;
1539 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1540 event = ntohl(*((unsigned int *)(data)));
1542 event_end = ntohl(*((unsigned int *)(data)));
1545 duration = ntohl(*((unsigned int *)(data)));
1547 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);
1549 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp);
1550 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1551 /* It's really special -- process it the Cisco way */
1552 if (rtp->lastevent <= seqno || (rtp->lastevent >= 65530 && seqno <= 6)) {
1553 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1554 rtp->lastevent = seqno;
1556 } else if (rtpPT.code == AST_RTP_CN) {
1558 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1560 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1562 return f ? f : &ast_null_frame;
1564 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1565 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;
1568 rtp->lastrxts = timestamp;
1570 rtp->rxseqno = seqno;
1572 /* Record received timestamp as last received now */
1573 rtp->lastrxts = timestamp;
1576 rtp->f.datalen = res - hdrlen;
1577 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1578 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1579 rtp->f.seqno = seqno;
1580 if (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) {
1581 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1582 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1583 ast_frame_byteswap_be(&rtp->f);
1584 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1585 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1586 ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
1587 rtp->f.ts = timestamp / 8;
1588 rtp->f.len = rtp->f.samples / 8;
1589 } else if(rtp->f.subclass & AST_FORMAT_VIDEO_MASK) {
1590 /* Video -- samples is # of samples vs. 90000 */
1591 if (!rtp->lastividtimestamp)
1592 rtp->lastividtimestamp = timestamp;
1593 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1594 rtp->lastividtimestamp = timestamp;
1595 rtp->f.delivery.tv_sec = 0;
1596 rtp->f.delivery.tv_usec = 0;
1597 /* Pass the RTP marker bit as bit 0 in the subclass field.
1598 * This is ok because subclass is actually a bitmask, and
1599 * the low bits represent audio formats, that are not
1600 * involved here since we deal with video.
1603 rtp->f.subclass |= 0x1;
1605 /* TEXT -- samples is # of samples vs. 1000 */
1606 if (!rtp->lastitexttimestamp)
1607 rtp->lastitexttimestamp = timestamp;
1608 rtp->f.samples = timestamp - rtp->lastitexttimestamp;
1609 rtp->lastitexttimestamp = timestamp;
1610 rtp->f.delivery.tv_sec = 0;
1611 rtp->f.delivery.tv_usec = 0;
1617 /* The following array defines the MIME Media type (and subtype) for each
1618 of our codecs, or RTP-specific data type. */
1620 struct rtpPayloadType payloadType;
1624 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1625 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1626 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1627 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1628 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1629 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1630 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1631 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1632 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1633 {{1, AST_FORMAT_G729A}, "audio", "G729A"},
1634 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1635 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1636 {{1, AST_FORMAT_G722}, "audio", "G722"},
1637 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
1638 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1639 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1640 {{0, AST_RTP_CN}, "audio", "CN"},
1641 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1642 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1643 {{1, AST_FORMAT_H261}, "video", "H261"},
1644 {{1, AST_FORMAT_H263}, "video", "H263"},
1645 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1646 {{1, AST_FORMAT_H264}, "video", "H264"},
1647 {{1, AST_FORMAT_MP4_VIDEO}, "video", "MP4V-ES"},
1648 {{1, AST_FORMAT_T140}, "text", "T140"},
1652 * \brief Mapping between Asterisk codecs and rtp payload types
1654 * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1655 * also, our own choices for dynamic payload types. This is our master
1656 * table for transmission
1658 * See http://www.iana.org/assignments/rtp-parameters for a list of
1661 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1662 [0] = {1, AST_FORMAT_ULAW},
1663 #ifdef USE_DEPRECATED_G726
1664 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1666 [3] = {1, AST_FORMAT_GSM},
1667 [4] = {1, AST_FORMAT_G723_1},
1668 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1669 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1670 [7] = {1, AST_FORMAT_LPC10},
1671 [8] = {1, AST_FORMAT_ALAW},
1672 [9] = {1, AST_FORMAT_G722},
1673 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1674 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1675 [13] = {0, AST_RTP_CN},
1676 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1677 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1678 [18] = {1, AST_FORMAT_G729A},
1679 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1680 [26] = {1, AST_FORMAT_JPEG},
1681 [31] = {1, AST_FORMAT_H261},
1682 [34] = {1, AST_FORMAT_H263},
1683 [97] = {1, AST_FORMAT_ILBC},
1684 [98] = {1, AST_FORMAT_H263_PLUS},
1685 [99] = {1, AST_FORMAT_H264},
1686 [101] = {0, AST_RTP_DTMF},
1687 [102] = {1, AST_FORMAT_T140}, /* Real time text chat */
1688 [103] = {1, AST_FORMAT_H263_PLUS},
1689 [104] = {1, AST_FORMAT_MP4_VIDEO},
1690 [110] = {1, AST_FORMAT_SPEEX},
1691 [111] = {1, AST_FORMAT_G726},
1692 [112] = {1, AST_FORMAT_G726_AAL2},
1693 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1696 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1703 rtp_bridge_lock(rtp);
1705 for (i = 0; i < MAX_RTP_PT; ++i) {
1706 rtp->current_RTP_PT[i].isAstFormat = 0;
1707 rtp->current_RTP_PT[i].code = 0;
1710 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1711 rtp->rtp_lookup_code_cache_code = 0;
1712 rtp->rtp_lookup_code_cache_result = 0;
1714 rtp_bridge_unlock(rtp);
1717 void ast_rtp_pt_default(struct ast_rtp* rtp)
1721 rtp_bridge_lock(rtp);
1723 /* Initialize to default payload types */
1724 for (i = 0; i < MAX_RTP_PT; ++i) {
1725 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1726 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1729 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1730 rtp->rtp_lookup_code_cache_code = 0;
1731 rtp->rtp_lookup_code_cache_result = 0;
1733 rtp_bridge_unlock(rtp);
1736 void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
1740 rtp_bridge_lock(dest);
1741 rtp_bridge_lock(src);
1743 for (i=0; i < MAX_RTP_PT; ++i) {
1744 dest->current_RTP_PT[i].isAstFormat =
1745 src->current_RTP_PT[i].isAstFormat;
1746 dest->current_RTP_PT[i].code =
1747 src->current_RTP_PT[i].code;
1749 dest->rtp_lookup_code_cache_isAstFormat = 0;
1750 dest->rtp_lookup_code_cache_code = 0;
1751 dest->rtp_lookup_code_cache_result = 0;
1753 rtp_bridge_unlock(src);
1754 rtp_bridge_unlock(dest);
1757 /*! \brief Get channel driver interface structure */
1758 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1760 struct ast_rtp_protocol *cur = NULL;
1762 AST_RWLIST_RDLOCK(&protos);
1763 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1764 if (cur->type == chan->tech->type)
1767 AST_RWLIST_UNLOCK(&protos);
1772 int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1774 // dest = c0, src = c1
1775 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1776 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1777 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
1778 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1779 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;
1780 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;
1781 int srccodec, destcodec, nat_active = 0;
1784 ast_channel_lock(c0);
1786 while (ast_channel_trylock(c1)) {
1787 ast_channel_unlock(c0);
1789 ast_channel_lock(c0);
1793 /* Find channel driver interfaces */
1794 destpr = get_proto(c0);
1796 srcpr = get_proto(c1);
1798 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c0->name);
1799 ast_channel_unlock(c0);
1801 ast_channel_unlock(c1);
1805 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
1806 ast_channel_unlock(c0);
1808 ast_channel_unlock(c1);
1812 /* Get audio, video and text interface (if native bridge is possible) */
1813 audio_dest_res = destpr->get_rtp_info(c0, &destp);
1814 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
1815 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(c0, &tdestp) : AST_RTP_GET_FAILED;
1817 audio_src_res = srcpr->get_rtp_info(c1, &srcp);
1818 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
1819 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(c1, &tsrcp) : AST_RTP_GET_FAILED;
1822 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1823 if (audio_dest_res != AST_RTP_TRY_NATIVE) {
1824 /* Somebody doesn't want to play... */
1825 ast_channel_unlock(c0);
1827 ast_channel_unlock(c1);
1830 if (audio_src_res == AST_RTP_TRY_NATIVE && srcpr->get_codec)
1831 srccodec = srcpr->get_codec(c1);
1834 if (audio_dest_res == AST_RTP_TRY_NATIVE && destpr->get_codec)
1835 destcodec = destpr->get_codec(c0);
1838 /* Ensure we have at least one matching codec */
1839 if (!(srccodec & destcodec)) {
1840 ast_channel_unlock(c0);
1842 ast_channel_unlock(c1);
1845 /* Consider empty media as non-existant */
1846 if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
1848 if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1850 /* Bridge media early */
1851 if (destpr->set_rtp_peer(c0, srcp, vsrcp, tsrcp, srccodec, nat_active))
1852 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1853 ast_channel_unlock(c0);
1855 ast_channel_unlock(c1);
1856 ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1860 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1862 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1863 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1864 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
1865 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1866 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;
1867 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;
1868 int srccodec, destcodec;
1871 ast_channel_lock(dest);
1872 while (ast_channel_trylock(src)) {
1873 ast_channel_unlock(dest);
1875 ast_channel_lock(dest);
1878 /* Find channel driver interfaces */
1879 if (!(destpr = get_proto(dest))) {
1880 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1881 ast_channel_unlock(dest);
1882 ast_channel_unlock(src);
1885 if (!(srcpr = get_proto(src))) {
1886 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", src->name);
1887 ast_channel_unlock(dest);
1888 ast_channel_unlock(src);
1892 /* Get audio and video interface (if native bridge is possible) */
1893 audio_dest_res = destpr->get_rtp_info(dest, &destp);
1894 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
1895 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(dest, &tdestp) : AST_RTP_GET_FAILED;
1896 audio_src_res = srcpr->get_rtp_info(src, &srcp);
1897 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
1898 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(src, &tsrcp) : AST_RTP_GET_FAILED;
1900 /* Ensure we have at least one matching codec */
1901 if (srcpr->get_codec)
1902 srccodec = srcpr->get_codec(src);
1905 if (destpr->get_codec)
1906 destcodec = destpr->get_codec(dest);
1910 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1911 if (audio_dest_res != AST_RTP_TRY_NATIVE || audio_src_res != AST_RTP_TRY_NATIVE || !(srccodec & destcodec)) {
1912 /* Somebody doesn't want to play... */
1913 ast_channel_unlock(dest);
1914 ast_channel_unlock(src);
1917 ast_rtp_pt_copy(destp, srcp);
1918 if (vdestp && vsrcp)
1919 ast_rtp_pt_copy(vdestp, vsrcp);
1920 if (tdestp && tsrcp)
1921 ast_rtp_pt_copy(tdestp, tsrcp);
1924 if (destpr->set_rtp_peer(dest, srcp, vsrcp, tsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1925 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1927 ast_channel_unlock(dest);
1928 ast_channel_unlock(src);
1929 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1933 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1934 * By default, use the well-known value for this type (although it may
1935 * still be set to a different value by a subsequent "a=rtpmap:" line)
1937 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1939 if (pt < 0 || pt > MAX_RTP_PT || static_RTP_PT[pt].code == 0)
1940 return; /* bogus payload type */
1942 rtp_bridge_lock(rtp);
1943 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1944 rtp_bridge_unlock(rtp);
1947 /*! \brief remove setting from payload type list if the rtpmap header indicates
1948 an unknown media type */
1949 void ast_rtp_unset_m_type(struct ast_rtp* rtp, int pt)
1951 rtp_bridge_lock(rtp);
1952 rtp->current_RTP_PT[pt].isAstFormat = 0;
1953 rtp->current_RTP_PT[pt].code = 0;
1954 rtp_bridge_unlock(rtp);
1957 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1958 * an SDP "a=rtpmap:" line.
1959 * \return 0 if the MIME type was found and set, -1 if it wasn't found
1961 int ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
1962 char *mimeType, char *mimeSubtype,
1963 enum ast_rtp_options options)
1968 if (pt < 0 || pt > MAX_RTP_PT)
1969 return -1; /* bogus payload type */
1971 rtp_bridge_lock(rtp);
1973 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1974 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1975 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1977 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1978 if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
1979 mimeTypes[i].payloadType.isAstFormat &&
1980 (options & AST_RTP_OPT_G726_NONSTANDARD))
1981 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
1986 rtp_bridge_unlock(rtp);
1988 return (found ? 0 : -1);
1991 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
1992 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1993 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1994 int* astFormats, int* nonAstFormats)
1998 rtp_bridge_lock(rtp);
2000 *astFormats = *nonAstFormats = 0;
2001 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2002 if (rtp->current_RTP_PT[pt].isAstFormat) {
2003 *astFormats |= rtp->current_RTP_PT[pt].code;
2005 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
2009 rtp_bridge_unlock(rtp);
2014 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
2016 struct rtpPayloadType result;
2018 result.isAstFormat = result.code = 0;
2020 if (pt < 0 || pt > MAX_RTP_PT)
2021 return result; /* bogus payload type */
2023 /* Start with negotiated codecs */
2024 rtp_bridge_lock(rtp);
2025 result = rtp->current_RTP_PT[pt];
2026 rtp_bridge_unlock(rtp);
2028 /* If it doesn't exist, check our static RTP type list, just in case */
2030 result = static_RTP_PT[pt];
2035 /*! \brief Looks up an RTP code out of our *static* outbound list */
2036 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
2040 rtp_bridge_lock(rtp);
2042 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
2043 code == rtp->rtp_lookup_code_cache_code) {
2044 /* Use our cached mapping, to avoid the overhead of the loop below */
2045 pt = rtp->rtp_lookup_code_cache_result;
2046 rtp_bridge_unlock(rtp);
2050 /* Check the dynamic list first */
2051 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2052 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
2053 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2054 rtp->rtp_lookup_code_cache_code = code;
2055 rtp->rtp_lookup_code_cache_result = pt;
2056 rtp_bridge_unlock(rtp);
2061 /* Then the static list */
2062 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2063 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
2064 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2065 rtp->rtp_lookup_code_cache_code = code;
2066 rtp->rtp_lookup_code_cache_result = pt;
2067 rtp_bridge_unlock(rtp);
2072 rtp_bridge_unlock(rtp);
2077 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
2078 enum ast_rtp_options options)
2082 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
2083 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
2085 (code == AST_FORMAT_G726_AAL2) &&
2086 (options & AST_RTP_OPT_G726_NONSTANDARD))
2089 return mimeTypes[i].subtype;
2096 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
2097 const int isAstFormat, enum ast_rtp_options options)
2107 snprintf(end, size, "0x%x (", capability);
2114 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
2115 if (capability & format) {
2116 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
2118 snprintf(end, size, "%s|", name);
2126 ast_copy_string(start, "nothing)", size);
2133 /*! \brief Open RTP or RTCP socket for a session.
2134 * Print a message on failure.
2136 static int rtp_socket(const char *type)
2138 int s = socket(AF_INET, SOCK_DGRAM, 0);
2142 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
2144 long flags = fcntl(s, F_GETFL);
2145 fcntl(s, F_SETFL, flags | O_NONBLOCK);
2148 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
2155 * \brief Initialize a new RTCP session.
2157 * \returns The newly initialized RTCP session.
2159 static struct ast_rtcp *ast_rtcp_new(void)
2161 struct ast_rtcp *rtcp;
2163 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
2165 rtcp->s = rtp_socket("RTCP");
2166 rtcp->us.sin_family = AF_INET;
2167 rtcp->them.sin_family = AF_INET;
2178 * \brief Initialize a new RTP structure.
2181 void ast_rtp_new_init(struct ast_rtp *rtp)
2184 ast_mutex_init(&rtp->bridge_lock);
2187 rtp->them.sin_family = AF_INET;
2188 rtp->us.sin_family = AF_INET;
2189 rtp->ssrc = ast_random();
2190 rtp->seqno = ast_random() & 0xffff;
2191 ast_set_flag(rtp, FLAG_HAS_DTMF);
2196 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
2198 struct ast_rtp *rtp;
2202 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
2205 ast_rtp_new_init(rtp);
2207 rtp->s = rtp_socket("RTP");
2210 if (sched && rtcpenable) {
2212 rtp->rtcp = ast_rtcp_new();
2216 * Try to bind the RTP port, x, and possibly the RTCP port, x+1 as well.
2217 * Start from a random (even, by RTP spec) port number, and
2218 * iterate until success or no ports are available.
2219 * Note that the requirement of RTP port being even, or RTCP being the
2220 * next one, cannot be enforced in presence of a NAT box because the
2221 * mapping is not under our control.
2223 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
2224 x = x & ~1; /* make it an even number */
2225 startplace = x; /* remember the starting point */
2226 /* this is constant across the loop */
2227 rtp->us.sin_addr = addr;
2229 rtp->rtcp->us.sin_addr = addr;
2231 rtp->us.sin_port = htons(x);
2232 if (!bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) {
2233 /* bind succeeded, if no rtcp then we are done */
2236 /* have rtcp, try to bind it */
2237 rtp->rtcp->us.sin_port = htons(x + 1);
2238 if (!bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us)))
2239 break; /* success again, we are really done */
2241 * RTCP bind failed, so close and recreate the
2242 * already bound RTP socket for the next round.
2245 rtp->s = rtp_socket("RTP");
2250 * If we get here, there was an error in one of the bind()
2251 * calls, so make sure it is nothing unexpected.
2253 if (errno != EADDRINUSE) {
2254 /* We got an error that wasn't expected, abort! */
2255 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
2259 * One of the ports is in use. For the next iteration,
2260 * increment by two and handle wraparound.
2261 * If we reach the starting point, then declare failure.
2265 x = (rtpstart + 1) & ~1;
2266 if (x == startplace) {
2267 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
2274 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
2275 ast_set_flag(rtp, FLAG_CALLBACK_MODE);
2277 ast_rtp_pt_default(rtp);
2284 close(rtp->rtcp->s);
2285 ast_free(rtp->rtcp);
2291 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
2295 memset(&ia, 0, sizeof(ia));
2296 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
2299 int ast_rtp_setqos(struct ast_rtp *rtp, int tos, int cos, char *desc)
2301 return ast_netsock_set_qos(rtp->s, tos, cos, desc);
2304 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2306 rtp->them.sin_port = them->sin_port;
2307 rtp->them.sin_addr = them->sin_addr;
2309 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
2310 rtp->rtcp->them.sin_addr = them->sin_addr;
2315 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2317 if ((them->sin_family != AF_INET) ||
2318 (them->sin_port != rtp->them.sin_port) ||
2319 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
2320 them->sin_family = AF_INET;
2321 them->sin_port = rtp->them.sin_port;
2322 them->sin_addr = rtp->them.sin_addr;
2328 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
2333 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
2335 struct ast_rtp *bridged = NULL;
2337 rtp_bridge_lock(rtp);
2338 bridged = rtp->bridged;
2339 rtp_bridge_unlock(rtp);
2344 void ast_rtp_stop(struct ast_rtp *rtp)
2346 if (rtp->rtcp && rtp->rtcp->schedid > 0) {
2347 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2348 rtp->rtcp->schedid = -1;
2351 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
2352 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
2354 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
2355 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
2358 ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
2361 void ast_rtp_reset(struct ast_rtp *rtp)
2363 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
2364 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
2365 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
2367 rtp->lastdigitts = 0;
2369 rtp->lastividtimestamp = 0;
2370 rtp->lastovidtimestamp = 0;
2371 rtp->lastitexttimestamp = 0;
2372 rtp->lastotexttimestamp = 0;
2373 rtp->lasteventseqn = 0;
2375 rtp->lasttxformat = 0;
2376 rtp->lastrxformat = 0;
2378 rtp->dtmfsamples = 0;
2383 char *ast_rtp_get_quality(struct ast_rtp *rtp, struct ast_rtp_quality *qual)
2387 *themssrc their ssrc
2389 *rxjitter our calculated jitter(rx)
2390 *rxcount no. received packets
2391 *txjitter reported jitter of the other end
2392 *txcount transmitted packets
2393 *rlp remote lost packets
2394 *rtt round trip time
2398 qual->local_ssrc = rtp->ssrc;
2399 qual->local_jitter = rtp->rxjitter;
2400 qual->local_count = rtp->rxcount;
2401 qual->remote_ssrc = rtp->themssrc;
2402 qual->remote_count = rtp->txcount;
2404 qual->local_lostpackets = rtp->rtcp->expected_prior - rtp->rtcp->received_prior;
2405 qual->remote_lostpackets = rtp->rtcp->reported_lost;
2406 qual->remote_jitter = rtp->rtcp->reported_jitter / 65536.0;
2407 qual->rtt = rtp->rtcp->rtt;
2411 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality),
2412 "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
2415 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2418 (double)rtp->rtcp->reported_jitter / 65536.0,
2420 rtp->rtcp->reported_lost,
2422 return rtp->rtcp->quality;
2424 return "<Unknown> - RTP/RTCP has already been destroyed";
2427 void ast_rtp_destroy(struct ast_rtp *rtp)
2429 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
2430 /*Print some info on the call here */
2431 ast_verbose(" RTP-stats\n");
2432 ast_verbose("* Our Receiver:\n");
2433 ast_verbose(" SSRC: %u\n", rtp->themssrc);
2434 ast_verbose(" Received packets: %u\n", rtp->rxcount);
2435 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
2436 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
2437 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
2438 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
2439 ast_verbose("* Our Sender:\n");
2440 ast_verbose(" SSRC: %u\n", rtp->ssrc);
2441 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2442 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
2443 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter / (unsigned int)65536.0);
2444 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
2445 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
2448 manager_event(EVENT_FLAG_REPORTING, "RTPReceiverStat", "SSRC: %u\r\n"
2449 "ReceivedPackets: %u\r\n"
2450 "LostPackets: %u\r\n"
2456 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2459 rtp->rtcp->rr_count);
2460 manager_event(EVENT_FLAG_REPORTING, "RTPSenderStat", "SSRC: %u\r\n"
2461 "SentPackets: %u\r\n"
2462 "LostPackets: %u\r\n"
2468 rtp->rtcp->reported_lost,
2469 rtp->rtcp->reported_jitter,
2470 rtp->rtcp->sr_count,
2473 ast_smoother_free(rtp->smoother);
2475 ast_io_remove(rtp->io, rtp->ioid);
2479 if (rtp->rtcp->schedid > 0)
2480 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2481 close(rtp->rtcp->s);
2482 ast_free(rtp->rtcp);
2486 ast_mutex_destroy(&rtp->bridge_lock);
2491 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2495 if (ast_tvzero(rtp->txcore)) {
2496 rtp->txcore = ast_tvnow();
2497 /* Round to 20ms for nice, pretty timestamps */
2498 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2500 /* Use previous txcore if available */
2501 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2502 ms = ast_tvdiff_ms(t, rtp->txcore);
2505 /* Use what we just got for next time */
2507 return (unsigned int) ms;
2510 /*! \brief Send begin frames for DTMF */
2511 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
2513 unsigned int *rtpheader;
2514 int hdrlen = 12, res = 0, i = 0, payload = 0;
2517 if ((digit <= '9') && (digit >= '0'))
2519 else if (digit == '*')
2521 else if (digit == '#')
2523 else if ((digit >= 'A') && (digit <= 'D'))
2524 digit = digit - 'A' + 12;
2525 else if ((digit >= 'a') && (digit <= 'd'))
2526 digit = digit - 'a' + 12;
2528 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2532 /* If we have no peer, return immediately */
2533 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2536 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
2538 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2539 rtp->send_duration = 160;
2541 /* Get a pointer to the header */
2542 rtpheader = (unsigned int *)data;
2543 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2544 rtpheader[1] = htonl(rtp->lastdigitts);
2545 rtpheader[2] = htonl(rtp->ssrc);
2547 for (i = 0; i < 2; i++) {
2548 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2549 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2551 ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
2552 ast_inet_ntoa(rtp->them.sin_addr),
2553 ntohs(rtp->them.sin_port), strerror(errno));
2554 if (rtp_debug_test_addr(&rtp->them))
2555 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2556 ast_inet_ntoa(rtp->them.sin_addr),
2557 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2558 /* Increment sequence number */
2560 /* Increment duration */
2561 rtp->send_duration += 160;
2562 /* Clear marker bit and set seqno */
2563 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2566 /* Since we received a begin, we can safely store the digit and disable any compensation */
2567 rtp->sending_digit = 1;
2568 rtp->send_digit = digit;
2569 rtp->send_payload = payload;
2574 /*! \brief Send continuation frame for DTMF */
2575 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
2577 unsigned int *rtpheader;
2578 int hdrlen = 12, res = 0;
2581 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2584 /* Setup packet to send */
2585 rtpheader = (unsigned int *)data;
2586 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2587 rtpheader[1] = htonl(rtp->lastdigitts);
2588 rtpheader[2] = htonl(rtp->ssrc);
2589 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2590 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2593 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2595 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2596 ast_inet_ntoa(rtp->them.sin_addr),
2597 ntohs(rtp->them.sin_port), strerror(errno));
2598 if (rtp_debug_test_addr(&rtp->them))
2599 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2600 ast_inet_ntoa(rtp->them.sin_addr),
2601 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2603 /* Increment sequence number */
2605 /* Increment duration */
2606 rtp->send_duration += 160;
2611 /*! \brief Send end packets for DTMF */
2612 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
2614 unsigned int *rtpheader;
2615 int hdrlen = 12, res = 0, i = 0;
2618 /* If no address, then bail out */
2619 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2622 if ((digit <= '9') && (digit >= '0'))
2624 else if (digit == '*')
2626 else if (digit == '#')
2628 else if ((digit >= 'A') && (digit <= 'D'))
2629 digit = digit - 'A' + 12;
2630 else if ((digit >= 'a') && (digit <= 'd'))
2631 digit = digit - 'a' + 12;
2633 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2637 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2639 rtpheader = (unsigned int *)data;
2640 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2641 rtpheader[1] = htonl(rtp->lastdigitts);
2642 rtpheader[2] = htonl(rtp->ssrc);
2643 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2645 rtpheader[3] |= htonl((1 << 23));
2646 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2647 /* Send 3 termination packets */
2648 for (i = 0; i < 3; i++) {
2649 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2651 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2652 ast_inet_ntoa(rtp->them.sin_addr),
2653 ntohs(rtp->them.sin_port), strerror(errno));
2654 if (rtp_debug_test_addr(&rtp->them))
2655 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2656 ast_inet_ntoa(rtp->them.sin_addr),
2657 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2659 rtp->sending_digit = 0;
2660 rtp->send_digit = 0;
2661 /* Increment lastdigitts */
2662 rtp->lastdigitts += 960;
2668 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
2669 int ast_rtcp_send_h261fur(void *data)
2671 struct ast_rtp *rtp = data;
2674 rtp->rtcp->sendfur = 1;
2675 res = ast_rtcp_write(data);
2680 /*! \brief Send RTCP sender's report */
2681 static int ast_rtcp_write_sr(const void *data)
2683 struct ast_rtp *rtp = (struct ast_rtp *)data;
2687 unsigned int now_lsw;
2688 unsigned int now_msw;
2689 unsigned int *rtcpheader;
2691 unsigned int extended;
2692 unsigned int expected;
2693 unsigned int expected_interval;
2694 unsigned int received_interval;
2697 struct timeval dlsr;
2700 /* Commented condition is always not NULL if rtp->rtcp is not NULL */
2701 if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
2704 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
2705 ast_verbose("RTCP SR transmission error, rtcp halted\n");
2706 if (rtp->rtcp->schedid > 0)
2707 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2708 rtp->rtcp->schedid = -1;
2712 gettimeofday(&now, NULL);
2713 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
2714 rtcpheader = (unsigned int *)bdata;
2715 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
2716 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
2717 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
2718 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
2719 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
2720 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
2723 extended = rtp->cycles + rtp->lastrxseqno;
2724 expected = extended - rtp->seedrxseqno + 1;
2725 if (rtp->rxcount > expected)
2726 expected += rtp->rxcount - expected;
2727 lost = expected - rtp->rxcount;
2728 expected_interval = expected - rtp->rtcp->expected_prior;
2729 rtp->rtcp->expected_prior = expected;
2730 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2731 rtp->rtcp->received_prior = rtp->rxcount;
2732 lost_interval = expected_interval - received_interval;
2733 if (expected_interval == 0 || lost_interval <= 0)
2736 fraction = (lost_interval << 8) / expected_interval;
2737 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2738 rtcpheader[7] = htonl(rtp->themssrc);
2739 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2740 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2741 rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
2742 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2743 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2746 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2748 if (rtp->rtcp->sendfur) {
2749 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2750 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
2752 rtp->rtcp->sendfur = 0;
2755 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2756 /* it can change mid call, and SDES can't) */
2757 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2758 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2759 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2762 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2764 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));
2765 if (rtp->rtcp->schedid > 0)
2766 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2767 rtp->rtcp->schedid = -1;
2771 /* FIXME Don't need to get a new one */
2772 gettimeofday(&rtp->rtcp->txlsr, NULL);
2773 rtp->rtcp->sr_count++;
2775 rtp->rtcp->lastsrtxcount = rtp->txcount;
2777 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2778 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2779 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
2780 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2781 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
2782 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2783 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
2784 ast_verbose(" Report block:\n");
2785 ast_verbose(" Fraction lost: %u\n", fraction);
2786 ast_verbose(" Cumulative loss: %u\n", lost);
2787 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
2788 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
2789 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2791 manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To %s:%d\r\n"
2793 "SentNTP: %u.%010u\r\n"
2795 "SentPackets: %u\r\n"
2796 "SentOctets: %u\r\n"
2798 "FractionLost: %u\r\n"
2799 "CumulativeLoss: %u\r\n"
2800 "IAJitter: %.4f\r\n"
2801 "TheirLastSR: %u\r\n"
2802 "DLSR: %4.4f (sec)\r\n",
2803 ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port),
2805 (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
2812 rtp->rtcp->themrxlsr,
2813 (double)(ntohl(rtcpheader[12])/65536.0));
2817 /*! \brief Send RTCP recipient's report */
2818 static int ast_rtcp_write_rr(const void *data)
2820 struct ast_rtp *rtp = (struct ast_rtp *)data;
2824 unsigned int extended;
2825 unsigned int expected;
2826 unsigned int expected_interval;
2827 unsigned int received_interval;
2830 unsigned int *rtcpheader;
2832 struct timeval dlsr;
2835 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2838 if (!rtp->rtcp->them.sin_addr.s_addr) {
2839 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
2840 if (rtp->rtcp->schedid > 0)
2841 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2842 rtp->rtcp->schedid = -1;
2846 extended = rtp->cycles + rtp->lastrxseqno;
2847 expected = extended - rtp->seedrxseqno + 1;
2848 lost = expected - rtp->rxcount;
2849 expected_interval = expected - rtp->rtcp->expected_prior;
2850 rtp->rtcp->expected_prior = expected;
2851 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2852 rtp->rtcp->received_prior = rtp->rxcount;
2853 lost_interval = expected_interval - received_interval;
2854 if (expected_interval == 0 || lost_interval <= 0)
2857 fraction = (lost_interval << 8) / expected_interval;
2858 gettimeofday(&now, NULL);
2859 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2860 rtcpheader = (unsigned int *)bdata;
2861 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2862 rtcpheader[1] = htonl(rtp->ssrc);
2863 rtcpheader[2] = htonl(rtp->themssrc);
2864 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2865 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2866 rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
2867 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2868 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2870 if (rtp->rtcp->sendfur) {
2871 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2872 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
2874 rtp->rtcp->sendfur = 0;
2877 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2878 it can change mid call, and SDES can't) */
2879 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2880 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2881 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2884 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2887 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2888 /* Remove the scheduler */
2889 if (rtp->rtcp->schedid > 0)
2890 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2891 rtp->rtcp->schedid = -1;
2895 rtp->rtcp->rr_count++;
2897 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2898 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2899 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2900 " IA jitter: %.4f\n"
2901 " Their last SR: %u\n"
2902 " DLSR: %4.4f (sec)\n\n",
2903 ast_inet_ntoa(rtp->rtcp->them.sin_addr),
2904 ntohs(rtp->rtcp->them.sin_port),
2905 rtp->ssrc, rtp->themssrc, fraction, lost,
2907 rtp->rtcp->themrxlsr,
2908 (double)(ntohl(rtcpheader[7])/65536.0));
2914 /*! \brief Write and RTCP packet to the far end
2915 * \note Decide if we are going to send an SR (with Reception Block) or RR
2916 * RR is sent if we have not sent any rtp packets in the previous interval */
2917 static int ast_rtcp_write(const void *data)
2919 struct ast_rtp *rtp = (struct ast_rtp *)data;
2922 if (!rtp || !rtp->rtcp)
2925 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2926 res = ast_rtcp_write_sr(data);
2928 res = ast_rtcp_write_rr(data);
2933 /*! \brief generate comfort noice (CNG) */
2934 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2936 unsigned int *rtpheader;
2941 level = 127 - (level & 0x7f);
2942 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2944 /* If we have no peer, return immediately */
2945 if (!rtp->them.sin_addr.s_addr)
2948 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2950 /* Get a pointer to the header */
2951 rtpheader = (unsigned int *)data;
2952 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2953 rtpheader[1] = htonl(rtp->lastts);
2954 rtpheader[2] = htonl(rtp->ssrc);
2956 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2957 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2959 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));
2960 if (rtp_debug_test_addr(&rtp->them))
2961 ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
2962 , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
2968 /*! \brief Write RTP packet with audio or video media frames into UDP packet */
2969 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2971 unsigned char *rtpheader;
2978 ms = calc_txstamp(rtp, &f->delivery);
2979 /* Default prediction */
2980 if (f->subclass & AST_FORMAT_AUDIO_MASK) {
2981 pred = rtp->lastts + f->samples;
2983 /* Re-calculate last TS */
2984 rtp->lastts = rtp->lastts + ms * 8;
2985 if (ast_tvzero(f->delivery)) {
2986 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
2987 and if so, go with our prediction */
2988 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
2991 ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2995 } else if(f->subclass & AST_FORMAT_VIDEO_MASK) {
2996 mark = f->subclass & 0x1;
2997 pred = rtp->lastovidtimestamp + f->samples;
2998 /* Re-calculate last TS */
2999 rtp->lastts = rtp->lastts + ms * 90;
3000 /* If it's close to our prediction, go for it */
3001 if (ast_tvzero(f->delivery)) {
3002 if (abs(rtp->lastts - pred) < 7200) {
3004 rtp->lastovidtimestamp += f->samples;
3006 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);
3007 rtp->lastovidtimestamp = rtp->lastts;
3011 pred = rtp->lastotexttimestamp + f->samples;
3012 /* Re-calculate last TS */
3013 rtp->lastts = rtp->lastts + ms * 90;
3014 /* If it's close to our prediction, go for it */
3015 if (ast_tvzero(f->delivery)) {
3016 if (abs(rtp->lastts - pred) < 7200) {
3018 rtp->lastotexttimestamp += f->samples;
3020 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);
3021 rtp->lastotexttimestamp = rtp->lastts;
3025 /* If the timestamp for non-digit packets has moved beyond the timestamp
3026 for digits, update the digit timestamp.
3028 if (rtp->lastts > rtp->lastdigitts)
3029 rtp->lastdigitts = rtp->lastts;
3031 if (ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO))
3032 rtp->lastts = f->ts * 8;
3034 /* Get a pointer to the header */
3035 rtpheader = (unsigned char *)(f->data - hdrlen);
3037 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
3038 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
3039 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
3041 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
3042 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
3044 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
3045 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));
3046 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
3047 /* Only give this error message once if we are not RTP debugging */
3048 if (option_debug || rtpdebug)
3049 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));
3050 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
3054 rtp->txoctetcount +=(res - hdrlen);
3056 if (rtp->rtcp && rtp->rtcp->schedid < 1)
3057 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
3060 if (rtp_debug_test_addr(&rtp->them))
3061 ast_verbose("Sent RTP packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3062 ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
3070 int ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
3073 for (x = 0; x < 32; x++) { /* Ugly way */
3074 rtp->pref.order[x] = prefs->order[x];
3075 rtp->pref.framing[x] = prefs->framing[x];
3078 ast_smoother_free(rtp->smoother);
3079 rtp->smoother = NULL;
3083 struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
3088 int ast_rtp_codec_getformat(int pt)
3090 if (pt < 0 || pt > MAX_RTP_PT)
3091 return 0; /* bogus payload type */
3093 if (static_RTP_PT[pt].isAstFormat)
3094 return static_RTP_PT[pt].code;
3099 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
3101 struct ast_frame *f;
3107 /* If we have no peer, return immediately */
3108 if (!rtp->them.sin_addr.s_addr)
3111 /* If there is no data length, return immediately */
3115 /* Make sure we have enough space for RTP header */
3116 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO) && (_f->frametype != AST_FRAME_TEXT)) {
3117 ast_log(LOG_WARNING, "RTP can only send voice, video and text\n");
3121 /* The bottom bit of a video subclass contains the marker bit */
3122 subclass = _f->subclass;
3123 if (_f->frametype == AST_FRAME_VIDEO)
3126 codec = ast_rtp_lookup_code(rtp, 1, subclass);
3128 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
3132 if (rtp->lasttxformat != subclass) {
3133 /* New format, reset the smoother */
3134 ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
3135 rtp->lasttxformat = subclass;
3137 ast_smoother_free(rtp->smoother);
3138 rtp->smoother = NULL;