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$")
40 #include <netinet/in.h>
42 #include <sys/socket.h>
43 #include <arpa/inet.h>
46 #include "asterisk/rtp.h"
47 #include "asterisk/frame.h"
48 #include "asterisk/logger.h"
49 #include "asterisk/options.h"
50 #include "asterisk/channel.h"
51 #include "asterisk/acl.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/config.h"
54 #include "asterisk/lock.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/netsock.h"
57 #include "asterisk/cli.h"
58 #include "asterisk/manager.h"
59 #include "asterisk/unaligned.h"
60 #include "asterisk/utils.h"
62 #define MAX_TIMESTAMP_SKEW 640
64 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
65 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
66 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
67 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
69 #define RTCP_PT_FUR 192
70 #define RTCP_PT_SR 200
71 #define RTCP_PT_RR 201
72 #define RTCP_PT_SDES 202
73 #define RTCP_PT_BYE 203
74 #define RTCP_PT_APP 204
78 #define DEFAULT_DTMF_TIMEOUT 3000 /*!< samples */
80 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
82 static int rtpstart; /*!< First port for RTP sessions (set in rtp.conf) */
83 static int rtpend; /*!< Last port for RTP sessions (set in rtp.conf) */
84 static int rtpdebug; /*!< Are we debugging? */
85 static int rtcpdebug; /*!< Are we debugging RTCP? */
86 static int rtcpstats; /*!< Are we debugging RTCP? */
87 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
88 static int stundebug; /*!< Are we debugging stun? */
89 static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
90 static struct sockaddr_in rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
92 static int nochecksums;
95 /* Uncomment this to enable more intense native bridging, but note: this is currently buggy */
96 /* #define P2P_INTENSE */
99 * \brief Structure representing a RTP session.
101 * 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 [...]"
104 /*! \brief The value of each payload format mapping: */
105 struct rtpPayloadType {
106 int isAstFormat; /*!< whether the following code is an AST_FORMAT */
111 /*! \brief RTP session description */
115 unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
116 unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
117 unsigned int themssrc; /*!< Their SSRC */
120 unsigned int lastrxts;
121 unsigned int lastividtimestamp;
122 unsigned int lastovidtimestamp;
123 unsigned int lastitexttimestamp;
124 unsigned int lastotexttimestamp;
125 unsigned int lasteventseqn;
126 int lastrxseqno; /*!< Last received sequence number */
127 unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
128 unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
129 unsigned int rxcount; /*!< How many packets have we received? */
130 unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
131 unsigned int txcount; /*!< How many packets have we sent? */
132 unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
133 unsigned int cycles; /*!< Shifted count of sequence number cycles */
134 double rxjitter; /*!< Interarrival jitter at the moment */
135 double rxtransit; /*!< Relative transit time for previous packet */
139 int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
140 int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
141 int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
143 /* DTMF Reception Variables */
145 unsigned int lastevent;
147 unsigned int dtmfsamples;
148 /* DTMF Transmission Variables */
149 unsigned int lastdigitts;
150 char sending_digit; /*!< boolean - are we sending digits */
151 char send_digit; /*!< digit we are sending */
156 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
157 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
158 struct timeval rxcore;
159 struct timeval txcore;
160 double drxcore; /*!< The double representation of the first received packet */
161 struct timeval lastrx; /*!< timeval when we last received a packet */
162 struct timeval dtmfmute;
163 struct ast_smoother *smoother;
165 unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
166 unsigned short rxseqno;
167 struct sched_context *sched;
168 struct io_context *io;
170 ast_rtp_callback callback;
172 ast_mutex_t bridge_lock;
174 struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
175 int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
176 int rtp_lookup_code_cache_code;
177 int rtp_lookup_code_cache_result;
178 struct ast_rtcp *rtcp;
179 struct ast_codec_pref pref;
180 struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
183 /* Forward declarations */
184 static int ast_rtcp_write(const void *data);
185 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
186 static int ast_rtcp_write_sr(const void *data);
187 static int ast_rtcp_write_rr(const void *data);
188 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
189 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
190 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
192 #define FLAG_3389_WARNING (1 << 0)
193 #define FLAG_NAT_ACTIVE (3 << 1)
194 #define FLAG_NAT_INACTIVE (0 << 1)
195 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
196 #define FLAG_HAS_DTMF (1 << 3)
197 #define FLAG_P2P_SENT_MARK (1 << 4)
198 #define FLAG_P2P_NEED_DTMF (1 << 5)
199 #define FLAG_CALLBACK_MODE (1 << 6)
200 #define FLAG_DTMF_COMPENSATE (1 << 7)
201 #define FLAG_HAS_STUN (1 << 8)
204 * \brief Structure defining an RTCP session.
206 * The concept "RTCP session" is not defined in RFC 3550, but since
207 * this structure is analogous to ast_rtp, which tracks a RTP session,
208 * it is logical to think of this as a RTCP session.
210 * RTCP packet is defined on page 9 of RFC 3550.
214 int s; /*!< Socket */
215 struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
216 struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
217 unsigned int soc; /*!< What they told us */
218 unsigned int spc; /*!< What they told us */
219 unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
220 struct timeval rxlsr; /*!< Time when we got their last SR */
221 struct timeval txlsr; /*!< Time when we sent or last SR*/
222 unsigned int expected_prior; /*!< no. packets in previous interval */
223 unsigned int received_prior; /*!< no. packets received in previous interval */
224 int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
225 unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
226 unsigned int sr_count; /*!< number of SRs we've sent */
227 unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
228 double accumulated_transit; /*!< accumulated a-dlsr-lsr */
229 double rtt; /*!< Last reported rtt */
230 unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
231 unsigned int reported_lost; /*!< Reported lost packets in their RR */
232 char quality[AST_MAX_USER_FIELD];
241 * \brief STUN support code
243 * This code provides some support for doing STUN transactions.
244 * Eventually it should be moved elsewhere as other protocols
245 * than RTP can benefit from it - e.g. SIP.
246 * STUN is described in RFC3489 and it is based on the exchange
247 * of UDP packets between a client and one or more servers to
248 * determine the externally visible address (and port) of the client
249 * once it has gone through the NAT boxes that connect it to the
251 * The simplest request packet is just the header defined in
252 * struct stun_header, and from the response we may just look at
253 * one attribute, STUN_MAPPED_ADDRESS, that we find in the response.
254 * By doing more transactions with different server addresses we
255 * may determine more about the behaviour of the NAT boxes, of
256 * course - the details are in the RFC.
258 * All STUN packets start with a simple header made of a type,
259 * length (excluding the header) and a 16-byte random transaction id.
260 * Following the header we may have zero or more attributes, each
261 * structured as a type, length and a value (whose format depends
262 * on the type, but often contains addresses).
263 * Of course all fields are in network format.
266 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
269 unsigned short msgtype;
270 unsigned short msglen;
272 unsigned char ies[0];
273 } __attribute__((packed));
278 unsigned char value[0];
279 } __attribute__((packed));
282 * The format normally used for addresses carried by STUN messages.
285 unsigned char unused;
286 unsigned char family;
289 } __attribute__((packed));
291 #define STUN_IGNORE (0)
292 #define STUN_ACCEPT (1)
294 /*! \brief STUN message types
295 * 'BIND' refers to transactions used to determine the externally
296 * visible addresses. 'SEC' refers to transactions used to establish
297 * a session key for subsequent requests.
298 * 'SEC' functionality is not supported here.
301 #define STUN_BINDREQ 0x0001
302 #define STUN_BINDRESP 0x0101
303 #define STUN_BINDERR 0x0111
304 #define STUN_SECREQ 0x0002
305 #define STUN_SECRESP 0x0102
306 #define STUN_SECERR 0x0112
308 /*! \brief Basic attribute types in stun messages.
309 * Messages can also contain custom attributes (codes above 0x7fff)
311 #define STUN_MAPPED_ADDRESS 0x0001
312 #define STUN_RESPONSE_ADDRESS 0x0002
313 #define STUN_CHANGE_REQUEST 0x0003
314 #define STUN_SOURCE_ADDRESS 0x0004
315 #define STUN_CHANGED_ADDRESS 0x0005
316 #define STUN_USERNAME 0x0006
317 #define STUN_PASSWORD 0x0007
318 #define STUN_MESSAGE_INTEGRITY 0x0008
319 #define STUN_ERROR_CODE 0x0009
320 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
321 #define STUN_REFLECTED_FROM 0x000b
323 /*! \brief helper function to print message names */
324 static const char *stun_msg2str(int msg)
328 return "Binding Request";
330 return "Binding Response";
332 return "Binding Error Response";
334 return "Shared Secret Request";
336 return "Shared Secret Response";
338 return "Shared Secret Error Response";
340 return "Non-RFC3489 Message";
343 /*! \brief helper function to print attribute names */
344 static const char *stun_attr2str(int msg)
347 case STUN_MAPPED_ADDRESS:
348 return "Mapped Address";
349 case STUN_RESPONSE_ADDRESS:
350 return "Response Address";
351 case STUN_CHANGE_REQUEST:
352 return "Change Request";
353 case STUN_SOURCE_ADDRESS:
354 return "Source Address";
355 case STUN_CHANGED_ADDRESS:
356 return "Changed Address";
361 case STUN_MESSAGE_INTEGRITY:
362 return "Message Integrity";
363 case STUN_ERROR_CODE:
365 case STUN_UNKNOWN_ATTRIBUTES:
366 return "Unknown Attributes";
367 case STUN_REFLECTED_FROM:
368 return "Reflected From";
370 return "Non-RFC3489 Attribute";
373 /*! \brief here we store credentials extracted from a message */
375 const char *username;
376 const char *password;
379 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
382 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
383 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
384 switch (ntohs(attr->attr)) {
386 state->username = (const char *) (attr->value);
389 state->password = (const char *) (attr->value);
393 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
394 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
399 /*! \brief append a string to an STUN message */
400 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
402 int size = sizeof(**attr) + strlen(s);
404 (*attr)->attr = htons(attrval);
405 (*attr)->len = htons(strlen(s));
406 memcpy((*attr)->value, s, strlen(s));
407 (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
413 /*! \brief append an address to an STUN message */
414 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
416 int size = sizeof(**attr) + 8;
417 struct stun_addr *addr;
419 (*attr)->attr = htons(attrval);
420 (*attr)->len = htons(8);
421 addr = (struct stun_addr *)((*attr)->value);
424 addr->port = sin->sin_port;
425 addr->addr = sin->sin_addr.s_addr;
426 (*attr) = (struct stun_attr *)((*attr)->value + 8);
432 /*! \brief wrapper to send an STUN message */
433 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
435 return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
436 (struct sockaddr *)dst, sizeof(*dst));
439 /*! \brief helper function to generate a random request id */
440 static void stun_req_id(struct stun_header *req)
443 for (x = 0; x < 4; x++)
444 req->id.id[x] = ast_random();
447 size_t ast_rtp_alloc_size(void)
449 return sizeof(struct ast_rtp);
452 /*! \brief callback type to be invoked on stun responses. */
453 typedef int (stun_cb_f)(struct stun_attr *attr, void *arg);
455 /*! \brief handle an incoming STUN message.
457 * Do some basic sanity checks on packet size and content,
458 * try to extract a bit of information, and possibly reply.
459 * At the moment this only processes BIND requests, and returns
460 * the externally visible address of the request.
461 * If a callback is specified, invoke it with the attribute.
463 static int stun_handle_packet(int s, struct sockaddr_in *src,
464 unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
466 struct stun_header *hdr = (struct stun_header *)data;
467 struct stun_attr *attr;
468 struct stun_state st;
469 int ret = STUN_IGNORE;
472 /* On entry, 'len' is the length of the udp payload. After the
473 * initial checks it becomes the size of unprocessed options,
474 * while 'data' is advanced accordingly.
476 if (len < sizeof(struct stun_header)) {
477 ast_debug(1, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
480 len -= sizeof(struct stun_header);
481 data += sizeof(struct stun_header);
482 x = ntohs(hdr->msglen); /* len as advertised in the message */
484 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), x);
486 ast_debug(1, "Scrambled STUN packet length (got %d, expecting %d)\n", x, (int)len);
489 memset(&st, 0, sizeof(st));
491 if (len < sizeof(struct stun_attr)) {
492 ast_debug(1, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
495 attr = (struct stun_attr *)data;
496 /* compute total attribute length */
497 x = ntohs(attr->len) + sizeof(struct stun_attr);
499 ast_debug(1, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x, (int)len);
504 if (stun_process_attr(&st, attr)) {
505 ast_debug(1, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
508 /* Clear attribute id: in case previous entry was a string,
509 * this will act as the terminator for the string.
515 /* Null terminate any string.
516 * XXX NOTE, we write past the size of the buffer passed by the
517 * caller, so this is potentially dangerous. The only thing that
518 * saves us is that usually we read the incoming message in a
519 * much larger buffer in the struct ast_rtp
523 /* Now prepare to generate a reply, which at the moment is done
524 * only for properly formed (len == 0) STUN_BINDREQ messages.
527 unsigned char respdata[1024];
528 struct stun_header *resp = (struct stun_header *)respdata;
529 int resplen = 0; /* len excluding header */
530 int respleft = sizeof(respdata) - sizeof(struct stun_header);
535 attr = (struct stun_attr *)resp->ies;
536 switch (ntohs(hdr->msgtype)) {
539 ast_verbose("STUN Bind Request, username: %s\n",
540 st.username ? st.username : "<none>");
542 append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
543 append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
544 resp->msglen = htons(resplen);
545 resp->msgtype = htons(STUN_BINDRESP);
546 stun_send(s, src, resp);
551 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
557 /*! \brief Extract the STUN_MAPPED_ADDRESS from the stun response.
558 * This is used as a callback for stun_handle_response
559 * when called from ast_stun_request.
561 static int stun_get_mapped(struct stun_attr *attr, void *arg)
563 struct stun_addr *addr = (struct stun_addr *)(attr + 1);
564 struct sockaddr_in *sa = (struct sockaddr_in *)arg;
566 if (ntohs(attr->attr) != STUN_MAPPED_ADDRESS || ntohs(attr->len) != 8)
567 return 1; /* not us. */
568 sa->sin_port = addr->port;
569 sa->sin_addr.s_addr = addr->addr;
573 /*! \brief Generic STUN request
574 * Send a generic stun request to the server specified,
575 * possibly waiting for a reply and filling the 'reply' field with
576 * the externally visible address. Note that in this case the request
578 * (Note, the interface may change slightly in the future).
580 * \param s the socket used to send the request
581 * \param dst the address of the STUN server
582 * \param username if non null, add the username in the request
583 * \param answer if non null, the function waits for a response and
584 * puts here the externally visible address.
585 * \return 0 on success, other values on error.
587 int ast_stun_request(int s, struct sockaddr_in *dst,
588 const char *username, struct sockaddr_in *answer)
590 struct stun_header *req;
591 unsigned char reqdata[1024];
593 struct stun_attr *attr;
597 req = (struct stun_header *)reqdata;
600 reqleft = sizeof(reqdata) - sizeof(struct stun_header);
603 attr = (struct stun_attr *)req->ies;
605 append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
606 req->msglen = htons(reqlen);
607 req->msgtype = htons(STUN_BINDREQ);
608 for (retry = 0; retry < 3; retry++) { /* XXX make retries configurable */
609 /* send request, possibly wait for reply */
610 unsigned char reply_buf[1024];
612 struct timeval to = { 3, 0 }; /* timeout, make it configurable */
613 struct sockaddr_in src;
616 res = stun_send(s, dst, req);
618 ast_log(LOG_WARNING, "ast_stun_request send #%d failed error %d, retry\n",
626 res = ast_select(s + 1, &rfds, NULL, NULL, &to);
627 if (res <= 0) /* timeout or error */
629 bzero(&src, sizeof(src));
630 srclen = sizeof(src);
631 /* XXX pass -1 in the size, because stun_handle_packet might
632 * write past the end of the buffer.
634 res = recvfrom(s, reply_buf, sizeof(reply_buf) - 1,
635 0, (struct sockaddr *)&src, &srclen);
637 ast_log(LOG_WARNING, "ast_stun_request recvfrom #%d failed error %d, retry\n",
641 bzero(answer, sizeof(struct sockaddr_in));
642 stun_handle_packet(s, &src, reply_buf, res,
643 stun_get_mapped, answer);
644 res = 0; /* signal regular exit */
650 /*! \brief send a STUN BIND request to the given destination.
651 * Optionally, add a username if specified.
653 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
655 ast_stun_request(rtp->s, suggestion, username, NULL);
658 /*! \brief List of current sessions */
659 static AST_RWLIST_HEAD_STATIC(protos, ast_rtp_protocol);
661 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
663 unsigned int sec, usec, frac;
664 sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
666 frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
671 int ast_rtp_fd(struct ast_rtp *rtp)
676 int ast_rtcp_fd(struct ast_rtp *rtp)
683 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
685 unsigned int interval;
686 /*! \todo XXX Do a more reasonable calculation on this one
687 * Look in RFC 3550 Section A.7 for an example*/
688 interval = rtcpinterval;
692 /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
693 void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
695 rtp->rtptimeout = (-1) * rtp->rtptimeout;
696 rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
699 /*! \brief Set rtp timeout */
700 void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
702 rtp->rtptimeout = timeout;
705 /*! \brief Set rtp hold timeout */
706 void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
708 rtp->rtpholdtimeout = timeout;
711 /*! \brief set RTP keepalive interval */
712 void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
714 rtp->rtpkeepalive = period;
717 /*! \brief Get rtp timeout */
718 int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
720 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
722 return rtp->rtptimeout;
725 /*! \brief Get rtp hold timeout */
726 int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
728 if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
730 return rtp->rtpholdtimeout;
733 /*! \brief Get RTP keepalive interval */
734 int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
736 return rtp->rtpkeepalive;
739 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
744 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
746 rtp->callback = callback;
749 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
754 int ast_rtp_getnat(struct ast_rtp *rtp)
756 return ast_test_flag(rtp, FLAG_NAT_ACTIVE);
759 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
761 ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
764 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
766 ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
769 void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
771 ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
774 static void rtp_bridge_lock(struct ast_rtp *rtp)
777 ast_mutex_lock(&rtp->bridge_lock);
782 static void rtp_bridge_unlock(struct ast_rtp *rtp)
785 ast_mutex_unlock(&rtp->bridge_lock);
790 static struct ast_frame *send_dtmf(struct ast_rtp *rtp, enum ast_frame_type type)
792 if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
793 (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
794 ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
796 rtp->dtmfsamples = 0;
797 return &ast_null_frame;
799 ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
800 if (rtp->resp == 'X') {
801 rtp->f.frametype = AST_FRAME_CONTROL;
802 rtp->f.subclass = AST_CONTROL_FLASH;
804 rtp->f.frametype = type;
805 rtp->f.subclass = rtp->resp;
815 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
819 if (rtpdebugaddr.sin_addr.s_addr) {
820 if (((ntohs(rtpdebugaddr.sin_port) != 0)
821 && (rtpdebugaddr.sin_port != addr->sin_port))
822 || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
828 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
832 if (rtcpdebugaddr.sin_addr.s_addr) {
833 if (((ntohs(rtcpdebugaddr.sin_port) != 0)
834 && (rtcpdebugaddr.sin_port != addr->sin_port))
835 || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
842 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
846 struct ast_frame *f = NULL;
851 /* We should have at least 4 bytes in RTP data */
855 /* The format of Cisco RTP DTMF packet looks like next:
856 +0 - sequence number of DTMF RTP packet (begins from 1,
859 +1 (bit 0) - flaps by different DTMF digits delimited by audio
860 or repeated digit without audio???
861 +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
862 then falls to 0 at its end)
863 +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
864 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
865 by each new packet and thus provides some redudancy.
867 Sample of Cisco RTP DTMF packet is (all data in hex):
868 19 07 00 02 12 02 20 02
869 showing end of DTMF digit '2'.
872 27 07 00 02 0A 02 20 02
873 28 06 20 02 00 02 0A 02
874 shows begin of new digit '2' with very short pause (20 ms) after
875 previous digit '2'. Bit +1.0 flips at begin of new digit.
877 Cisco RTP DTMF packets comes as replacement of audio RTP packets
878 so its uses the same sequencing and timestamping rules as replaced
879 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
880 on audio framing parameters. Marker bit isn't used within stream of
881 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
882 are not sequential at borders between DTMF and audio streams,
888 event = data[3] & 0x1f;
890 if (option_debug > 2 || rtpdebug)
891 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);
894 } else if (event < 11) {
896 } else if (event < 12) {
898 } else if (event < 16) {
899 resp = 'A' + (event - 12);
900 } else if (event < 17) {
903 if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
905 /* Why we should care on DTMF compensation at reception? */
906 if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
907 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
908 rtp->dtmfsamples = 0;
910 } else if ((rtp->resp == resp) && !power) {
911 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
912 f->samples = rtp->dtmfsamples * 8;
914 } else if (rtp->resp == resp)
915 rtp->dtmfsamples += 20 * 8;
916 rtp->dtmfcount = dtmftimeout;
921 * \brief Process RTP DTMF and events according to RFC 2833.
923 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
932 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp)
935 unsigned int event_end;
936 unsigned int samples;
938 struct ast_frame *f = NULL;
940 /* Figure out event, event end, and samples */
941 event = ntohl(*((unsigned int *)(data)));
943 event_end = ntohl(*((unsigned int *)(data)));
946 samples = ntohl(*((unsigned int *)(data)));
949 /* Print out debug if turned on */
950 if (rtpdebug || option_debug > 2)
951 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
953 /* Figure out what digit was pressed */
956 } else if (event < 11) {
958 } else if (event < 12) {
960 } else if (event < 16) {
961 resp = 'A' + (event - 12);
962 } else if (event < 17) { /* Event 16: Hook flash */
965 /* Not a supported event */
966 ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
967 return &ast_null_frame;
970 if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
971 if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
973 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
975 rtp->lastevent = timestamp;
978 if ((!(rtp->resp) && (!(event_end & 0x80))) || (rtp->resp && rtp->resp != resp)) {
980 f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
981 } else if ((event_end & 0x80) && (rtp->lastevent != seqno) && rtp->resp) {
982 f = send_dtmf(rtp, AST_FRAME_DTMF_END);
983 f->len = ast_tvdiff_ms(ast_samp2tv(samples, 8000), ast_tv(0, 0)); /* XXX hard coded 8kHz */
985 rtp->lastevent = seqno;
989 rtp->dtmfcount = dtmftimeout;
990 rtp->dtmfsamples = samples;
996 * \brief Process Comfort Noise RTP.
998 * This is incomplete at the moment.
1001 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
1003 struct ast_frame *f = NULL;
1004 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
1005 totally help us out becuase we don't have an engine to keep it going and we are not
1006 guaranteed to have it every 20ms or anything */
1008 ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
1010 if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
1011 ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
1012 ast_inet_ntoa(rtp->them.sin_addr));
1013 ast_set_flag(rtp, FLAG_3389_WARNING);
1016 /* Must have at least one byte */
1020 rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
1021 rtp->f.datalen = len - 1;
1022 rtp->f.offset = AST_FRIENDLY_OFFSET;
1023 memcpy(rtp->f.data, data + 1, len - 1);
1029 rtp->f.frametype = AST_FRAME_CNG;
1030 rtp->f.subclass = data[0] & 0x7f;
1031 rtp->f.datalen = len - 1;
1033 rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
1038 static int rtpread(int *id, int fd, short events, void *cbdata)
1040 struct ast_rtp *rtp = cbdata;
1041 struct ast_frame *f;
1042 f = ast_rtp_read(rtp);
1045 rtp->callback(rtp, f, rtp->data);
1050 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
1053 int position, i, packetwords;
1055 struct sockaddr_in sin;
1056 unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
1057 unsigned int *rtcpheader;
1060 unsigned int length;
1069 struct ast_frame *f = &ast_null_frame;
1071 if (!rtp || !rtp->rtcp)
1072 return &ast_null_frame;
1076 res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
1077 0, (struct sockaddr *)&sin, &len);
1078 rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
1083 if (errno != EAGAIN) {
1084 ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n", strerror(errno));
1087 return &ast_null_frame;
1090 packetwords = res / 4;
1093 /* Send to whoever sent to us */
1094 if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1095 (rtp->rtcp->them.sin_port != sin.sin_port)) {
1096 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1097 if (option_debug || rtpdebug)
1098 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));
1102 ast_debug(1, "Got RTCP report of %d bytes\n", res);
1104 /* Process a compound packet */
1106 while (position < packetwords) {
1108 length = ntohl(rtcpheader[i]);
1109 pt = (length & 0xff0000) >> 16;
1110 rc = (length & 0x1f000000) >> 24;
1113 if ((i + length) > packetwords) {
1114 ast_log(LOG_WARNING, "RTCP Read too short\n");
1115 return &ast_null_frame;
1118 if (rtcp_debug_test_addr(&sin)) {
1119 ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
1120 ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
1121 ast_verbose("Reception reports: %d\n", rc);
1122 ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
1125 i += 2; /* Advance past header and ssrc */
1129 gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
1130 rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
1131 rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
1132 rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
1134 if (rtcp_debug_test_addr(&sin)) {
1135 ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
1136 ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
1137 ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
1142 /* Intentional fall through */
1144 /* Don't handle multiple reception reports (rc > 1) yet */
1145 /* Calculate RTT per RFC */
1146 gettimeofday(&now, NULL);
1147 timeval2ntp(now, &msw, &lsw);
1148 if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
1149 comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
1150 lsr = ntohl(rtcpheader[i + 4]);
1151 dlsr = ntohl(rtcpheader[i + 5]);
1152 rtt = comp - lsr - dlsr;
1154 /* Convert end to end delay to usec (keeping the calculation in 64bit space)
1155 sess->ee_delay = (eedelay * 1000) / 65536; */
1157 rtt = (rtt * 1000000) >> 16;
1159 rtt = (rtt * 1000) >> 16;
1163 rttsec = rtt / 1000.;
1165 if (comp - dlsr >= lsr) {
1166 rtp->rtcp->accumulated_transit += rttsec;
1167 rtp->rtcp->rtt = rttsec;
1168 if (rtp->rtcp->maxrtt<rttsec)
1169 rtp->rtcp->maxrtt = rttsec;
1170 if (rtp->rtcp->minrtt>rttsec)
1171 rtp->rtcp->minrtt = rttsec;
1172 } else if (rtcp_debug_test_addr(&sin)) {
1173 ast_verbose("Internal RTCP NTP clock skew detected: "
1174 "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
1176 lsr, comp, dlsr, dlsr / 65536,
1177 (dlsr % 65536) * 1000 / 65536,
1178 dlsr - (comp - lsr));
1182 rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
1183 rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
1184 if (rtcp_debug_test_addr(&sin)) {
1185 ast_verbose(" Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
1186 ast_verbose(" Packets lost so far: %d\n", rtp->rtcp->reported_lost);
1187 ast_verbose(" Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
1188 ast_verbose(" Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
1189 ast_verbose(" Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
1190 ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
1191 ast_verbose(" DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
1193 ast_verbose(" RTT: %lu(sec)\n", (unsigned long) rtt);
1196 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From %s:%d\r\n"
1198 "ReceptionReports: %d\r\n"
1199 "SenderSSRC: %u\r\n"
1200 "FractionLost: %ld\r\n"
1201 "PacketsLost: %d\r\n"
1202 "HighestSequence: %ld\r\n"
1203 "SequenceNumberCycles: %ld\r\n"
1205 "LastSR: %lu.%010lu\r\n"
1206 "DLSR: %4.4f(sec)\r\n"
1207 "RTT: %llu(sec)\r\n",
1208 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
1209 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1212 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1213 rtp->rtcp->reported_lost,
1214 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1215 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1216 rtp->rtcp->reported_jitter,
1217 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1218 ntohl(rtcpheader[i + 5])/65536.0,
1219 (unsigned long long)rtt);
1221 manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From %s:%d\r\n"
1223 "ReceptionReports: %d\r\n"
1224 "SenderSSRC: %u\r\n"
1225 "FractionLost: %ld\r\n"
1226 "PacketsLost: %d\r\n"
1227 "HighestSequence: %ld\r\n"
1228 "SequenceNumberCycles: %ld\r\n"
1230 "LastSR: %lu.%010lu\r\n"
1231 "DLSR: %4.4f(sec)\r\n",
1232 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
1233 pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
1236 (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
1237 rtp->rtcp->reported_lost,
1238 (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
1239 (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
1240 rtp->rtcp->reported_jitter,
1241 (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
1242 ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
1243 ntohl(rtcpheader[i + 5])/65536.0);
1247 if (rtcp_debug_test_addr(&sin))
1248 ast_verbose("Received an RTCP Fast Update Request\n");
1249 rtp->f.frametype = AST_FRAME_CONTROL;
1250 rtp->f.subclass = AST_CONTROL_VIDUPDATE;
1258 if (rtcp_debug_test_addr(&sin))
1259 ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1262 if (rtcp_debug_test_addr(&sin))
1263 ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
1266 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));
1269 position += (length + 1);
1275 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
1279 double current_time;
1284 if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
1285 gettimeofday(&rtp->rxcore, NULL);
1286 rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
1287 /* map timestamp to a real time */
1288 rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
1289 rtp->rxcore.tv_sec -= timestamp / 8000;
1290 rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
1291 /* Round to 0.1ms for nice, pretty timestamps */
1292 rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
1293 if (rtp->rxcore.tv_usec < 0) {
1294 /* Adjust appropriately if necessary */
1295 rtp->rxcore.tv_usec += 1000000;
1296 rtp->rxcore.tv_sec -= 1;
1300 gettimeofday(&now,NULL);
1301 /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
1302 tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
1303 tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
1304 if (tv->tv_usec >= 1000000) {
1305 tv->tv_usec -= 1000000;
1308 prog = (double)((timestamp-rtp->seedrxts)/8000.);
1309 dtv = (double)rtp->drxcore + (double)(prog);
1310 current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
1311 transit = current_time - dtv;
1312 d = transit - rtp->rxtransit;
1313 rtp->rxtransit = transit;
1316 rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
1317 if (rtp->rtcp && rtp->rxjitter > rtp->rtcp->maxrxjitter)
1318 rtp->rtcp->maxrxjitter = rtp->rxjitter;
1319 if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
1320 rtp->rtcp->minrxjitter = rtp->rxjitter;
1323 /*! \brief Perform a Packet2Packet RTP write */
1324 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, struct ast_rtp *bridged, unsigned int *rtpheader, int len, int hdrlen)
1326 int res = 0, payload = 0, bridged_payload = 0, mark;
1327 struct rtpPayloadType rtpPT;
1328 int reconstruct = ntohl(rtpheader[0]);
1330 /* Get fields from packet */
1331 payload = (reconstruct & 0x7f0000) >> 16;
1332 mark = (((reconstruct & 0x800000) >> 23) != 0);
1334 /* Check what the payload value should be */
1335 rtpPT = ast_rtp_lookup_pt(rtp, payload);
1337 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
1338 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
1341 /* Otherwise adjust bridged payload to match */
1342 bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
1344 /* If the mark bit has not been sent yet... do it now */
1345 if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
1347 ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
1350 /* Reconstruct part of the packet */
1351 reconstruct &= 0xFF80FFFF;
1352 reconstruct |= (bridged_payload << 16);
1353 reconstruct |= (mark << 23);
1354 rtpheader[0] = htonl(reconstruct);
1356 /* Send the packet back out */
1357 res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
1359 if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
1360 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));
1361 } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
1362 if (option_debug || rtpdebug)
1363 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));
1364 ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
1367 } else if (rtp_debug_test_addr(&bridged->them))
1368 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);
1373 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
1376 struct sockaddr_in sin;
1387 unsigned int timestamp;
1388 unsigned int *rtpheader;
1389 struct rtpPayloadType rtpPT;
1390 struct ast_rtp *bridged = NULL;
1392 /* If time is up, kill it */
1393 if (rtp->sending_digit)
1394 ast_rtp_senddigit_continuation(rtp);
1398 /* Cache where the header will go */
1399 res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
1400 0, (struct sockaddr *)&sin, &len);
1402 rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
1406 if (errno != EAGAIN) {
1407 ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
1410 return &ast_null_frame;
1414 ast_log(LOG_WARNING, "RTP Read too short\n");
1415 return &ast_null_frame;
1419 seqno = ntohl(rtpheader[0]);
1421 /* Check RTP version */
1422 version = (seqno & 0xC0000000) >> 30;
1424 /* If the two high bits are 0, this might be a
1425 * STUN message, so process it. stun_handle_packet()
1426 * answers to requests, and it returns STUN_ACCEPT
1427 * if the request is valid.
1429 if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == STUN_ACCEPT) &&
1430 (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
1431 memcpy(&rtp->them, &sin, sizeof(rtp->them));
1433 return &ast_null_frame;
1436 #if 0 /* Allow to receive RTP stream with closed transmission path */
1437 /* If we don't have the other side's address, then ignore this */
1438 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
1439 return &ast_null_frame;
1442 /* Send to whoever send to us if NAT is turned on */
1444 if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
1445 (rtp->them.sin_port != sin.sin_port)) {
1448 memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
1449 rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
1452 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
1453 if (option_debug || rtpdebug)
1454 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));
1458 /* If we are bridged to another RTP stream, send direct */
1459 if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
1460 return &ast_null_frame;
1463 return &ast_null_frame;
1465 payloadtype = (seqno & 0x7f0000) >> 16;
1466 padding = seqno & (1 << 29);
1467 mark = seqno & (1 << 23);
1468 ext = seqno & (1 << 28);
1469 cc = (seqno & 0xF000000) >> 24;
1471 timestamp = ntohl(rtpheader[1]);
1472 ssrc = ntohl(rtpheader[2]);
1474 if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
1475 if (option_debug || rtpdebug)
1476 ast_debug(0, "Forcing Marker bit, because SSRC has changed\n");
1483 /* Remove padding bytes */
1484 res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
1488 /* CSRC fields present */
1493 /* RTP Extension present */
1494 hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
1498 profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
1499 if (profile == 0x505a)
1500 ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
1502 ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
1507 ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
1508 return &ast_null_frame;
1511 rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1513 if (rtp->rxcount==1) {
1514 /* This is the first RTP packet successfully received from source */
1515 rtp->seedrxseqno = seqno;
1518 /* Do not schedule RR if RTCP isn't run */
1519 if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
1520 /* Schedule transmission of Receiver Report */
1521 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
1523 if ( (int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
1524 rtp->cycles += RTP_SEQ_MOD;
1526 rtp->lastrxseqno = seqno;
1528 if (rtp->themssrc==0)
1529 rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
1531 if (rtp_debug_test_addr(&sin))
1532 ast_verbose("Got RTP packet from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1533 ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
1535 rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
1536 if (!rtpPT.isAstFormat) {
1537 struct ast_frame *f = NULL;
1539 /* This is special in-band data that's not one of our codecs */
1540 if (rtpPT.code == AST_RTP_DTMF) {
1541 /* It's special -- rfc2833 process it */
1542 if (rtp_debug_test_addr(&sin)) {
1543 unsigned char *data;
1545 unsigned int event_end;
1546 unsigned int duration;
1547 data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
1548 event = ntohl(*((unsigned int *)(data)));
1550 event_end = ntohl(*((unsigned int *)(data)));
1553 duration = ntohl(*((unsigned int *)(data)));
1555 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);
1557 f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp);
1558 } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
1559 /* It's really special -- process it the Cisco way */
1560 if (rtp->lastevent <= seqno || (rtp->lastevent >= 65530 && seqno <= 6)) {
1561 f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1562 rtp->lastevent = seqno;
1564 } else if (rtpPT.code == AST_RTP_CN) {
1566 f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
1568 ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
1570 return f ? f : &ast_null_frame;
1572 rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
1573 rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : (rtp->f.subclass < AST_FORMAT_MAX_VIDEO) ? AST_FRAME_VIDEO : AST_FRAME_TEXT;
1576 rtp->lastrxts = timestamp;
1578 rtp->rxseqno = seqno;
1580 /* Record received timestamp as last received now */
1581 rtp->lastrxts = timestamp;
1584 rtp->f.datalen = res - hdrlen;
1585 rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
1586 rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
1587 rtp->f.seqno = seqno;
1588 if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
1589 rtp->f.samples = ast_codec_get_samples(&rtp->f);
1590 if (rtp->f.subclass == AST_FORMAT_SLINEAR)
1591 ast_frame_byteswap_be(&rtp->f);
1592 calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
1593 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1594 rtp->f.has_timing_info = 1;
1595 rtp->f.ts = timestamp / 8;
1596 rtp->f.len = rtp->f.samples / 8;
1597 } else if(rtp->f.subclass < AST_FORMAT_MAX_VIDEO) {
1598 /* Video -- samples is # of samples vs. 90000 */
1599 if (!rtp->lastividtimestamp)
1600 rtp->lastividtimestamp = timestamp;
1601 rtp->f.samples = timestamp - rtp->lastividtimestamp;
1602 rtp->lastividtimestamp = timestamp;
1603 rtp->f.delivery.tv_sec = 0;
1604 rtp->f.delivery.tv_usec = 0;
1605 /* Pass the RTP marker bit as bit 0 in the subclass field.
1606 * This is ok because subclass is actually a bitmask, and
1607 * the low bits represent audio formats, that are not
1608 * involved here since we deal with video.
1611 rtp->f.subclass |= 0x1;
1613 /* TEXT -- samples is # of samples vs. 1000 */
1614 if (!rtp->lastitexttimestamp)
1615 rtp->lastitexttimestamp = timestamp;
1616 rtp->f.samples = timestamp - rtp->lastitexttimestamp;
1617 rtp->lastitexttimestamp = timestamp;
1618 rtp->f.delivery.tv_sec = 0;
1619 rtp->f.delivery.tv_usec = 0;
1625 /* The following array defines the MIME Media type (and subtype) for each
1626 of our codecs, or RTP-specific data type. */
1628 struct rtpPayloadType payloadType;
1632 {{1, AST_FORMAT_G723_1}, "audio", "G723"},
1633 {{1, AST_FORMAT_GSM}, "audio", "GSM"},
1634 {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
1635 {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
1636 {{1, AST_FORMAT_G726}, "audio", "G726-32"},
1637 {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
1638 {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
1639 {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
1640 {{1, AST_FORMAT_G729A}, "audio", "G729"},
1641 {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
1642 {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
1643 {{1, AST_FORMAT_G722}, "audio", "G722"},
1644 {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
1645 {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
1646 {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
1647 {{0, AST_RTP_CN}, "audio", "CN"},
1648 {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
1649 {{1, AST_FORMAT_PNG}, "video", "PNG"},
1650 {{1, AST_FORMAT_H261}, "video", "H261"},
1651 {{1, AST_FORMAT_H263}, "video", "H263"},
1652 {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
1653 {{1, AST_FORMAT_H264}, "video", "H264"},
1654 {{1, AST_FORMAT_MP4_VIDEO}, "video", "MP4V-ES"},
1655 {{1, AST_FORMAT_T140}, "text", "T140"},
1659 * \brief Mapping between Asterisk codecs and rtp payload types
1661 * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1662 * also, our own choices for dynamic payload types. This is our master
1663 * table for transmission
1665 * See http://www.iana.org/assignments/rtp-parameters for a list of
1668 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
1669 [0] = {1, AST_FORMAT_ULAW},
1670 #ifdef USE_DEPRECATED_G726
1671 [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1673 [3] = {1, AST_FORMAT_GSM},
1674 [4] = {1, AST_FORMAT_G723_1},
1675 [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
1676 [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
1677 [7] = {1, AST_FORMAT_LPC10},
1678 [8] = {1, AST_FORMAT_ALAW},
1679 [9] = {1, AST_FORMAT_G722},
1680 [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
1681 [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
1682 [13] = {0, AST_RTP_CN},
1683 [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
1684 [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
1685 [18] = {1, AST_FORMAT_G729A},
1686 [19] = {0, AST_RTP_CN}, /* Also used for CN */
1687 [26] = {1, AST_FORMAT_JPEG},
1688 [31] = {1, AST_FORMAT_H261},
1689 [34] = {1, AST_FORMAT_H263},
1690 [97] = {1, AST_FORMAT_ILBC},
1691 [98] = {1, AST_FORMAT_H263_PLUS},
1692 [99] = {1, AST_FORMAT_H264},
1693 [101] = {0, AST_RTP_DTMF},
1694 [102] = {1, AST_FORMAT_T140}, /* Real time text chat */
1695 [103] = {1, AST_FORMAT_H263_PLUS},
1696 [104] = {1, AST_FORMAT_MP4_VIDEO},
1697 [110] = {1, AST_FORMAT_SPEEX},
1698 [111] = {1, AST_FORMAT_G726},
1699 [112] = {1, AST_FORMAT_G726_AAL2},
1700 [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
1703 void ast_rtp_pt_clear(struct ast_rtp* rtp)
1710 rtp_bridge_lock(rtp);
1712 for (i = 0; i < MAX_RTP_PT; ++i) {
1713 rtp->current_RTP_PT[i].isAstFormat = 0;
1714 rtp->current_RTP_PT[i].code = 0;
1717 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1718 rtp->rtp_lookup_code_cache_code = 0;
1719 rtp->rtp_lookup_code_cache_result = 0;
1721 rtp_bridge_unlock(rtp);
1724 void ast_rtp_pt_default(struct ast_rtp* rtp)
1728 rtp_bridge_lock(rtp);
1730 /* Initialize to default payload types */
1731 for (i = 0; i < MAX_RTP_PT; ++i) {
1732 rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
1733 rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
1736 rtp->rtp_lookup_code_cache_isAstFormat = 0;
1737 rtp->rtp_lookup_code_cache_code = 0;
1738 rtp->rtp_lookup_code_cache_result = 0;
1740 rtp_bridge_unlock(rtp);
1743 void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
1747 rtp_bridge_lock(dest);
1748 rtp_bridge_lock(src);
1750 for (i=0; i < MAX_RTP_PT; ++i) {
1751 dest->current_RTP_PT[i].isAstFormat =
1752 src->current_RTP_PT[i].isAstFormat;
1753 dest->current_RTP_PT[i].code =
1754 src->current_RTP_PT[i].code;
1756 dest->rtp_lookup_code_cache_isAstFormat = 0;
1757 dest->rtp_lookup_code_cache_code = 0;
1758 dest->rtp_lookup_code_cache_result = 0;
1760 rtp_bridge_unlock(src);
1761 rtp_bridge_unlock(dest);
1764 /*! \brief Get channel driver interface structure */
1765 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
1767 struct ast_rtp_protocol *cur = NULL;
1769 AST_RWLIST_RDLOCK(&protos);
1770 AST_RWLIST_TRAVERSE(&protos, cur, list) {
1771 if (cur->type == chan->tech->type)
1774 AST_RWLIST_UNLOCK(&protos);
1779 int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
1781 // dest = c0, src = c1
1782 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1783 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1784 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
1785 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1786 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;
1787 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;
1788 int srccodec, destcodec, nat_active = 0;
1791 ast_channel_lock(c0);
1793 while (ast_channel_trylock(c1)) {
1794 ast_channel_unlock(c0);
1796 ast_channel_lock(c0);
1800 /* Find channel driver interfaces */
1801 destpr = get_proto(c0);
1803 srcpr = get_proto(c1);
1805 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c0->name);
1806 ast_channel_unlock(c0);
1808 ast_channel_unlock(c1);
1812 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
1813 ast_channel_unlock(c0);
1815 ast_channel_unlock(c1);
1819 /* Get audio, video and text interface (if native bridge is possible) */
1820 audio_dest_res = destpr->get_rtp_info(c0, &destp);
1821 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
1822 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(c0, &tdestp) : AST_RTP_GET_FAILED;
1824 audio_src_res = srcpr->get_rtp_info(c1, &srcp);
1825 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
1826 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(c1, &tsrcp) : AST_RTP_GET_FAILED;
1829 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1830 if (audio_dest_res != AST_RTP_TRY_NATIVE) {
1831 /* Somebody doesn't want to play... */
1832 ast_channel_unlock(c0);
1834 ast_channel_unlock(c1);
1837 if (audio_src_res == AST_RTP_TRY_NATIVE && srcpr->get_codec)
1838 srccodec = srcpr->get_codec(c1);
1841 if (audio_dest_res == AST_RTP_TRY_NATIVE && destpr->get_codec)
1842 destcodec = destpr->get_codec(c0);
1845 /* Ensure we have at least one matching codec */
1846 if (!(srccodec & destcodec)) {
1847 ast_channel_unlock(c0);
1849 ast_channel_unlock(c1);
1852 /* Consider empty media as non-existant */
1853 if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
1855 if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1857 /* Bridge media early */
1858 if (destpr->set_rtp_peer(c0, srcp, vsrcp, tsrcp, srccodec, nat_active))
1859 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1860 ast_channel_unlock(c0);
1862 ast_channel_unlock(c1);
1863 ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
1867 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
1869 struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
1870 struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
1871 struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
1872 struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
1873 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;
1874 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;
1875 int srccodec, destcodec;
1878 ast_channel_lock(dest);
1879 while (ast_channel_trylock(src)) {
1880 ast_channel_unlock(dest);
1882 ast_channel_lock(dest);
1885 /* Find channel driver interfaces */
1886 if (!(destpr = get_proto(dest))) {
1887 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", dest->name);
1888 ast_channel_unlock(dest);
1889 ast_channel_unlock(src);
1892 if (!(srcpr = get_proto(src))) {
1893 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", src->name);
1894 ast_channel_unlock(dest);
1895 ast_channel_unlock(src);
1899 /* Get audio and video interface (if native bridge is possible) */
1900 audio_dest_res = destpr->get_rtp_info(dest, &destp);
1901 video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
1902 text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(dest, &tdestp) : AST_RTP_GET_FAILED;
1903 audio_src_res = srcpr->get_rtp_info(src, &srcp);
1904 video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
1905 text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(src, &tsrcp) : AST_RTP_GET_FAILED;
1907 /* Ensure we have at least one matching codec */
1908 if (srcpr->get_codec)
1909 srccodec = srcpr->get_codec(src);
1912 if (destpr->get_codec)
1913 destcodec = destpr->get_codec(dest);
1917 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1918 if (audio_dest_res != AST_RTP_TRY_NATIVE || audio_src_res != AST_RTP_TRY_NATIVE || !(srccodec & destcodec)) {
1919 /* Somebody doesn't want to play... */
1920 ast_channel_unlock(dest);
1921 ast_channel_unlock(src);
1924 ast_rtp_pt_copy(destp, srcp);
1925 if (vdestp && vsrcp)
1926 ast_rtp_pt_copy(vdestp, vsrcp);
1927 if (tdestp && tsrcp)
1928 ast_rtp_pt_copy(tdestp, tsrcp);
1931 if (destpr->set_rtp_peer(dest, srcp, vsrcp, tsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
1932 ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
1934 ast_channel_unlock(dest);
1935 ast_channel_unlock(src);
1936 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
1940 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1941 * By default, use the well-known value for this type (although it may
1942 * still be set to a different value by a subsequent "a=rtpmap:" line)
1944 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
1946 if (pt < 0 || pt > MAX_RTP_PT || static_RTP_PT[pt].code == 0)
1947 return; /* bogus payload type */
1949 rtp_bridge_lock(rtp);
1950 rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
1951 rtp_bridge_unlock(rtp);
1954 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1955 * an SDP "a=rtpmap:" line.
1957 void ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
1958 char *mimeType, char *mimeSubtype,
1959 enum ast_rtp_options options)
1963 if (pt < 0 || pt > MAX_RTP_PT)
1964 return; /* bogus payload type */
1966 rtp_bridge_lock(rtp);
1968 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
1969 if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
1970 strcasecmp(mimeType, mimeTypes[i].type) == 0) {
1971 rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
1972 if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
1973 mimeTypes[i].payloadType.isAstFormat &&
1974 (options & AST_RTP_OPT_G726_NONSTANDARD))
1975 rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
1980 rtp_bridge_unlock(rtp);
1985 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
1986 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
1987 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
1988 int* astFormats, int* nonAstFormats)
1992 rtp_bridge_lock(rtp);
1994 *astFormats = *nonAstFormats = 0;
1995 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
1996 if (rtp->current_RTP_PT[pt].isAstFormat) {
1997 *astFormats |= rtp->current_RTP_PT[pt].code;
1999 *nonAstFormats |= rtp->current_RTP_PT[pt].code;
2003 rtp_bridge_unlock(rtp);
2008 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
2010 struct rtpPayloadType result;
2012 result.isAstFormat = result.code = 0;
2014 if (pt < 0 || pt > MAX_RTP_PT)
2015 return result; /* bogus payload type */
2017 /* Start with negotiated codecs */
2018 rtp_bridge_lock(rtp);
2019 result = rtp->current_RTP_PT[pt];
2020 rtp_bridge_unlock(rtp);
2022 /* If it doesn't exist, check our static RTP type list, just in case */
2024 result = static_RTP_PT[pt];
2029 /*! \brief Looks up an RTP code out of our *static* outbound list */
2030 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
2034 rtp_bridge_lock(rtp);
2036 if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
2037 code == rtp->rtp_lookup_code_cache_code) {
2038 /* Use our cached mapping, to avoid the overhead of the loop below */
2039 pt = rtp->rtp_lookup_code_cache_result;
2040 rtp_bridge_unlock(rtp);
2044 /* Check the dynamic list first */
2045 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2046 if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
2047 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2048 rtp->rtp_lookup_code_cache_code = code;
2049 rtp->rtp_lookup_code_cache_result = pt;
2050 rtp_bridge_unlock(rtp);
2055 /* Then the static list */
2056 for (pt = 0; pt < MAX_RTP_PT; ++pt) {
2057 if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
2058 rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
2059 rtp->rtp_lookup_code_cache_code = code;
2060 rtp->rtp_lookup_code_cache_result = pt;
2061 rtp_bridge_unlock(rtp);
2066 rtp_bridge_unlock(rtp);
2071 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
2072 enum ast_rtp_options options)
2076 for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
2077 if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
2079 (code == AST_FORMAT_G726_AAL2) &&
2080 (options & AST_RTP_OPT_G726_NONSTANDARD))
2083 return mimeTypes[i].subtype;
2090 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
2091 const int isAstFormat, enum ast_rtp_options options)
2101 snprintf(end, size, "0x%x (", capability);
2108 for (format = 1; format < AST_RTP_MAX; format <<= 1) {
2109 if (capability & format) {
2110 const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
2112 snprintf(end, size, "%s|", name);
2120 ast_copy_string(start, "nothing)", size);
2127 /*! \brief Open RTP or RTCP socket for a session.
2128 * Print a message on failure.
2130 static int rtp_socket(const char *type)
2132 int s = socket(AF_INET, SOCK_DGRAM, 0);
2136 ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
2138 long flags = fcntl(s, F_GETFL);
2139 fcntl(s, F_SETFL, flags | O_NONBLOCK);
2142 setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
2149 * \brief Initialize a new RTCP session.
2151 * \returns The newly initialized RTCP session.
2153 static struct ast_rtcp *ast_rtcp_new(void)
2155 struct ast_rtcp *rtcp;
2157 if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
2159 rtcp->s = rtp_socket("RTCP");
2160 rtcp->us.sin_family = AF_INET;
2161 rtcp->them.sin_family = AF_INET;
2172 * \brief Initialize a new RTP structure.
2175 void ast_rtp_new_init(struct ast_rtp *rtp)
2178 ast_mutex_init(&rtp->bridge_lock);
2181 rtp->them.sin_family = AF_INET;
2182 rtp->us.sin_family = AF_INET;
2183 rtp->ssrc = ast_random();
2184 rtp->seqno = ast_random() & 0xffff;
2185 ast_set_flag(rtp, FLAG_HAS_DTMF);
2190 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
2192 struct ast_rtp *rtp;
2196 if (!(rtp = ast_calloc(1, sizeof(*rtp))))
2199 ast_rtp_new_init(rtp);
2201 rtp->s = rtp_socket("RTP");
2204 if (sched && rtcpenable) {
2206 rtp->rtcp = ast_rtcp_new();
2210 * Try to bind the RTP port, x, and possibly the RTCP port, x+1 as well.
2211 * Start from a random (even, by RTP spec) port number, and
2212 * iterate until success or no ports are available.
2213 * Note that the requirement of RTP port being even, or RTCP being the
2214 * next one, cannot be enforced in presence of a NAT box because the
2215 * mapping is not under our control.
2217 x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
2218 x = x & ~1; /* make it an even number */
2219 startplace = x; /* remember the starting point */
2220 /* this is constant across the loop */
2221 rtp->us.sin_addr = addr;
2223 rtp->rtcp->us.sin_addr = addr;
2225 rtp->us.sin_port = htons(x);
2226 if (!bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) {
2227 /* bind succeeded, if no rtcp then we are done */
2230 /* have rtcp, try to bind it */
2231 rtp->rtcp->us.sin_port = htons(x + 1);
2232 if (!bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us)))
2233 break; /* success again, we are really done */
2235 * RTCP bind failed, so close and recreate the
2236 * already bound RTP socket for the next round.
2239 rtp->s = rtp_socket("RTP");
2244 * If we get here, there was an error in one of the bind()
2245 * calls, so make sure it is nothing unexpected.
2247 if (errno != EADDRINUSE) {
2248 /* We got an error that wasn't expected, abort! */
2249 ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
2253 * One of the ports is in use. For the next iteration,
2254 * increment by two and handle wraparound.
2255 * If we reach the starting point, then declare failure.
2259 x = (rtpstart + 1) & ~1;
2260 if (x == startplace) {
2261 ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
2268 rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
2269 ast_set_flag(rtp, FLAG_CALLBACK_MODE);
2271 ast_rtp_pt_default(rtp);
2278 close(rtp->rtcp->s);
2279 ast_free(rtp->rtcp);
2285 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
2289 memset(&ia, 0, sizeof(ia));
2290 return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
2293 int ast_rtp_setqos(struct ast_rtp *rtp, int tos, int cos)
2295 return ast_netsock_set_qos(rtp->s, tos, cos);
2298 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2300 rtp->them.sin_port = them->sin_port;
2301 rtp->them.sin_addr = them->sin_addr;
2303 rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
2304 rtp->rtcp->them.sin_addr = them->sin_addr;
2309 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
2311 if ((them->sin_family != AF_INET) ||
2312 (them->sin_port != rtp->them.sin_port) ||
2313 (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
2314 them->sin_family = AF_INET;
2315 them->sin_port = rtp->them.sin_port;
2316 them->sin_addr = rtp->them.sin_addr;
2322 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
2327 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
2329 struct ast_rtp *bridged = NULL;
2331 rtp_bridge_lock(rtp);
2332 bridged = rtp->bridged;
2333 rtp_bridge_unlock(rtp);
2338 void ast_rtp_stop(struct ast_rtp *rtp)
2340 if (rtp->rtcp && rtp->rtcp->schedid > 0) {
2341 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2342 rtp->rtcp->schedid = -1;
2345 memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
2346 memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
2348 memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
2349 memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
2352 ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
2355 void ast_rtp_reset(struct ast_rtp *rtp)
2357 memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
2358 memset(&rtp->txcore, 0, sizeof(rtp->txcore));
2359 memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
2361 rtp->lastdigitts = 0;
2363 rtp->lastividtimestamp = 0;
2364 rtp->lastovidtimestamp = 0;
2365 rtp->lastitexttimestamp = 0;
2366 rtp->lastotexttimestamp = 0;
2367 rtp->lasteventseqn = 0;
2369 rtp->lasttxformat = 0;
2370 rtp->lastrxformat = 0;
2372 rtp->dtmfsamples = 0;
2377 char *ast_rtp_get_quality(struct ast_rtp *rtp, struct ast_rtp_quality *qual)
2381 *themssrc their ssrc
2383 *rxjitter our calculated jitter(rx)
2384 *rxcount no. received packets
2385 *txjitter reported jitter of the other end
2386 *txcount transmitted packets
2387 *rlp remote lost packets
2388 *rtt round trip time
2392 qual->local_ssrc = rtp->ssrc;
2393 qual->local_lostpackets = rtp->rtcp->expected_prior - rtp->rtcp->received_prior;
2394 qual->local_jitter = rtp->rxjitter;
2395 qual->local_count = rtp->rxcount;
2396 qual->remote_ssrc = rtp->themssrc;
2397 qual->remote_lostpackets = rtp->rtcp->reported_lost;
2398 qual->remote_jitter = rtp->rtcp->reported_jitter / 65536.0;
2399 qual->remote_count = rtp->txcount;
2400 qual->rtt = rtp->rtcp->rtt;
2402 snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality), "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f", rtp->ssrc, rtp->themssrc, rtp->rtcp->expected_prior - rtp->rtcp->received_prior, rtp->rxjitter, rtp->rxcount, (double)rtp->rtcp->reported_jitter/65536., rtp->txcount, rtp->rtcp->reported_lost, rtp->rtcp->rtt);
2404 return rtp->rtcp->quality;
2407 void ast_rtp_destroy(struct ast_rtp *rtp)
2409 if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
2410 /*Print some info on the call here */
2411 ast_verbose(" RTP-stats\n");
2412 ast_verbose("* Our Receiver:\n");
2413 ast_verbose(" SSRC: %u\n", rtp->themssrc);
2414 ast_verbose(" Received packets: %u\n", rtp->rxcount);
2415 ast_verbose(" Lost packets: %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
2416 ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
2417 ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
2418 ast_verbose(" RR-count: %u\n", rtp->rtcp->rr_count);
2419 ast_verbose("* Our Sender:\n");
2420 ast_verbose(" SSRC: %u\n", rtp->ssrc);
2421 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2422 ast_verbose(" Lost packets: %u\n", rtp->rtcp->reported_lost);
2423 ast_verbose(" Jitter: %u\n", rtp->rtcp->reported_jitter / (unsigned int)65536.0);
2424 ast_verbose(" SR-count: %u\n", rtp->rtcp->sr_count);
2425 ast_verbose(" RTT: %f\n", rtp->rtcp->rtt);
2428 manager_event(EVENT_FLAG_REPORTING, "RTPReceiverStat", "SSRC: %u\r\n"
2429 "ReceivedPackets: %u\r\n"
2430 "LostPackets: %u\r\n"
2436 rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
2439 rtp->rtcp->rr_count);
2440 manager_event(EVENT_FLAG_REPORTING, "RTPSenderStat", "SSRC: %u\r\n"
2441 "SentPackets: %u\r\n"
2442 "LostPackets: %u\r\n"
2448 rtp->rtcp->reported_lost,
2449 rtp->rtcp->reported_jitter,
2450 rtp->rtcp->sr_count,
2453 ast_smoother_free(rtp->smoother);
2455 ast_io_remove(rtp->io, rtp->ioid);
2459 if (rtp->rtcp->schedid > 0)
2460 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2461 close(rtp->rtcp->s);
2462 ast_free(rtp->rtcp);
2466 ast_mutex_destroy(&rtp->bridge_lock);
2471 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
2475 if (ast_tvzero(rtp->txcore)) {
2476 rtp->txcore = ast_tvnow();
2477 /* Round to 20ms for nice, pretty timestamps */
2478 rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
2480 /* Use previous txcore if available */
2481 t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
2482 ms = ast_tvdiff_ms(t, rtp->txcore);
2485 /* Use what we just got for next time */
2487 return (unsigned int) ms;
2490 /*! \brief Send begin frames for DTMF */
2491 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
2493 unsigned int *rtpheader;
2494 int hdrlen = 12, res = 0, i = 0, payload = 0;
2497 if ((digit <= '9') && (digit >= '0'))
2499 else if (digit == '*')
2501 else if (digit == '#')
2503 else if ((digit >= 'A') && (digit <= 'D'))
2504 digit = digit - 'A' + 12;
2505 else if ((digit >= 'a') && (digit <= 'd'))
2506 digit = digit - 'a' + 12;
2508 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2512 /* If we have no peer, return immediately */
2513 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2516 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
2518 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2519 rtp->send_duration = 160;
2521 /* Get a pointer to the header */
2522 rtpheader = (unsigned int *)data;
2523 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
2524 rtpheader[1] = htonl(rtp->lastdigitts);
2525 rtpheader[2] = htonl(rtp->ssrc);
2527 for (i = 0; i < 2; i++) {
2528 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2529 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2531 ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
2532 ast_inet_ntoa(rtp->them.sin_addr),
2533 ntohs(rtp->them.sin_port), strerror(errno));
2534 if (rtp_debug_test_addr(&rtp->them))
2535 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2536 ast_inet_ntoa(rtp->them.sin_addr),
2537 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2538 /* Increment sequence number */
2540 /* Increment duration */
2541 rtp->send_duration += 160;
2542 /* Clear marker bit and set seqno */
2543 rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
2546 /* Since we received a begin, we can safely store the digit and disable any compensation */
2547 rtp->sending_digit = 1;
2548 rtp->send_digit = digit;
2549 rtp->send_payload = payload;
2554 /*! \brief Send continuation frame for DTMF */
2555 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
2557 unsigned int *rtpheader;
2558 int hdrlen = 12, res = 0;
2561 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2564 /* Setup packet to send */
2565 rtpheader = (unsigned int *)data;
2566 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2567 rtpheader[1] = htonl(rtp->lastdigitts);
2568 rtpheader[2] = htonl(rtp->ssrc);
2569 rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
2570 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2573 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2575 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2576 ast_inet_ntoa(rtp->them.sin_addr),
2577 ntohs(rtp->them.sin_port), strerror(errno));
2578 if (rtp_debug_test_addr(&rtp->them))
2579 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2580 ast_inet_ntoa(rtp->them.sin_addr),
2581 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2583 /* Increment sequence number */
2585 /* Increment duration */
2586 rtp->send_duration += 160;
2591 /*! \brief Send end packets for DTMF */
2592 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
2594 unsigned int *rtpheader;
2595 int hdrlen = 12, res = 0, i = 0;
2598 /* If no address, then bail out */
2599 if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
2602 if ((digit <= '9') && (digit >= '0'))
2604 else if (digit == '*')
2606 else if (digit == '#')
2608 else if ((digit >= 'A') && (digit <= 'D'))
2609 digit = digit - 'A' + 12;
2610 else if ((digit >= 'a') && (digit <= 'd'))
2611 digit = digit - 'a' + 12;
2613 ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
2617 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2619 rtpheader = (unsigned int *)data;
2620 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
2621 rtpheader[1] = htonl(rtp->lastdigitts);
2622 rtpheader[2] = htonl(rtp->ssrc);
2623 rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
2625 rtpheader[3] |= htonl((1 << 23));
2626 rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
2627 /* Send 3 termination packets */
2628 for (i = 0; i < 3; i++) {
2629 res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
2631 ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
2632 ast_inet_ntoa(rtp->them.sin_addr),
2633 ntohs(rtp->them.sin_port), strerror(errno));
2634 if (rtp_debug_test_addr(&rtp->them))
2635 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2636 ast_inet_ntoa(rtp->them.sin_addr),
2637 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
2639 rtp->sending_digit = 0;
2640 rtp->send_digit = 0;
2641 /* Increment lastdigitts */
2642 rtp->lastdigitts += 960;
2648 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
2649 int ast_rtcp_send_h261fur(void *data)
2651 struct ast_rtp *rtp = data;
2654 rtp->rtcp->sendfur = 1;
2655 res = ast_rtcp_write(data);
2660 /*! \brief Send RTCP sender's report */
2661 static int ast_rtcp_write_sr(const void *data)
2663 struct ast_rtp *rtp = (struct ast_rtp *)data;
2667 unsigned int now_lsw;
2668 unsigned int now_msw;
2669 unsigned int *rtcpheader;
2671 unsigned int extended;
2672 unsigned int expected;
2673 unsigned int expected_interval;
2674 unsigned int received_interval;
2677 struct timeval dlsr;
2680 /* Commented condition is always not NULL if rtp->rtcp is not NULL */
2681 if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
2684 if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
2685 ast_verbose("RTCP SR transmission error, rtcp halted\n");
2686 if (rtp->rtcp->schedid > 0)
2687 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2688 rtp->rtcp->schedid = -1;
2692 gettimeofday(&now, NULL);
2693 timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
2694 rtcpheader = (unsigned int *)bdata;
2695 rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
2696 rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
2697 rtcpheader[3] = htonl(now_lsw); /* now, LSW */
2698 rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
2699 rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
2700 rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
2703 extended = rtp->cycles + rtp->lastrxseqno;
2704 expected = extended - rtp->seedrxseqno + 1;
2705 if (rtp->rxcount > expected)
2706 expected += rtp->rxcount - expected;
2707 lost = expected - rtp->rxcount;
2708 expected_interval = expected - rtp->rtcp->expected_prior;
2709 rtp->rtcp->expected_prior = expected;
2710 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2711 rtp->rtcp->received_prior = rtp->rxcount;
2712 lost_interval = expected_interval - received_interval;
2713 if (expected_interval == 0 || lost_interval <= 0)
2716 fraction = (lost_interval << 8) / expected_interval;
2717 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2718 rtcpheader[7] = htonl(rtp->themssrc);
2719 rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2720 rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2721 rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
2722 rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
2723 rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2726 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
2728 if (rtp->rtcp->sendfur) {
2729 rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
2730 rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
2732 rtp->rtcp->sendfur = 0;
2735 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2736 /* it can change mid call, and SDES can't) */
2737 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2738 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2739 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2742 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2744 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));
2745 if (rtp->rtcp->schedid > 0)
2746 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2747 rtp->rtcp->schedid = -1;
2751 /* FIXME Don't need to get a new one */
2752 gettimeofday(&rtp->rtcp->txlsr, NULL);
2753 rtp->rtcp->sr_count++;
2755 rtp->rtcp->lastsrtxcount = rtp->txcount;
2757 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2758 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
2759 ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
2760 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
2761 ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
2762 ast_verbose(" Sent packets: %u\n", rtp->txcount);
2763 ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
2764 ast_verbose(" Report block:\n");
2765 ast_verbose(" Fraction lost: %u\n", fraction);
2766 ast_verbose(" Cumulative loss: %u\n", lost);
2767 ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
2768 ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
2769 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
2771 manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To %s:%d\r\n"
2773 "SentNTP: %u.%010u\r\n"
2775 "SentPackets: %u\r\n"
2776 "SentOctets: %u\r\n"
2778 "FractionLost: %u\r\n"
2779 "CumulativeLoss: %u\r\n"
2780 "IAJitter: %.4f\r\n"
2781 "TheirLastSR: %u\r\n"
2782 "DLSR: %4.4f (sec)\r\n",
2783 ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port),
2785 (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
2792 rtp->rtcp->themrxlsr,
2793 (double)(ntohl(rtcpheader[12])/65536.0));
2797 /*! \brief Send RTCP recipient's report */
2798 static int ast_rtcp_write_rr(const void *data)
2800 struct ast_rtp *rtp = (struct ast_rtp *)data;
2804 unsigned int extended;
2805 unsigned int expected;
2806 unsigned int expected_interval;
2807 unsigned int received_interval;
2810 unsigned int *rtcpheader;
2812 struct timeval dlsr;
2815 if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
2818 if (!rtp->rtcp->them.sin_addr.s_addr) {
2819 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
2820 if (rtp->rtcp->schedid > 0)
2821 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2822 rtp->rtcp->schedid = -1;
2826 extended = rtp->cycles + rtp->lastrxseqno;
2827 expected = extended - rtp->seedrxseqno + 1;
2828 lost = expected - rtp->rxcount;
2829 expected_interval = expected - rtp->rtcp->expected_prior;
2830 rtp->rtcp->expected_prior = expected;
2831 received_interval = rtp->rxcount - rtp->rtcp->received_prior;
2832 rtp->rtcp->received_prior = rtp->rxcount;
2833 lost_interval = expected_interval - received_interval;
2834 if (expected_interval == 0 || lost_interval <= 0)
2837 fraction = (lost_interval << 8) / expected_interval;
2838 gettimeofday(&now, NULL);
2839 timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
2840 rtcpheader = (unsigned int *)bdata;
2841 rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
2842 rtcpheader[1] = htonl(rtp->ssrc);
2843 rtcpheader[2] = htonl(rtp->themssrc);
2844 rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
2845 rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
2846 rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
2847 rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
2848 rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
2850 if (rtp->rtcp->sendfur) {
2851 rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
2852 rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
2854 rtp->rtcp->sendfur = 0;
2857 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2858 it can change mid call, and SDES can't) */
2859 rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
2860 rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
2861 rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2864 res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
2867 ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
2868 /* Remove the scheduler */
2869 if (rtp->rtcp->schedid > 0)
2870 ast_sched_del(rtp->sched, rtp->rtcp->schedid);
2871 rtp->rtcp->schedid = -1;
2875 rtp->rtcp->rr_count++;
2877 if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
2878 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2879 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2880 " IA jitter: %.4f\n"
2881 " Their last SR: %u\n"
2882 " DLSR: %4.4f (sec)\n\n",
2883 ast_inet_ntoa(rtp->rtcp->them.sin_addr),
2884 ntohs(rtp->rtcp->them.sin_port),
2885 rtp->ssrc, rtp->themssrc, fraction, lost,
2887 rtp->rtcp->themrxlsr,
2888 (double)(ntohl(rtcpheader[7])/65536.0));
2894 /*! \brief Write and RTCP packet to the far end
2895 * \note Decide if we are going to send an SR (with Reception Block) or RR
2896 * RR is sent if we have not sent any rtp packets in the previous interval */
2897 static int ast_rtcp_write(const void *data)
2899 struct ast_rtp *rtp = (struct ast_rtp *)data;
2902 if (!rtp || !rtp->rtcp)
2905 if (rtp->txcount > rtp->rtcp->lastsrtxcount)
2906 res = ast_rtcp_write_sr(data);
2908 res = ast_rtcp_write_rr(data);
2913 /*! \brief generate comfort noice (CNG) */
2914 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
2916 unsigned int *rtpheader;
2921 level = 127 - (level & 0x7f);
2922 payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
2924 /* If we have no peer, return immediately */
2925 if (!rtp->them.sin_addr.s_addr)
2928 rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2930 /* Get a pointer to the header */
2931 rtpheader = (unsigned int *)data;
2932 rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
2933 rtpheader[1] = htonl(rtp->lastts);
2934 rtpheader[2] = htonl(rtp->ssrc);
2936 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
2937 res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
2939 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));
2940 if (rtp_debug_test_addr(&rtp->them))
2941 ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
2942 , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
2948 /*! \brief Write RTP packet with audio or video media frames into UDP packet */
2949 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
2951 unsigned char *rtpheader;
2958 ms = calc_txstamp(rtp, &f->delivery);
2959 /* Default prediction */
2960 if (f->subclass < AST_FORMAT_MAX_AUDIO) {
2961 pred = rtp->lastts + f->samples;
2963 /* Re-calculate last TS */
2964 rtp->lastts = rtp->lastts + ms * 8;
2965 if (ast_tvzero(f->delivery)) {
2966 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
2967 and if so, go with our prediction */
2968 if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
2971 ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
2975 } else if(f->subclass < AST_FORMAT_MAX_VIDEO) {
2976 mark = f->subclass & 0x1;
2977 pred = rtp->lastovidtimestamp + f->samples;
2978 /* Re-calculate last TS */
2979 rtp->lastts = rtp->lastts + ms * 90;
2980 /* If it's close to our prediction, go for it */
2981 if (ast_tvzero(f->delivery)) {
2982 if (abs(rtp->lastts - pred) < 7200) {
2984 rtp->lastovidtimestamp += f->samples;
2986 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);
2987 rtp->lastovidtimestamp = rtp->lastts;
2991 pred = rtp->lastotexttimestamp + f->samples;
2992 /* Re-calculate last TS */
2993 rtp->lastts = rtp->lastts + ms * 90;
2994 /* If it's close to our prediction, go for it */
2995 if (ast_tvzero(f->delivery)) {
2996 if (abs(rtp->lastts - pred) < 7200) {
2998 rtp->lastotexttimestamp += f->samples;
3000 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);
3001 rtp->lastotexttimestamp = rtp->lastts;
3005 /* If the timestamp for non-digit packets has moved beyond the timestamp
3006 for digits, update the digit timestamp.
3008 if (rtp->lastts > rtp->lastdigitts)
3009 rtp->lastdigitts = rtp->lastts;
3011 if (f->has_timing_info)
3012 rtp->lastts = f->ts * 8;
3014 /* Get a pointer to the header */
3015 rtpheader = (unsigned char *)(f->data - hdrlen);
3017 put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
3018 put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
3019 put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
3021 if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
3022 res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
3024 if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
3025 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));
3026 } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
3027 /* Only give this error message once if we are not RTP debugging */
3028 if (option_debug || rtpdebug)
3029 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));
3030 ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
3034 rtp->txoctetcount +=(res - hdrlen);
3036 if (rtp->rtcp && rtp->rtcp->schedid < 1)
3037 rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
3040 if (rtp_debug_test_addr(&rtp->them))
3041 ast_verbose("Sent RTP packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3042 ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
3050 int ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
3053 for (x = 0; x < 32; x++) { /* Ugly way */
3054 rtp->pref.order[x] = prefs->order[x];
3055 rtp->pref.framing[x] = prefs->framing[x];
3058 ast_smoother_free(rtp->smoother);
3059 rtp->smoother = NULL;
3063 struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
3068 int ast_rtp_codec_getformat(int pt)
3070 if (pt < 0 || pt > MAX_RTP_PT)
3071 return 0; /* bogus payload type */
3073 if (static_RTP_PT[pt].isAstFormat)
3074 return static_RTP_PT[pt].code;
3079 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
3081 struct ast_frame *f;
3087 /* If we have no peer, return immediately */
3088 if (!rtp->them.sin_addr.s_addr)
3091 /* If there is no data length, return immediately */
3095 /* Make sure we have enough space for RTP header */
3096 if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO) && (_f->frametype != AST_FRAME_TEXT)) {
3097 ast_log(LOG_WARNING, "RTP can only send voice, video and text\n");
3101 /* The bottom bit of a video subclass contains the marker bit */
3102 subclass = _f->subclass;
3103 if (_f->frametype == AST_FRAME_VIDEO)
3106 codec = ast_rtp_lookup_code(rtp, 1, subclass);
3108 ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
3112 if (rtp->lasttxformat != subclass) {
3113 /* New format, reset the smoother */
3114 ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
3115 rtp->lasttxformat = subclass;
3117 ast_smoother_free(rtp->smoother);
3118 rtp->smoother = NULL;
3121 if (!rtp->smoother && subclass != AST_FORMAT_SPEEX) {
3122 struct ast_format_list fmt = ast_codec_pref_getsize(&rtp->pref, subclass);
3123 if (fmt.inc_ms) { /* if codec parameters is set / avoid division by zero */
3124 if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
3125 ast_log(LOG_WARNING, "Unable to create smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
3129 ast_smoother_set_flags(rtp->smoother, fmt.flags);
3130 ast_debug(1, "Created smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
3133 if (rtp->smoother) {
3134 if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
3135 ast_smoother_feed_be(rtp->smoother, _f);
3137 ast_smoother_feed(rtp->smoother, _f);
3140 while ((f = ast_smoother_read(rtp->smoother)) && (f->data))
3141 ast_rtp_raw_write(rtp, f, codec);
3143 /* Don't buffer outgoing frames; send them one-per-packet: */
3144 if (_f->offset < hdrlen)
3145 f = ast_frdup(_f); /*! \bug XXX this might never be free'd. Why do we do this? */
3149 ast_rtp_raw_write(rtp, f, codec);
3157 /*! \brief Unregister interface to channel driver */
3158 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
3160 AST_RWLIST_WRLOCK(&protos);
3161 AST_RWLIST_REMOVE(&protos, proto, list);
3162 AST_RWLIST_UNLOCK(&protos);
3165 /*! \brief Register interface to channel driver */
3166 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
3168 struct ast_rtp_protocol *cur;
3170 AST_RWLIST_WRLOCK(&protos);
3171 AST_RWLIST_TRAVERSE(&protos, cur, list) {
3172 if (!strcmp(cur->type, proto->type)) {
3173 ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
3174 AST_RWLIST_UNLOCK(&protos);
3178 AST_RWLIST_INSERT_HEAD(&protos, proto, list);
3179 AST_RWLIST_UNLOCK(&protos);
3184 /*! \brief Bridge loop for true native bridge (reinvite) */
3185 static enum ast_bridge_result bridge_native_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp *p0, struct ast_rtp *p1, struct ast_rtp *vp0, struct ast_rtp *vp1, struct ast_rtp *tp0, struct ast_rtp *tp1, struct ast_rtp_protocol *pr0, struct ast_rtp_protocol *pr1, int codec0, int codec1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
3187 struct ast_frame *fr = NULL;
3188 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
3189 int oldcodec0 = codec0, oldcodec1 = codec1;
3190 struct sockaddr_in ac1 = {0,}, vac1 = {0,}, tac1 = {0,}, ac0 = {0,}, vac0 = {0,}, tac0 = {0,};
3191 struct sockaddr_in t1 = {0,}, vt1 = {0,}, tt1 = {0,}, t0 = {0,}, vt0 = {0,}, tt0 = {0,};
3193 /* Set it up so audio goes directly between the two endpoints */
3195 /* Test the first channel */
3196 if (!(pr0->set_rtp_peer(c0, p1, vp1, tp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))) {
3197 ast_rtp_get_peer(p1, &ac1);
3199 ast_rtp_get_peer(vp1, &vac1);
3201 ast_rtp_get_peer(tp1, &tac1);
3203 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
3205 /* Test the second channel */
3206 if (!(pr1->set_rtp_peer(c1, p0, vp0, tp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))) {
3207 ast_rtp_get_peer(p0, &ac0);
3209 ast_rtp_get_peer(vp0, &vac0);
3211 ast_rtp_get_peer(tp0, &tac0);
3213 ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c1->name, c0->name);
3215 /* Now we can unlock and move into our loop */
3216 ast_channel_unlock(c0);
3217 ast_channel_unlock(c1);
3219 ast_poll_channel_add(c0, c1);
3221 /* Throw our channels into the structure and enter the loop */
3226 /* Check if anything changed */
3227 if ((c0->tech_pvt != pvt0) ||
3228 (c1->tech_pvt != pvt1) ||
3229 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
3230 ast_debug(1, "Oooh, something is weird, backing out\n");
3231 if (c0->tech_pvt == pvt0)
3232 if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
3233 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
3234 if (c1->tech_pvt == pvt1)
3235 if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
3236 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
3237 ast_poll_channel_del(c0, c1);
3238 return AST_BRIDGE_RETRY;
3241 /* Check if they have changed their address */
3242 ast_rtp_get_peer(p1, &t1);
3244 ast_rtp_get_peer(vp1, &vt1);
3246 ast_rtp_get_peer(tp1, &tt1);
3248 codec1 = pr1->get_codec(c1);
3249 ast_rtp_get_peer(p0, &t0);
3251 ast_rtp_get_peer(vp0, &vt0);
3253 ast_rtp_get_peer(tp0, &tt0);
3255 codec0 = pr0->get_codec(c0);
3256 if ((inaddrcmp(&t1, &ac1)) ||
3257 (vp1 && inaddrcmp(&vt1, &vac1)) ||
3258 (tp1 && inaddrcmp(&tt1, &tac1)) ||
3259 (codec1 != oldcodec1)) {
3260 ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
3261 c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
3262 ast_debug(2, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
3263 c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
3264 ast_debug(2, "Oooh, '%s' changed end taddress to %s:%d (format %d)\n",
3265 c1->name, ast_inet_ntoa(tt1.sin_addr), ntohs(tt1.sin_port), codec1);
3266 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3267 c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
3268 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3269 c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
3270 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3271 c1->name, ast_inet_ntoa(tac1.sin_addr), ntohs(tac1.sin_port), oldcodec1);
3272 if (pr0->set_rtp_peer(c0, t1.sin_addr.s_addr ? p1 : NULL, vt1.sin_addr.s_addr ? vp1 : NULL, tt1.sin_addr.s_addr ? tp1 : NULL, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
3273 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
3274 memcpy(&ac1, &t1, sizeof(ac1));
3275 memcpy(&vac1, &vt1, sizeof(vac1));
3276 memcpy(&tac1, &tt1, sizeof(tac1));
3279 if ((inaddrcmp(&t0, &ac0)) ||
3280 (vp0 && inaddrcmp(&vt0, &vac0)) ||
3281 (tp0 && inaddrcmp(&tt0, &tac0))) {
3282 ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
3283 c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
3284 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3285 c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
3286 if (pr1->set_rtp_peer(c1, t0.sin_addr.s_addr ? p0 : NULL, vt0.sin_addr.s_addr ? vp0 : NULL, tt0.sin_addr.s_addr ? tp0 : NULL, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
3287 ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
3288 memcpy(&ac0, &t0, sizeof(ac0));
3289 memcpy(&vac0, &vt0, sizeof(vac0));
3290 memcpy(&tac0, &tt0, sizeof(tac0));
3294 /* Wait for frame to come in on the channels */
3295 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
3297 if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
3298 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
3299 if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
3300 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
3301 return AST_BRIDGE_RETRY;
3303 ast_debug(1, "Ooh, empty read...\n");
3304 if (ast_check_hangup(c0) || ast_check_hangup(c1))
3309 other = (who == c0) ? c1 : c0;
3310 if (!fr || ((fr->frametype == AST_FRAME_DTMF) &&
3311 (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
3312 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
3313 /* Break out of bridge */
3316 ast_debug(1, "Oooh, got a %s\n", fr ? "digit" : "hangup");
3317 if (c0->tech_pvt == pvt0)
3318 if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
3319 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
3320 if (c1->tech_pvt == pvt1)
3321 if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
3322 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
3323 ast_poll_channel_del(c0, c1);
3324 return AST_BRIDGE_COMPLETE;
3325 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3326 if ((fr->subclass == AST_CONTROL_HOLD) ||
3327 (fr->subclass == AST_CONTROL_UNHOLD) ||
3328 (fr->subclass == AST_CONTROL_VIDUPDATE)) {
3329 if (fr->subclass == AST_CONTROL_HOLD) {
3330 /* If we someone went on hold we want the other side to reinvite back to us */
3332 pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0);
3334 pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0);
3335 } else if (fr->subclass == AST_CONTROL_UNHOLD) {
3336 /* If they went off hold they should go back to being direct */
3338 pr1->set_rtp_peer(c1, p0, vp0, tp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE));
3340 pr0->set_rtp_peer(c0, p1, vp1, tp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE));
3342 /* Update local address information */
3343 ast_rtp_get_peer(p0, &t0);
3344 memcpy(&ac0, &t0, sizeof(ac0));
3345 ast_rtp_get_peer(p1, &t1);
3346 memcpy(&ac1, &t1, sizeof(ac1));
3347 /* Update codec information */
3349 oldcodec0 = codec0 = pr0->get_codec(c0);
3351 oldcodec1 = codec1 = pr1->get_codec(c1);
3352 ast_indicate_data(other, fr->subclass, fr->data, fr->datalen);
3357 ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
3358 return AST_BRIDGE_COMPLETE;
3361 if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
3362 (fr->frametype == AST_FRAME_DTMF) ||
3363 (fr->frametype == AST_FRAME_VOICE) ||
3364 (fr->frametype == AST_FRAME_VIDEO) ||
3365 (fr->frametype == AST_FRAME_IMAGE) ||
3366 (fr->frametype == AST_FRAME_HTML) ||
3367 (fr->frametype == AST_FRAME_MODEM) ||
3368 (fr->frametype == AST_FRAME_TEXT)) {
3369 ast_write(other, fr);
3381 ast_poll_channel_del(c0, c1);
3383 if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
3384 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
3385 if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
3386 ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
3388 return AST_BRIDGE_FAILED;
3391 /*! \brief P2P RTP Callback */
3393 static int p2p_rtp_callback(int *id, int fd, short events, void *cbdata)
3395 int res = 0, hdrlen = 12;
3396 struct sockaddr_in sin;
3398 unsigned int *header;
3399 struct ast_rtp *rtp = cbdata, *bridged = NULL;
3405 if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
3408 header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
3410 /* If NAT support is turned on, then see if we need to change their address */
3412 ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
3413 (rtp->them.sin_port != sin.sin_port))) {
3416 ast_set_flag(rtp, FLAG_NAT_ACTIVE);
3417 if (option_debug || rtpdebug)
3418 ast_debug(0, "P2P 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));
3421 /* Write directly out to other RTP stream if bridged */
3422 if ((bridged = ast_rtp_get_bridged(rtp)))
3423 bridge_p2p_rtp_write(rtp, bridged, header, res, hdrlen);
3428 /*! \brief Helper function to switch a channel and RTP stream into callback mode */
3429 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
3431 /* If we need DTMF, are looking for STUN, or we have no IO structure then we can't do direct callback */
3432 if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) || ast_test_flag(rtp, FLAG_HAS_STUN) || !rtp->io)
3435 /* If the RTP structure is already in callback mode, remove it temporarily */
3437 ast_io_remove(rtp->io, rtp->ioid);
3441 /* Steal the file descriptors from the channel */
3444 /* Now, fire up callback mode */
3445 iod[0] = ast_io_add(rtp->io, ast_rtp_fd(rtp), p2p_rtp_callback, AST_IO_IN, rtp);
3450 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
3456 /*! \brief Helper function to switch a channel and RTP stream out of callback mode */
3457 static int p2p_callback_disable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
3459 ast_channel_lock(chan);
3461 /* Remove the callback from the IO context */
3462 ast_io_remove(rtp->io, iod[0]);
3464 /* Restore file descriptors */
3465 chan->fds[0] = ast_rtp_fd(rtp);
3466 ast_channel_unlock(chan);
3468 /* Restore callback mode if previously used */
3469 if (ast_test_flag(rtp, FLAG_CALLBACK_MODE))
3470 rtp->ioid = ast_io_add(rtp->io, ast_rtp_fd(rtp), rtpread, AST_IO_IN, rtp);
3475 /*! \brief Helper function that sets what an RTP structure is bridged to */
3476 static void p2p_set_bridge(struct ast_rtp *rtp0, struct ast_rtp *rtp1)
3478 rtp_bridge_lock(rtp0);
3479 rtp0->bridged = rtp1;
3480 rtp_bridge_unlock(rtp0);
3485 /*! \brief Bridge loop for partial native bridge (packet2packet)
3487 In p2p mode, Asterisk is a very basic RTP proxy, just forwarding whatever
3488 rtp/rtcp we get in to the channel.
3489 \note this currently only works for Audio
3491 static enum ast_bridge_result bridge_p2p_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp *p0, struct ast_rtp *p1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
3493 struct ast_frame *fr = NULL;
3494 struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
3495 int *p0_iod[2] = {NULL, NULL}, *p1_iod[2] = {NULL, NULL};
3496 int p0_callback = 0, p1_callback = 0;
3497 enum ast_bridge_result res = AST_BRIDGE_FAILED;
3499 /* Okay, setup each RTP structure to do P2P forwarding */
3500 ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
3501 p2p_set_bridge(p0, p1);
3502 ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
3503 p2p_set_bridge(p1, p0);
3505 /* Activate callback modes if possible */
3506 p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
3507 p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
3509 /* Now let go of the channel locks and be on our way */
3510 ast_channel_unlock(c0);
3511 ast_channel_unlock(c1);
3513 ast_poll_channel_add(c0, c1);
3515 /* Go into a loop forwarding frames until we don't need to anymore */
3520 /* Check if anything changed */
3521 if ((c0->tech_pvt != pvt0) ||
3522 (c1->tech_pvt != pvt1) ||
3523 (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
3524 ast_debug(3, "p2p-rtp-bridge: Oooh, something is weird, backing out\n");
3525 /* If a masquerade needs to happen we have to try to read in a frame so that it actually happens. Without this we risk being called again and going into a loop */
3526 if ((c0->masq || c0->masqr) && (fr = ast_read(c0)))
3528 if ((c1->masq || c1->masqr) && (fr = ast_read(c1)))
3530 res = AST_BRIDGE_RETRY;
3533 /* Wait on a channel to feed us a frame */
3534 if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
3536 res = AST_BRIDGE_RETRY;
3539 if (option_debug > 2)
3540 ast_log(LOG_NOTICE, "p2p-rtp-bridge: Ooh, empty read...\n");
3541 if (ast_check_hangup(c0) || ast_check_hangup(c1))
3545 /* Read in frame from channel */
3547 other = (who == c0) ? c1 : c0;
3548 /* Depending on the frame we may need to break out of our bridge */
3549 if (!fr || ((fr->frametype == AST_FRAME_DTMF) &&
3550 ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
3551 ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
3552 /* Record received frame and who */
3555 ast_debug(3, "p2p-rtp-bridge: Ooh, got a %s\n", fr ? "digit" : "hangup");
3556 res = AST_BRIDGE_COMPLETE;
3558 } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3559 if ((fr->subclass == AST_CONTROL_HOLD) ||
3560 (fr->subclass == AST_CONTROL_UNHOLD) ||
3561 (fr->subclass == AST_CONTROL_VIDUPDATE)) {
3562 /* If we are going on hold, then break callback mode and P2P bridging */
3563 if (fr->subclass == AST_CONTROL_HOLD) {
3565 p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
3567 p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
3568 p2p_set_bridge(p0, NULL);
3569 p2p_set_bridge(p1, NULL);
3570 } else if (fr->subclass == AST_CONTROL_UNHOLD) {
3571 /* If we are off hold, then go back to callback mode and P2P bridging */