2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
22 * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
24 * \author Mark Spencer <markster@digium.com>
26 * \note RTP is defined in RFC 3550.
31 ASTERISK_FILE_VERSION(__FILE__
, "$Revision$")
37 #include "asterisk/rtp.h"
38 #include "asterisk/frame.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/acl.h"
41 #include "asterisk/config.h"
42 #include "asterisk/lock.h"
43 #include "asterisk/utils.h"
44 #include "asterisk/netsock.h"
45 #include "asterisk/cli.h"
46 #include "asterisk/manager.h"
47 #include "asterisk/unaligned.h"
49 #define MAX_TIMESTAMP_SKEW 640
51 #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
52 #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
53 #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
54 #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
56 #define RTCP_PT_FUR 192
57 #define RTCP_PT_SR 200
58 #define RTCP_PT_RR 201
59 #define RTCP_PT_SDES 202
60 #define RTCP_PT_BYE 203
61 #define RTCP_PT_APP 204
65 #define DEFAULT_DTMF_TIMEOUT 3000 /*!< samples */
67 static int dtmftimeout
= DEFAULT_DTMF_TIMEOUT
;
69 static int rtpstart
; /*!< First port for RTP sessions (set in rtp.conf) */
70 static int rtpend
; /*!< Last port for RTP sessions (set in rtp.conf) */
71 static int rtpdebug
; /*!< Are we debugging? */
72 static int rtcpdebug
; /*!< Are we debugging RTCP? */
73 static int rtcpstats
; /*!< Are we debugging RTCP? */
74 static int rtcpinterval
= RTCP_DEFAULT_INTERVALMS
; /*!< Time between rtcp reports in millisecs */
75 static int stundebug
; /*!< Are we debugging stun? */
76 static struct sockaddr_in rtpdebugaddr
; /*!< Debug packets to/from this host */
77 static struct sockaddr_in rtcpdebugaddr
; /*!< Debug RTCP packets to/from this host */
79 static int nochecksums
;
83 enum strict_rtp_state
{
84 STRICT_RTP_OPEN
= 0, /*! No RTP packets should be dropped, all sources accepted */
85 STRICT_RTP_LEARN
, /*! Accept next packet as source */
86 STRICT_RTP_CLOSED
, /*! Drop all RTP packets not coming from source that was learned */
89 /* Uncomment this to enable more intense native bridging, but note: this is currently buggy */
90 /* #define P2P_INTENSE */
93 * \brief Structure representing a RTP session.
95 * 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 [...]"
98 /*! \brief The value of each payload format mapping: */
99 struct rtpPayloadType
{
100 int isAstFormat
; /*!< whether the following code is an AST_FORMAT */
105 /*! \brief RTP session description */
109 unsigned char rawdata
[8192 + AST_FRIENDLY_OFFSET
];
110 unsigned int ssrc
; /*!< Synchronization source, RFC 3550, page 10. */
111 unsigned int themssrc
; /*!< Their SSRC */
114 unsigned int lastrxts
;
115 unsigned int lastividtimestamp
;
116 unsigned int lastovidtimestamp
;
117 unsigned int lastitexttimestamp
;
118 unsigned int lastotexttimestamp
;
119 unsigned int lasteventseqn
;
120 int lastrxseqno
; /*!< Last received sequence number */
121 unsigned short seedrxseqno
; /*!< What sequence number did they start with?*/
122 unsigned int seedrxts
; /*!< What RTP timestamp did they start with? */
123 unsigned int rxcount
; /*!< How many packets have we received? */
124 unsigned int rxoctetcount
; /*!< How many octets have we received? should be rxcount *160*/
125 unsigned int txcount
; /*!< How many packets have we sent? */
126 unsigned int txoctetcount
; /*!< How many octets have we sent? (txcount*160)*/
127 unsigned int cycles
; /*!< Shifted count of sequence number cycles */
128 double rxjitter
; /*!< Interarrival jitter at the moment */
129 double rxtransit
; /*!< Relative transit time for previous packet */
133 int rtptimeout
; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
134 int rtpholdtimeout
; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
135 int rtpkeepalive
; /*!< Send RTP comfort noice packets for keepalive */
137 /* DTMF Reception Variables */
139 unsigned int lastevent
;
141 unsigned int dtmfsamples
;
142 /* DTMF Transmission Variables */
143 unsigned int lastdigitts
;
144 char sending_digit
; /*!< boolean - are we sending digits */
145 char send_digit
; /*!< digit we are sending */
150 struct sockaddr_in us
; /*!< Socket representation of the local endpoint. */
151 struct sockaddr_in them
; /*!< Socket representation of the remote endpoint. */
152 struct timeval rxcore
;
153 struct timeval txcore
;
154 double drxcore
; /*!< The double representation of the first received packet */
155 struct timeval lastrx
; /*!< timeval when we last received a packet */
156 struct timeval dtmfmute
;
157 struct ast_smoother
*smoother
;
159 unsigned short seqno
; /*!< Sequence number, RFC 3550, page 13. */
160 unsigned short rxseqno
;
161 struct sched_context
*sched
;
162 struct io_context
*io
;
164 ast_rtp_callback callback
;
166 ast_mutex_t bridge_lock
;
168 struct rtpPayloadType current_RTP_PT
[MAX_RTP_PT
];
169 int rtp_lookup_code_cache_isAstFormat
; /*!< a cache for the result of rtp_lookup_code(): */
170 int rtp_lookup_code_cache_code
;
171 int rtp_lookup_code_cache_result
;
172 struct ast_rtcp
*rtcp
;
173 struct ast_codec_pref pref
;
174 struct ast_rtp
*bridged
; /*!< Who we are Packet bridged to */
176 enum strict_rtp_state strict_rtp_state
; /*!< Current state that strict RTP protection is in */
177 struct sockaddr_in strict_rtp_address
; /*!< Remote address information for strict RTP purposes */
179 int set_marker_bit
:1; /*!< Whether to set the marker bit or not */
182 /* Forward declarations */
183 static int ast_rtcp_write(const void *data
);
184 static void timeval2ntp(struct timeval tv
, unsigned int *msw
, unsigned int *lsw
);
185 static int ast_rtcp_write_sr(const void *data
);
186 static int ast_rtcp_write_rr(const void *data
);
187 static unsigned int ast_rtcp_calc_interval(struct ast_rtp
*rtp
);
188 static int ast_rtp_senddigit_continuation(struct ast_rtp
*rtp
);
189 int ast_rtp_senddigit_end(struct ast_rtp
*rtp
, char digit
);
191 #define FLAG_3389_WARNING (1 << 0)
192 #define FLAG_NAT_ACTIVE (3 << 1)
193 #define FLAG_NAT_INACTIVE (0 << 1)
194 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
195 #define FLAG_HAS_DTMF (1 << 3)
196 #define FLAG_P2P_SENT_MARK (1 << 4)
197 #define FLAG_P2P_NEED_DTMF (1 << 5)
198 #define FLAG_CALLBACK_MODE (1 << 6)
199 #define FLAG_DTMF_COMPENSATE (1 << 7)
200 #define FLAG_HAS_STUN (1 << 8)
203 * \brief Structure defining an RTCP session.
205 * The concept "RTCP session" is not defined in RFC 3550, but since
206 * this structure is analogous to ast_rtp, which tracks a RTP session,
207 * it is logical to think of this as a RTCP session.
209 * RTCP packet is defined on page 9 of RFC 3550.
213 int s
; /*!< Socket */
214 struct sockaddr_in us
; /*!< Socket representation of the local endpoint. */
215 struct sockaddr_in them
; /*!< Socket representation of the remote endpoint. */
216 unsigned int soc
; /*!< What they told us */
217 unsigned int spc
; /*!< What they told us */
218 unsigned int themrxlsr
; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
219 struct timeval rxlsr
; /*!< Time when we got their last SR */
220 struct timeval txlsr
; /*!< Time when we sent or last SR*/
221 unsigned int expected_prior
; /*!< no. packets in previous interval */
222 unsigned int received_prior
; /*!< no. packets received in previous interval */
223 int schedid
; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
224 unsigned int rr_count
; /*!< number of RRs we've sent, not including report blocks in SR's */
225 unsigned int sr_count
; /*!< number of SRs we've sent */
226 unsigned int lastsrtxcount
; /*!< Transmit packet count when last SR sent */
227 double accumulated_transit
; /*!< accumulated a-dlsr-lsr */
228 double rtt
; /*!< Last reported rtt */
229 unsigned int reported_jitter
; /*!< The contents of their last jitter entry in the RR */
230 unsigned int reported_lost
; /*!< Reported lost packets in their RR */
231 char quality
[AST_MAX_USER_FIELD
];
240 * \brief STUN support code
242 * This code provides some support for doing STUN transactions.
243 * Eventually it should be moved elsewhere as other protocols
244 * than RTP can benefit from it - e.g. SIP.
245 * STUN is described in RFC3489 and it is based on the exchange
246 * of UDP packets between a client and one or more servers to
247 * determine the externally visible address (and port) of the client
248 * once it has gone through the NAT boxes that connect it to the
250 * The simplest request packet is just the header defined in
251 * struct stun_header, and from the response we may just look at
252 * one attribute, STUN_MAPPED_ADDRESS, that we find in the response.
253 * By doing more transactions with different server addresses we
254 * may determine more about the behaviour of the NAT boxes, of
255 * course - the details are in the RFC.
257 * All STUN packets start with a simple header made of a type,
258 * length (excluding the header) and a 16-byte random transaction id.
259 * Following the header we may have zero or more attributes, each
260 * structured as a type, length and a value (whose format depends
261 * on the type, but often contains addresses).
262 * Of course all fields are in network format.
265 typedef struct { unsigned int id
[4]; } __attribute__((packed
)) stun_trans_id
;
268 unsigned short msgtype
;
269 unsigned short msglen
;
271 unsigned char ies
[0];
272 } __attribute__((packed
));
277 unsigned char value
[0];
278 } __attribute__((packed
));
281 * The format normally used for addresses carried by STUN messages.
284 unsigned char unused
;
285 unsigned char family
;
288 } __attribute__((packed
));
290 #define STUN_IGNORE (0)
291 #define STUN_ACCEPT (1)
293 /*! \brief STUN message types
294 * 'BIND' refers to transactions used to determine the externally
295 * visible addresses. 'SEC' refers to transactions used to establish
296 * a session key for subsequent requests.
297 * 'SEC' functionality is not supported here.
300 #define STUN_BINDREQ 0x0001
301 #define STUN_BINDRESP 0x0101
302 #define STUN_BINDERR 0x0111
303 #define STUN_SECREQ 0x0002
304 #define STUN_SECRESP 0x0102
305 #define STUN_SECERR 0x0112
307 /*! \brief Basic attribute types in stun messages.
308 * Messages can also contain custom attributes (codes above 0x7fff)
310 #define STUN_MAPPED_ADDRESS 0x0001
311 #define STUN_RESPONSE_ADDRESS 0x0002
312 #define STUN_CHANGE_REQUEST 0x0003
313 #define STUN_SOURCE_ADDRESS 0x0004
314 #define STUN_CHANGED_ADDRESS 0x0005
315 #define STUN_USERNAME 0x0006
316 #define STUN_PASSWORD 0x0007
317 #define STUN_MESSAGE_INTEGRITY 0x0008
318 #define STUN_ERROR_CODE 0x0009
319 #define STUN_UNKNOWN_ATTRIBUTES 0x000a
320 #define STUN_REFLECTED_FROM 0x000b
322 /*! \brief helper function to print message names */
323 static const char *stun_msg2str(int msg
)
327 return "Binding Request";
329 return "Binding Response";
331 return "Binding Error Response";
333 return "Shared Secret Request";
335 return "Shared Secret Response";
337 return "Shared Secret Error Response";
339 return "Non-RFC3489 Message";
342 /*! \brief helper function to print attribute names */
343 static const char *stun_attr2str(int msg
)
346 case STUN_MAPPED_ADDRESS
:
347 return "Mapped Address";
348 case STUN_RESPONSE_ADDRESS
:
349 return "Response Address";
350 case STUN_CHANGE_REQUEST
:
351 return "Change Request";
352 case STUN_SOURCE_ADDRESS
:
353 return "Source Address";
354 case STUN_CHANGED_ADDRESS
:
355 return "Changed Address";
360 case STUN_MESSAGE_INTEGRITY
:
361 return "Message Integrity";
362 case STUN_ERROR_CODE
:
364 case STUN_UNKNOWN_ATTRIBUTES
:
365 return "Unknown Attributes";
366 case STUN_REFLECTED_FROM
:
367 return "Reflected From";
369 return "Non-RFC3489 Attribute";
372 /*! \brief here we store credentials extracted from a message */
374 const char *username
;
375 const char *password
;
378 static int stun_process_attr(struct stun_state
*state
, struct stun_attr
*attr
)
381 ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
382 stun_attr2str(ntohs(attr
->attr
)), ntohs(attr
->attr
), ntohs(attr
->len
));
383 switch (ntohs(attr
->attr
)) {
385 state
->username
= (const char *) (attr
->value
);
388 state
->password
= (const char *) (attr
->value
);
392 ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
393 stun_attr2str(ntohs(attr
->attr
)), ntohs(attr
->attr
), ntohs(attr
->len
));
398 /*! \brief append a string to an STUN message */
399 static void append_attr_string(struct stun_attr
**attr
, int attrval
, const char *s
, int *len
, int *left
)
401 int size
= sizeof(**attr
) + strlen(s
);
403 (*attr
)->attr
= htons(attrval
);
404 (*attr
)->len
= htons(strlen(s
));
405 memcpy((*attr
)->value
, s
, strlen(s
));
406 (*attr
) = (struct stun_attr
*)((*attr
)->value
+ strlen(s
));
412 /*! \brief append an address to an STUN message */
413 static void append_attr_address(struct stun_attr
**attr
, int attrval
, struct sockaddr_in
*sin
, int *len
, int *left
)
415 int size
= sizeof(**attr
) + 8;
416 struct stun_addr
*addr
;
418 (*attr
)->attr
= htons(attrval
);
419 (*attr
)->len
= htons(8);
420 addr
= (struct stun_addr
*)((*attr
)->value
);
423 addr
->port
= sin
->sin_port
;
424 addr
->addr
= sin
->sin_addr
.s_addr
;
425 (*attr
) = (struct stun_attr
*)((*attr
)->value
+ 8);
431 /*! \brief wrapper to send an STUN message */
432 static int stun_send(int s
, struct sockaddr_in
*dst
, struct stun_header
*resp
)
434 return sendto(s
, resp
, ntohs(resp
->msglen
) + sizeof(*resp
), 0,
435 (struct sockaddr
*)dst
, sizeof(*dst
));
438 /*! \brief helper function to generate a random request id */
439 static void stun_req_id(struct stun_header
*req
)
442 for (x
= 0; x
< 4; x
++)
443 req
->id
.id
[x
] = ast_random();
446 size_t ast_rtp_alloc_size(void)
448 return sizeof(struct ast_rtp
);
451 /*! \brief callback type to be invoked on stun responses. */
452 typedef int (stun_cb_f
)(struct stun_attr
*attr
, void *arg
);
454 /*! \brief handle an incoming STUN message.
456 * Do some basic sanity checks on packet size and content,
457 * try to extract a bit of information, and possibly reply.
458 * At the moment this only processes BIND requests, and returns
459 * the externally visible address of the request.
460 * If a callback is specified, invoke it with the attribute.
462 static int stun_handle_packet(int s
, struct sockaddr_in
*src
,
463 unsigned char *data
, size_t len
, stun_cb_f
*stun_cb
, void *arg
)
465 struct stun_header
*hdr
= (struct stun_header
*)data
;
466 struct stun_attr
*attr
;
467 struct stun_state st
;
468 int ret
= STUN_IGNORE
;
471 /* On entry, 'len' is the length of the udp payload. After the
472 * initial checks it becomes the size of unprocessed options,
473 * while 'data' is advanced accordingly.
475 if (len
< sizeof(struct stun_header
)) {
476 ast_debug(1, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len
, (int) sizeof(struct stun_header
));
479 len
-= sizeof(struct stun_header
);
480 data
+= sizeof(struct stun_header
);
481 x
= ntohs(hdr
->msglen
); /* len as advertised in the message */
483 ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr
->msgtype
)), ntohs(hdr
->msgtype
), x
);
485 ast_debug(1, "Scrambled STUN packet length (got %d, expecting %d)\n", x
, (int)len
);
488 memset(&st
, 0, sizeof(st
));
490 if (len
< sizeof(struct stun_attr
)) {
491 ast_debug(1, "Runt Attribute (got %d, expecting %d)\n", (int)len
, (int) sizeof(struct stun_attr
));
494 attr
= (struct stun_attr
*)data
;
495 /* compute total attribute length */
496 x
= ntohs(attr
->len
) + sizeof(struct stun_attr
);
498 ast_debug(1, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x
, (int)len
);
503 if (stun_process_attr(&st
, attr
)) {
504 ast_debug(1, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr
->attr
)), ntohs(attr
->attr
));
507 /* Clear attribute id: in case previous entry was a string,
508 * this will act as the terminator for the string.
514 /* Null terminate any string.
515 * XXX NOTE, we write past the size of the buffer passed by the
516 * caller, so this is potentially dangerous. The only thing that
517 * saves us is that usually we read the incoming message in a
518 * much larger buffer in the struct ast_rtp
522 /* Now prepare to generate a reply, which at the moment is done
523 * only for properly formed (len == 0) STUN_BINDREQ messages.
526 unsigned char respdata
[1024];
527 struct stun_header
*resp
= (struct stun_header
*)respdata
;
528 int resplen
= 0; /* len excluding header */
529 int respleft
= sizeof(respdata
) - sizeof(struct stun_header
);
534 attr
= (struct stun_attr
*)resp
->ies
;
535 switch (ntohs(hdr
->msgtype
)) {
538 ast_verbose("STUN Bind Request, username: %s\n",
539 st
.username
? st
.username
: "<none>");
541 append_attr_string(&attr
, STUN_USERNAME
, st
.username
, &resplen
, &respleft
);
542 append_attr_address(&attr
, STUN_MAPPED_ADDRESS
, src
, &resplen
, &respleft
);
543 resp
->msglen
= htons(resplen
);
544 resp
->msgtype
= htons(STUN_BINDRESP
);
545 stun_send(s
, src
, resp
);
550 ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr
->msgtype
), stun_msg2str(ntohs(hdr
->msgtype
)));
556 /*! \brief Extract the STUN_MAPPED_ADDRESS from the stun response.
557 * This is used as a callback for stun_handle_response
558 * when called from ast_stun_request.
560 static int stun_get_mapped(struct stun_attr
*attr
, void *arg
)
562 struct stun_addr
*addr
= (struct stun_addr
*)(attr
+ 1);
563 struct sockaddr_in
*sa
= (struct sockaddr_in
*)arg
;
565 if (ntohs(attr
->attr
) != STUN_MAPPED_ADDRESS
|| ntohs(attr
->len
) != 8)
566 return 1; /* not us. */
567 sa
->sin_port
= addr
->port
;
568 sa
->sin_addr
.s_addr
= addr
->addr
;
572 /*! \brief Generic STUN request
573 * Send a generic stun request to the server specified,
574 * possibly waiting for a reply and filling the 'reply' field with
575 * the externally visible address. Note that in this case the request
577 * (Note, the interface may change slightly in the future).
579 * \param s the socket used to send the request
580 * \param dst the address of the STUN server
581 * \param username if non null, add the username in the request
582 * \param answer if non null, the function waits for a response and
583 * puts here the externally visible address.
584 * \return 0 on success, other values on error.
586 int ast_stun_request(int s
, struct sockaddr_in
*dst
,
587 const char *username
, struct sockaddr_in
*answer
)
589 struct stun_header
*req
;
590 unsigned char reqdata
[1024];
592 struct stun_attr
*attr
;
596 req
= (struct stun_header
*)reqdata
;
599 reqleft
= sizeof(reqdata
) - sizeof(struct stun_header
);
602 attr
= (struct stun_attr
*)req
->ies
;
604 append_attr_string(&attr
, STUN_USERNAME
, username
, &reqlen
, &reqleft
);
605 req
->msglen
= htons(reqlen
);
606 req
->msgtype
= htons(STUN_BINDREQ
);
607 for (retry
= 0; retry
< 3; retry
++) { /* XXX make retries configurable */
608 /* send request, possibly wait for reply */
609 unsigned char reply_buf
[1024];
611 struct timeval to
= { 3, 0 }; /* timeout, make it configurable */
612 struct sockaddr_in src
;
615 res
= stun_send(s
, dst
, req
);
617 ast_log(LOG_WARNING
, "ast_stun_request send #%d failed error %d, retry\n",
625 res
= ast_select(s
+ 1, &rfds
, NULL
, NULL
, &to
);
626 if (res
<= 0) /* timeout or error */
628 bzero(&src
, sizeof(src
));
629 srclen
= sizeof(src
);
630 /* XXX pass -1 in the size, because stun_handle_packet might
631 * write past the end of the buffer.
633 res
= recvfrom(s
, reply_buf
, sizeof(reply_buf
) - 1,
634 0, (struct sockaddr
*)&src
, &srclen
);
636 ast_log(LOG_WARNING
, "ast_stun_request recvfrom #%d failed error %d, retry\n",
640 bzero(answer
, sizeof(struct sockaddr_in
));
641 stun_handle_packet(s
, &src
, reply_buf
, res
,
642 stun_get_mapped
, answer
);
643 res
= 0; /* signal regular exit */
649 /*! \brief send a STUN BIND request to the given destination.
650 * Optionally, add a username if specified.
652 void ast_rtp_stun_request(struct ast_rtp
*rtp
, struct sockaddr_in
*suggestion
, const char *username
)
654 ast_stun_request(rtp
->s
, suggestion
, username
, NULL
);
657 /*! \brief List of current sessions */
658 static AST_RWLIST_HEAD_STATIC(protos
, ast_rtp_protocol
);
660 static void timeval2ntp(struct timeval tv
, unsigned int *msw
, unsigned int *lsw
)
662 unsigned int sec
, usec
, frac
;
663 sec
= tv
.tv_sec
+ 2208988800u; /* Sec between 1900 and 1970 */
665 frac
= (usec
<< 12) + (usec
<< 8) - ((usec
* 3650) >> 6);
670 int ast_rtp_fd(struct ast_rtp
*rtp
)
675 int ast_rtcp_fd(struct ast_rtp
*rtp
)
682 unsigned int ast_rtcp_calc_interval(struct ast_rtp
*rtp
)
684 unsigned int interval
;
685 /*! \todo XXX Do a more reasonable calculation on this one
686 * Look in RFC 3550 Section A.7 for an example*/
687 interval
= rtcpinterval
;
691 /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
692 void ast_rtp_set_rtptimers_onhold(struct ast_rtp
*rtp
)
694 rtp
->rtptimeout
= (-1) * rtp
->rtptimeout
;
695 rtp
->rtpholdtimeout
= (-1) * rtp
->rtpholdtimeout
;
698 /*! \brief Set rtp timeout */
699 void ast_rtp_set_rtptimeout(struct ast_rtp
*rtp
, int timeout
)
701 rtp
->rtptimeout
= timeout
;
704 /*! \brief Set rtp hold timeout */
705 void ast_rtp_set_rtpholdtimeout(struct ast_rtp
*rtp
, int timeout
)
707 rtp
->rtpholdtimeout
= timeout
;
710 /*! \brief set RTP keepalive interval */
711 void ast_rtp_set_rtpkeepalive(struct ast_rtp
*rtp
, int period
)
713 rtp
->rtpkeepalive
= period
;
716 /*! \brief Get rtp timeout */
717 int ast_rtp_get_rtptimeout(struct ast_rtp
*rtp
)
719 if (rtp
->rtptimeout
< 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
721 return rtp
->rtptimeout
;
724 /*! \brief Get rtp hold timeout */
725 int ast_rtp_get_rtpholdtimeout(struct ast_rtp
*rtp
)
727 if (rtp
->rtptimeout
< 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
729 return rtp
->rtpholdtimeout
;
732 /*! \brief Get RTP keepalive interval */
733 int ast_rtp_get_rtpkeepalive(struct ast_rtp
*rtp
)
735 return rtp
->rtpkeepalive
;
738 void ast_rtp_set_data(struct ast_rtp
*rtp
, void *data
)
743 void ast_rtp_set_callback(struct ast_rtp
*rtp
, ast_rtp_callback callback
)
745 rtp
->callback
= callback
;
748 void ast_rtp_setnat(struct ast_rtp
*rtp
, int nat
)
753 int ast_rtp_getnat(struct ast_rtp
*rtp
)
755 return ast_test_flag(rtp
, FLAG_NAT_ACTIVE
);
758 void ast_rtp_setdtmf(struct ast_rtp
*rtp
, int dtmf
)
760 ast_set2_flag(rtp
, dtmf
? 1 : 0, FLAG_HAS_DTMF
);
763 void ast_rtp_setdtmfcompensate(struct ast_rtp
*rtp
, int compensate
)
765 ast_set2_flag(rtp
, compensate
? 1 : 0, FLAG_DTMF_COMPENSATE
);
768 void ast_rtp_setstun(struct ast_rtp
*rtp
, int stun_enable
)
770 ast_set2_flag(rtp
, stun_enable
? 1 : 0, FLAG_HAS_STUN
);
773 static void rtp_bridge_lock(struct ast_rtp
*rtp
)
776 ast_mutex_lock(&rtp
->bridge_lock
);
781 static void rtp_bridge_unlock(struct ast_rtp
*rtp
)
784 ast_mutex_unlock(&rtp
->bridge_lock
);
789 static struct ast_frame
*send_dtmf(struct ast_rtp
*rtp
, enum ast_frame_type type
)
791 if (((ast_test_flag(rtp
, FLAG_DTMF_COMPENSATE
) && type
== AST_FRAME_DTMF_END
) ||
792 (type
== AST_FRAME_DTMF_BEGIN
)) && ast_tvcmp(ast_tvnow(), rtp
->dtmfmute
) < 0) {
793 ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp
->them
.sin_addr
));
795 rtp
->dtmfsamples
= 0;
796 return &ast_null_frame
;
798 ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp
->resp
, rtp
->resp
, ast_inet_ntoa(rtp
->them
.sin_addr
));
799 if (rtp
->resp
== 'X') {
800 rtp
->f
.frametype
= AST_FRAME_CONTROL
;
801 rtp
->f
.subclass
= AST_CONTROL_FLASH
;
803 rtp
->f
.frametype
= type
;
804 rtp
->f
.subclass
= rtp
->resp
;
814 static inline int rtp_debug_test_addr(struct sockaddr_in
*addr
)
818 if (rtpdebugaddr
.sin_addr
.s_addr
) {
819 if (((ntohs(rtpdebugaddr
.sin_port
) != 0)
820 && (rtpdebugaddr
.sin_port
!= addr
->sin_port
))
821 || (rtpdebugaddr
.sin_addr
.s_addr
!= addr
->sin_addr
.s_addr
))
827 static inline int rtcp_debug_test_addr(struct sockaddr_in
*addr
)
831 if (rtcpdebugaddr
.sin_addr
.s_addr
) {
832 if (((ntohs(rtcpdebugaddr
.sin_port
) != 0)
833 && (rtcpdebugaddr
.sin_port
!= addr
->sin_port
))
834 || (rtcpdebugaddr
.sin_addr
.s_addr
!= addr
->sin_addr
.s_addr
))
841 static struct ast_frame
*process_cisco_dtmf(struct ast_rtp
*rtp
, unsigned char *data
, int len
)
845 struct ast_frame
*f
= NULL
;
850 /* We should have at least 4 bytes in RTP data */
854 /* The format of Cisco RTP DTMF packet looks like next:
855 +0 - sequence number of DTMF RTP packet (begins from 1,
858 +1 (bit 0) - flaps by different DTMF digits delimited by audio
859 or repeated digit without audio???
860 +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
861 then falls to 0 at its end)
862 +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
863 Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
864 by each new packet and thus provides some redudancy.
866 Sample of Cisco RTP DTMF packet is (all data in hex):
867 19 07 00 02 12 02 20 02
868 showing end of DTMF digit '2'.
871 27 07 00 02 0A 02 20 02
872 28 06 20 02 00 02 0A 02
873 shows begin of new digit '2' with very short pause (20 ms) after
874 previous digit '2'. Bit +1.0 flips at begin of new digit.
876 Cisco RTP DTMF packets comes as replacement of audio RTP packets
877 so its uses the same sequencing and timestamping rules as replaced
878 audio packets. Repeat interval of DTMF packets is 20 ms and not rely
879 on audio framing parameters. Marker bit isn't used within stream of
880 DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
881 are not sequential at borders between DTMF and audio streams,
887 event
= data
[3] & 0x1f;
889 if (option_debug
> 2 || rtpdebug
)
890 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);
893 } else if (event
< 11) {
895 } else if (event
< 12) {
897 } else if (event
< 16) {
898 resp
= 'A' + (event
- 12);
899 } else if (event
< 17) {
902 if ((!rtp
->resp
&& power
) || (rtp
->resp
&& (rtp
->resp
!= resp
))) {
904 /* Why we should care on DTMF compensation at reception? */
905 if (!ast_test_flag(rtp
, FLAG_DTMF_COMPENSATE
)) {
906 f
= send_dtmf(rtp
, AST_FRAME_DTMF_BEGIN
);
907 rtp
->dtmfsamples
= 0;
909 } else if ((rtp
->resp
== resp
) && !power
) {
910 f
= send_dtmf(rtp
, AST_FRAME_DTMF_END
);
911 f
->samples
= rtp
->dtmfsamples
* 8;
913 } else if (rtp
->resp
== resp
)
914 rtp
->dtmfsamples
+= 20 * 8;
915 rtp
->dtmfcount
= dtmftimeout
;
920 * \brief Process RTP DTMF and events according to RFC 2833.
922 * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
931 static struct ast_frame
*process_rfc2833(struct ast_rtp
*rtp
, unsigned char *data
, int len
, unsigned int seqno
, unsigned int timestamp
)
934 unsigned int event_end
;
935 unsigned int samples
;
937 struct ast_frame
*f
= NULL
;
939 /* Figure out event, event end, and samples */
940 event
= ntohl(*((unsigned int *)(data
)));
942 event_end
= ntohl(*((unsigned int *)(data
)));
945 samples
= ntohl(*((unsigned int *)(data
)));
948 /* Print out debug if turned on */
949 if (rtpdebug
|| option_debug
> 2)
950 ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event
, len
);
952 /* Figure out what digit was pressed */
955 } else if (event
< 11) {
957 } else if (event
< 12) {
959 } else if (event
< 16) {
960 resp
= 'A' + (event
- 12);
961 } else if (event
< 17) { /* Event 16: Hook flash */
964 /* Not a supported event */
965 ast_log(LOG_DEBUG
, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event
);
966 return &ast_null_frame
;
969 if (ast_test_flag(rtp
, FLAG_DTMF_COMPENSATE
)) {
970 if ((rtp
->lastevent
!= timestamp
) || (rtp
->resp
&& rtp
->resp
!= resp
)) {
972 f
= send_dtmf(rtp
, AST_FRAME_DTMF_END
);
974 rtp
->lastevent
= timestamp
;
977 if ((!(rtp
->resp
) && (!(event_end
& 0x80))) || (rtp
->resp
&& rtp
->resp
!= resp
)) {
979 f
= send_dtmf(rtp
, AST_FRAME_DTMF_BEGIN
);
980 } else if ((event_end
& 0x80) && (rtp
->lastevent
!= seqno
) && rtp
->resp
) {
981 f
= send_dtmf(rtp
, AST_FRAME_DTMF_END
);
982 f
->len
= ast_tvdiff_ms(ast_samp2tv(samples
, 8000), ast_tv(0, 0)); /* XXX hard coded 8kHz */
984 rtp
->lastevent
= seqno
;
988 rtp
->dtmfcount
= dtmftimeout
;
989 rtp
->dtmfsamples
= samples
;
995 * \brief Process Comfort Noise RTP.
997 * This is incomplete at the moment.
1000 static struct ast_frame
*process_rfc3389(struct ast_rtp
*rtp
, unsigned char *data
, int len
)
1002 struct ast_frame
*f
= NULL
;
1003 /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
1004 totally help us out becuase we don't have an engine to keep it going and we are not
1005 guaranteed to have it every 20ms or anything */
1007 ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp
->lastrxformat
, len
);
1009 if (!(ast_test_flag(rtp
, FLAG_3389_WARNING
))) {
1010 ast_log(LOG_NOTICE
, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
1011 ast_inet_ntoa(rtp
->them
.sin_addr
));
1012 ast_set_flag(rtp
, FLAG_3389_WARNING
);
1015 /* Must have at least one byte */
1019 rtp
->f
.data
= rtp
->rawdata
+ AST_FRIENDLY_OFFSET
;
1020 rtp
->f
.datalen
= len
- 1;
1021 rtp
->f
.offset
= AST_FRIENDLY_OFFSET
;
1022 memcpy(rtp
->f
.data
, data
+ 1, len
- 1);
1028 rtp
->f
.frametype
= AST_FRAME_CNG
;
1029 rtp
->f
.subclass
= data
[0] & 0x7f;
1030 rtp
->f
.datalen
= len
- 1;
1032 rtp
->f
.delivery
.tv_usec
= rtp
->f
.delivery
.tv_sec
= 0;
1037 static int rtpread(int *id
, int fd
, short events
, void *cbdata
)
1039 struct ast_rtp
*rtp
= cbdata
;
1040 struct ast_frame
*f
;
1041 f
= ast_rtp_read(rtp
);
1044 rtp
->callback(rtp
, f
, rtp
->data
);
1049 struct ast_frame
*ast_rtcp_read(struct ast_rtp
*rtp
)
1052 int position
, i
, packetwords
;
1054 struct sockaddr_in sin
;
1055 unsigned int rtcpdata
[8192 + AST_FRIENDLY_OFFSET
];
1056 unsigned int *rtcpheader
;
1059 unsigned int length
;
1068 struct ast_frame
*f
= &ast_null_frame
;
1070 if (!rtp
|| !rtp
->rtcp
)
1071 return &ast_null_frame
;
1075 res
= recvfrom(rtp
->rtcp
->s
, rtcpdata
+ AST_FRIENDLY_OFFSET
, sizeof(rtcpdata
) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET
,
1076 0, (struct sockaddr
*)&sin
, &len
);
1077 rtcpheader
= (unsigned int *)(rtcpdata
+ AST_FRIENDLY_OFFSET
);
1082 if (errno
!= EAGAIN
) {
1083 ast_log(LOG_WARNING
, "RTCP Read error: %s. Hanging up.\n", strerror(errno
));
1086 return &ast_null_frame
;
1089 packetwords
= res
/ 4;
1092 /* Send to whoever sent to us */
1093 if ((rtp
->rtcp
->them
.sin_addr
.s_addr
!= sin
.sin_addr
.s_addr
) ||
1094 (rtp
->rtcp
->them
.sin_port
!= sin
.sin_port
)) {
1095 memcpy(&rtp
->rtcp
->them
, &sin
, sizeof(rtp
->rtcp
->them
));
1096 if (option_debug
|| rtpdebug
)
1097 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
));
1101 ast_debug(1, "Got RTCP report of %d bytes\n", res
);
1103 /* Process a compound packet */
1105 while (position
< packetwords
) {
1107 length
= ntohl(rtcpheader
[i
]);
1108 pt
= (length
& 0xff0000) >> 16;
1109 rc
= (length
& 0x1f000000) >> 24;
1112 if ((i
+ length
) > packetwords
) {
1113 if (option_debug
|| rtpdebug
)
1114 ast_log(LOG_DEBUG
, "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 coming in is not one of the negotiated ones then send it to the core, this will cause formats to change and the bridge to break */
1338 if (!bridged
->current_RTP_PT
[payload
].code
)
1341 /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
1342 if (ast_test_flag(rtp
, FLAG_P2P_NEED_DTMF
) && !rtpPT
.isAstFormat
&& rtpPT
.code
== AST_RTP_DTMF
)
1345 /* Otherwise adjust bridged payload to match */
1346 bridged_payload
= ast_rtp_lookup_code(bridged
, rtpPT
.isAstFormat
, rtpPT
.code
);
1348 /* If the mark bit has not been sent yet... do it now */
1349 if (!ast_test_flag(rtp
, FLAG_P2P_SENT_MARK
)) {
1351 ast_set_flag(rtp
, FLAG_P2P_SENT_MARK
);
1354 /* Reconstruct part of the packet */
1355 reconstruct
&= 0xFF80FFFF;
1356 reconstruct
|= (bridged_payload
<< 16);
1357 reconstruct
|= (mark
<< 23);
1358 rtpheader
[0] = htonl(reconstruct
);
1360 /* Send the packet back out */
1361 res
= sendto(bridged
->s
, (void *)rtpheader
, len
, 0, (struct sockaddr
*)&bridged
->them
, sizeof(bridged
->them
));
1363 if (!bridged
->nat
|| (bridged
->nat
&& (ast_test_flag(bridged
, FLAG_NAT_ACTIVE
) == FLAG_NAT_ACTIVE
))) {
1364 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
));
1365 } else if (((ast_test_flag(bridged
, FLAG_NAT_ACTIVE
) == FLAG_NAT_INACTIVE
) || rtpdebug
) && !ast_test_flag(bridged
, FLAG_NAT_INACTIVE_NOWARN
)) {
1366 if (option_debug
|| rtpdebug
)
1367 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
));
1368 ast_set_flag(bridged
, FLAG_NAT_INACTIVE_NOWARN
);
1371 } else if (rtp_debug_test_addr(&bridged
->them
))
1372 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
);
1377 struct ast_frame
*ast_rtp_read(struct ast_rtp
*rtp
)
1380 struct sockaddr_in sin
;
1391 unsigned int timestamp
;
1392 unsigned int *rtpheader
;
1393 struct rtpPayloadType rtpPT
;
1394 struct ast_rtp
*bridged
= NULL
;
1396 /* If time is up, kill it */
1397 if (rtp
->sending_digit
)
1398 ast_rtp_senddigit_continuation(rtp
);
1402 /* Cache where the header will go */
1403 res
= recvfrom(rtp
->s
, rtp
->rawdata
+ AST_FRIENDLY_OFFSET
, sizeof(rtp
->rawdata
) - AST_FRIENDLY_OFFSET
,
1404 0, (struct sockaddr
*)&sin
, &len
);
1406 /* If strict RTP protection is enabled see if we need to learn this address or if the packet should be dropped */
1407 if (rtp
->strict_rtp_state
== STRICT_RTP_LEARN
) {
1408 /* Copy over address that this packet was received on */
1409 memcpy(&rtp
->strict_rtp_address
, &sin
, sizeof(rtp
->strict_rtp_address
));
1410 /* Now move over to actually protecting the RTP port */
1411 rtp
->strict_rtp_state
= STRICT_RTP_CLOSED
;
1412 ast_debug(1, "Learned remote address is %s:%d for strict RTP purposes, now protecting the port.\n", ast_inet_ntoa(rtp
->strict_rtp_address
.sin_addr
), ntohs(rtp
->strict_rtp_address
.sin_port
));
1413 } else if (rtp
->strict_rtp_state
== STRICT_RTP_CLOSED
) {
1414 /* If the address we previously learned doesn't match the address this packet came in on simply drop it */
1415 if ((rtp
->strict_rtp_address
.sin_addr
.s_addr
!= sin
.sin_addr
.s_addr
) || (rtp
->strict_rtp_address
.sin_port
!= sin
.sin_port
)) {
1416 ast_debug(1, "Received RTP packet from %s:%d, dropping due to strict RTP protection. Expected it to be from %s:%d\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
), ast_inet_ntoa(rtp
->strict_rtp_address
.sin_addr
), ntohs(rtp
->strict_rtp_address
.sin_port
));
1417 return &ast_null_frame
;
1421 rtpheader
= (unsigned int *)(rtp
->rawdata
+ AST_FRIENDLY_OFFSET
);
1425 if (errno
!= EAGAIN
) {
1426 ast_log(LOG_WARNING
, "RTP Read error: %s. Hanging up.\n", strerror(errno
));
1429 return &ast_null_frame
;
1433 ast_log(LOG_WARNING
, "RTP Read too short\n");
1434 return &ast_null_frame
;
1438 seqno
= ntohl(rtpheader
[0]);
1440 /* Check RTP version */
1441 version
= (seqno
& 0xC0000000) >> 30;
1443 /* If the two high bits are 0, this might be a
1444 * STUN message, so process it. stun_handle_packet()
1445 * answers to requests, and it returns STUN_ACCEPT
1446 * if the request is valid.
1448 if ((stun_handle_packet(rtp
->s
, &sin
, rtp
->rawdata
+ AST_FRIENDLY_OFFSET
, res
, NULL
, NULL
) == STUN_ACCEPT
) &&
1449 (!rtp
->them
.sin_port
&& !rtp
->them
.sin_addr
.s_addr
)) {
1450 memcpy(&rtp
->them
, &sin
, sizeof(rtp
->them
));
1452 return &ast_null_frame
;
1455 #if 0 /* Allow to receive RTP stream with closed transmission path */
1456 /* If we don't have the other side's address, then ignore this */
1457 if (!rtp
->them
.sin_addr
.s_addr
|| !rtp
->them
.sin_port
)
1458 return &ast_null_frame
;
1461 /* Send to whoever send to us if NAT is turned on */
1463 if ((rtp
->them
.sin_addr
.s_addr
!= sin
.sin_addr
.s_addr
) ||
1464 (rtp
->them
.sin_port
!= sin
.sin_port
)) {
1467 memcpy(&rtp
->rtcp
->them
, &sin
, sizeof(rtp
->rtcp
->them
));
1468 rtp
->rtcp
->them
.sin_port
= htons(ntohs(rtp
->them
.sin_port
)+1);
1471 ast_set_flag(rtp
, FLAG_NAT_ACTIVE
);
1472 if (option_debug
|| rtpdebug
)
1473 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
));
1477 /* If we are bridged to another RTP stream, send direct */
1478 if ((bridged
= ast_rtp_get_bridged(rtp
)) && !bridge_p2p_rtp_write(rtp
, bridged
, rtpheader
, res
, hdrlen
))
1479 return &ast_null_frame
;
1482 return &ast_null_frame
;
1484 payloadtype
= (seqno
& 0x7f0000) >> 16;
1485 padding
= seqno
& (1 << 29);
1486 mark
= seqno
& (1 << 23);
1487 ext
= seqno
& (1 << 28);
1488 cc
= (seqno
& 0xF000000) >> 24;
1490 timestamp
= ntohl(rtpheader
[1]);
1491 ssrc
= ntohl(rtpheader
[2]);
1493 if (!mark
&& rtp
->rxssrc
&& rtp
->rxssrc
!= ssrc
) {
1494 if (option_debug
|| rtpdebug
)
1495 ast_debug(0, "Forcing Marker bit, because SSRC has changed\n");
1502 /* Remove padding bytes */
1503 res
-= rtp
->rawdata
[AST_FRIENDLY_OFFSET
+ res
- 1];
1507 /* CSRC fields present */
1512 /* RTP Extension present */
1513 hdrlen
+= (ntohl(rtpheader
[hdrlen
/4]) & 0xffff) << 2;
1517 profile
= (ntohl(rtpheader
[3]) & 0xffff0000) >> 16;
1518 if (profile
== 0x505a)
1519 ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
1521 ast_debug(1, "Found unknown RTP Extensions %x\n", profile
);
1526 ast_log(LOG_WARNING
, "RTP Read too short (%d, expecting %d)\n", res
, hdrlen
);
1527 return &ast_null_frame
;
1530 rtp
->rxcount
++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
1532 if (rtp
->rxcount
==1) {
1533 /* This is the first RTP packet successfully received from source */
1534 rtp
->seedrxseqno
= seqno
;
1537 /* Do not schedule RR if RTCP isn't run */
1538 if (rtp
->rtcp
&& rtp
->rtcp
->them
.sin_addr
.s_addr
&& rtp
->rtcp
->schedid
< 1) {
1539 /* Schedule transmission of Receiver Report */
1540 rtp
->rtcp
->schedid
= ast_sched_add(rtp
->sched
, ast_rtcp_calc_interval(rtp
), ast_rtcp_write
, rtp
);
1542 if ( (int)rtp
->lastrxseqno
- (int)seqno
> 100) /* if so it would indicate that the sender cycled; allow for misordering */
1543 rtp
->cycles
+= RTP_SEQ_MOD
;
1545 rtp
->lastrxseqno
= seqno
;
1548 rtp
->themssrc
= ntohl(rtpheader
[2]); /* Record their SSRC to put in future RR */
1550 if (rtp_debug_test_addr(&sin
))
1551 ast_verbose("Got RTP packet from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
1552 ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
), payloadtype
, seqno
, timestamp
,res
- hdrlen
);
1554 rtpPT
= ast_rtp_lookup_pt(rtp
, payloadtype
);
1555 if (!rtpPT
.isAstFormat
) {
1556 struct ast_frame
*f
= NULL
;
1558 /* This is special in-band data that's not one of our codecs */
1559 if (rtpPT
.code
== AST_RTP_DTMF
) {
1560 /* It's special -- rfc2833 process it */
1561 if (rtp_debug_test_addr(&sin
)) {
1562 unsigned char *data
;
1564 unsigned int event_end
;
1565 unsigned int duration
;
1566 data
= rtp
->rawdata
+ AST_FRIENDLY_OFFSET
+ hdrlen
;
1567 event
= ntohl(*((unsigned int *)(data
)));
1569 event_end
= ntohl(*((unsigned int *)(data
)));
1572 duration
= ntohl(*((unsigned int *)(data
)));
1574 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
);
1576 f
= process_rfc2833(rtp
, rtp
->rawdata
+ AST_FRIENDLY_OFFSET
+ hdrlen
, res
- hdrlen
, seqno
, timestamp
);
1577 } else if (rtpPT
.code
== AST_RTP_CISCO_DTMF
) {
1578 /* It's really special -- process it the Cisco way */
1579 if (rtp
->lastevent
<= seqno
|| (rtp
->lastevent
>= 65530 && seqno
<= 6)) {
1580 f
= process_cisco_dtmf(rtp
, rtp
->rawdata
+ AST_FRIENDLY_OFFSET
+ hdrlen
, res
- hdrlen
);
1581 rtp
->lastevent
= seqno
;
1583 } else if (rtpPT
.code
== AST_RTP_CN
) {
1585 f
= process_rfc3389(rtp
, rtp
->rawdata
+ AST_FRIENDLY_OFFSET
+ hdrlen
, res
- hdrlen
);
1587 ast_log(LOG_NOTICE
, "Unknown RTP codec %d received from '%s'\n", payloadtype
, ast_inet_ntoa(rtp
->them
.sin_addr
));
1589 return f
? f
: &ast_null_frame
;
1591 rtp
->lastrxformat
= rtp
->f
.subclass
= rtpPT
.code
;
1592 rtp
->f
.frametype
= (rtp
->f
.subclass
& AST_FORMAT_AUDIO_MASK
) ? AST_FRAME_VOICE
: (rtp
->f
.subclass
& AST_FORMAT_VIDEO_MASK
) ? AST_FRAME_VIDEO
: AST_FRAME_TEXT
;
1595 rtp
->lastrxts
= timestamp
;
1597 rtp
->rxseqno
= seqno
;
1599 /* Record received timestamp as last received now */
1600 rtp
->lastrxts
= timestamp
;
1603 rtp
->f
.datalen
= res
- hdrlen
;
1604 rtp
->f
.data
= rtp
->rawdata
+ hdrlen
+ AST_FRIENDLY_OFFSET
;
1605 rtp
->f
.offset
= hdrlen
+ AST_FRIENDLY_OFFSET
;
1606 rtp
->f
.seqno
= seqno
;
1607 if (rtp
->f
.subclass
& AST_FORMAT_AUDIO_MASK
) {
1608 rtp
->f
.samples
= ast_codec_get_samples(&rtp
->f
);
1609 if (rtp
->f
.subclass
== AST_FORMAT_SLINEAR
)
1610 ast_frame_byteswap_be(&rtp
->f
);
1611 calc_rxstamp(&rtp
->f
.delivery
, rtp
, timestamp
, mark
);
1612 /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
1613 ast_set_flag(&rtp
->f
, AST_FRFLAG_HAS_TIMING_INFO
);
1614 rtp
->f
.ts
= timestamp
/ 8;
1615 rtp
->f
.len
= rtp
->f
.samples
/ ( (ast_format_rate(rtp
->f
.subclass
) == 16000) ? 16 : 8 );
1616 } else if(rtp
->f
.subclass
& AST_FORMAT_VIDEO_MASK
) {
1617 /* Video -- samples is # of samples vs. 90000 */
1618 if (!rtp
->lastividtimestamp
)
1619 rtp
->lastividtimestamp
= timestamp
;
1620 rtp
->f
.samples
= timestamp
- rtp
->lastividtimestamp
;
1621 rtp
->lastividtimestamp
= timestamp
;
1622 rtp
->f
.delivery
.tv_sec
= 0;
1623 rtp
->f
.delivery
.tv_usec
= 0;
1624 /* Pass the RTP marker bit as bit 0 in the subclass field.
1625 * This is ok because subclass is actually a bitmask, and
1626 * the low bits represent audio formats, that are not
1627 * involved here since we deal with video.
1630 rtp
->f
.subclass
|= 0x1;
1632 /* TEXT -- samples is # of samples vs. 1000 */
1633 if (!rtp
->lastitexttimestamp
)
1634 rtp
->lastitexttimestamp
= timestamp
;
1635 rtp
->f
.samples
= timestamp
- rtp
->lastitexttimestamp
;
1636 rtp
->lastitexttimestamp
= timestamp
;
1637 rtp
->f
.delivery
.tv_sec
= 0;
1638 rtp
->f
.delivery
.tv_usec
= 0;
1644 /* The following array defines the MIME Media type (and subtype) for each
1645 of our codecs, or RTP-specific data type. */
1647 struct rtpPayloadType payloadType
;
1651 {{1, AST_FORMAT_G723_1
}, "audio", "G723"},
1652 {{1, AST_FORMAT_GSM
}, "audio", "GSM"},
1653 {{1, AST_FORMAT_ULAW
}, "audio", "PCMU"},
1654 {{1, AST_FORMAT_ULAW
}, "audio", "G711U"},
1655 {{1, AST_FORMAT_ALAW
}, "audio", "PCMA"},
1656 {{1, AST_FORMAT_ALAW
}, "audio", "G711A"},
1657 {{1, AST_FORMAT_G726
}, "audio", "G726-32"},
1658 {{1, AST_FORMAT_ADPCM
}, "audio", "DVI4"},
1659 {{1, AST_FORMAT_SLINEAR
}, "audio", "L16"},
1660 {{1, AST_FORMAT_LPC10
}, "audio", "LPC"},
1661 {{1, AST_FORMAT_G729A
}, "audio", "G729"},
1662 {{1, AST_FORMAT_G729A
}, "audio", "G729A"},
1663 {{1, AST_FORMAT_SPEEX
}, "audio", "speex"},
1664 {{1, AST_FORMAT_ILBC
}, "audio", "iLBC"},
1665 {{1, AST_FORMAT_G722
}, "audio", "G722"},
1666 {{1, AST_FORMAT_G726_AAL2
}, "audio", "AAL2-G726-32"},
1667 {{0, AST_RTP_DTMF
}, "audio", "telephone-event"},
1668 {{0, AST_RTP_CISCO_DTMF
}, "audio", "cisco-telephone-event"},
1669 {{0, AST_RTP_CN
}, "audio", "CN"},
1670 {{1, AST_FORMAT_JPEG
}, "video", "JPEG"},
1671 {{1, AST_FORMAT_PNG
}, "video", "PNG"},
1672 {{1, AST_FORMAT_H261
}, "video", "H261"},
1673 {{1, AST_FORMAT_H263
}, "video", "H263"},
1674 {{1, AST_FORMAT_H263_PLUS
}, "video", "h263-1998"},
1675 {{1, AST_FORMAT_H264
}, "video", "H264"},
1676 {{1, AST_FORMAT_MP4_VIDEO
}, "video", "MP4V-ES"},
1677 {{1, AST_FORMAT_T140
}, "text", "T140"},
1681 * \brief Mapping between Asterisk codecs and rtp payload types
1683 * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
1684 * also, our own choices for dynamic payload types. This is our master
1685 * table for transmission
1687 * See http://www.iana.org/assignments/rtp-parameters for a list of
1690 static struct rtpPayloadType static_RTP_PT
[MAX_RTP_PT
] = {
1691 [0] = {1, AST_FORMAT_ULAW
},
1692 #ifdef USE_DEPRECATED_G726
1693 [2] = {1, AST_FORMAT_G726
}, /* Technically this is G.721, but if Cisco can do it, so can we... */
1695 [3] = {1, AST_FORMAT_GSM
},
1696 [4] = {1, AST_FORMAT_G723_1
},
1697 [5] = {1, AST_FORMAT_ADPCM
}, /* 8 kHz */
1698 [6] = {1, AST_FORMAT_ADPCM
}, /* 16 kHz */
1699 [7] = {1, AST_FORMAT_LPC10
},
1700 [8] = {1, AST_FORMAT_ALAW
},
1701 [9] = {1, AST_FORMAT_G722
},
1702 [10] = {1, AST_FORMAT_SLINEAR
}, /* 2 channels */
1703 [11] = {1, AST_FORMAT_SLINEAR
}, /* 1 channel */
1704 [13] = {0, AST_RTP_CN
},
1705 [16] = {1, AST_FORMAT_ADPCM
}, /* 11.025 kHz */
1706 [17] = {1, AST_FORMAT_ADPCM
}, /* 22.050 kHz */
1707 [18] = {1, AST_FORMAT_G729A
},
1708 [19] = {0, AST_RTP_CN
}, /* Also used for CN */
1709 [26] = {1, AST_FORMAT_JPEG
},
1710 [31] = {1, AST_FORMAT_H261
},
1711 [34] = {1, AST_FORMAT_H263
},
1712 [97] = {1, AST_FORMAT_ILBC
},
1713 [98] = {1, AST_FORMAT_H263_PLUS
},
1714 [99] = {1, AST_FORMAT_H264
},
1715 [101] = {0, AST_RTP_DTMF
},
1716 [102] = {1, AST_FORMAT_T140
}, /* Real time text chat */
1717 [103] = {1, AST_FORMAT_H263_PLUS
},
1718 [104] = {1, AST_FORMAT_MP4_VIDEO
},
1719 [110] = {1, AST_FORMAT_SPEEX
},
1720 [111] = {1, AST_FORMAT_G726
},
1721 [112] = {1, AST_FORMAT_G726_AAL2
},
1722 [121] = {0, AST_RTP_CISCO_DTMF
}, /* Must be type 121 */
1725 void ast_rtp_pt_clear(struct ast_rtp
* rtp
)
1732 rtp_bridge_lock(rtp
);
1734 for (i
= 0; i
< MAX_RTP_PT
; ++i
) {
1735 rtp
->current_RTP_PT
[i
].isAstFormat
= 0;
1736 rtp
->current_RTP_PT
[i
].code
= 0;
1739 rtp
->rtp_lookup_code_cache_isAstFormat
= 0;
1740 rtp
->rtp_lookup_code_cache_code
= 0;
1741 rtp
->rtp_lookup_code_cache_result
= 0;
1743 rtp_bridge_unlock(rtp
);
1746 void ast_rtp_pt_default(struct ast_rtp
* rtp
)
1750 rtp_bridge_lock(rtp
);
1752 /* Initialize to default payload types */
1753 for (i
= 0; i
< MAX_RTP_PT
; ++i
) {
1754 rtp
->current_RTP_PT
[i
].isAstFormat
= static_RTP_PT
[i
].isAstFormat
;
1755 rtp
->current_RTP_PT
[i
].code
= static_RTP_PT
[i
].code
;
1758 rtp
->rtp_lookup_code_cache_isAstFormat
= 0;
1759 rtp
->rtp_lookup_code_cache_code
= 0;
1760 rtp
->rtp_lookup_code_cache_result
= 0;
1762 rtp_bridge_unlock(rtp
);
1765 void ast_rtp_pt_copy(struct ast_rtp
*dest
, struct ast_rtp
*src
)
1769 rtp_bridge_lock(dest
);
1770 rtp_bridge_lock(src
);
1772 for (i
= 0; i
< MAX_RTP_PT
; ++i
) {
1773 dest
->current_RTP_PT
[i
].isAstFormat
=
1774 src
->current_RTP_PT
[i
].isAstFormat
;
1775 dest
->current_RTP_PT
[i
].code
=
1776 src
->current_RTP_PT
[i
].code
;
1778 dest
->rtp_lookup_code_cache_isAstFormat
= 0;
1779 dest
->rtp_lookup_code_cache_code
= 0;
1780 dest
->rtp_lookup_code_cache_result
= 0;
1782 rtp_bridge_unlock(src
);
1783 rtp_bridge_unlock(dest
);
1786 /*! \brief Get channel driver interface structure */
1787 static struct ast_rtp_protocol
*get_proto(struct ast_channel
*chan
)
1789 struct ast_rtp_protocol
*cur
= NULL
;
1791 AST_RWLIST_RDLOCK(&protos
);
1792 AST_RWLIST_TRAVERSE(&protos
, cur
, list
) {
1793 if (cur
->type
== chan
->tech
->type
)
1796 AST_RWLIST_UNLOCK(&protos
);
1801 int ast_rtp_early_bridge(struct ast_channel
*c0
, struct ast_channel
*c1
)
1803 struct ast_rtp
*destp
= NULL
, *srcp
= NULL
; /* Audio RTP Channels */
1804 struct ast_rtp
*vdestp
= NULL
, *vsrcp
= NULL
; /* Video RTP channels */
1805 struct ast_rtp
*tdestp
= NULL
, *tsrcp
= NULL
; /* Text RTP channels */
1806 struct ast_rtp_protocol
*destpr
= NULL
, *srcpr
= NULL
;
1807 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
;
1808 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
;
1809 int srccodec
, destcodec
, nat_active
= 0;
1812 ast_channel_lock(c0
);
1814 while (ast_channel_trylock(c1
)) {
1815 ast_channel_unlock(c0
);
1817 ast_channel_lock(c0
);
1821 /* Find channel driver interfaces */
1822 destpr
= get_proto(c0
);
1824 srcpr
= get_proto(c1
);
1826 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c0
->name
);
1827 ast_channel_unlock(c0
);
1829 ast_channel_unlock(c1
);
1833 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c1
? c1
->name
: "<unspecified>");
1834 ast_channel_unlock(c0
);
1836 ast_channel_unlock(c1
);
1840 /* Get audio, video and text interface (if native bridge is possible) */
1841 audio_dest_res
= destpr
->get_rtp_info(c0
, &destp
);
1842 video_dest_res
= destpr
->get_vrtp_info
? destpr
->get_vrtp_info(c0
, &vdestp
) : AST_RTP_GET_FAILED
;
1843 text_dest_res
= destpr
->get_trtp_info
? destpr
->get_trtp_info(c0
, &tdestp
) : AST_RTP_GET_FAILED
;
1845 audio_src_res
= srcpr
->get_rtp_info(c1
, &srcp
);
1846 video_src_res
= srcpr
->get_vrtp_info
? srcpr
->get_vrtp_info(c1
, &vsrcp
) : AST_RTP_GET_FAILED
;
1847 text_src_res
= srcpr
->get_trtp_info
? srcpr
->get_trtp_info(c1
, &tsrcp
) : AST_RTP_GET_FAILED
;
1850 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1851 if (audio_dest_res
!= AST_RTP_TRY_NATIVE
) {
1852 /* Somebody doesn't want to play... */
1853 ast_channel_unlock(c0
);
1855 ast_channel_unlock(c1
);
1858 if (audio_src_res
== AST_RTP_TRY_NATIVE
&& srcpr
->get_codec
)
1859 srccodec
= srcpr
->get_codec(c1
);
1862 if (audio_dest_res
== AST_RTP_TRY_NATIVE
&& destpr
->get_codec
)
1863 destcodec
= destpr
->get_codec(c0
);
1866 /* Ensure we have at least one matching codec */
1867 if (!(srccodec
& destcodec
)) {
1868 ast_channel_unlock(c0
);
1870 ast_channel_unlock(c1
);
1873 /* Consider empty media as non-existent */
1874 if (audio_src_res
== AST_RTP_TRY_NATIVE
&& !srcp
->them
.sin_addr
.s_addr
)
1876 if (srcp
&& (srcp
->nat
|| ast_test_flag(srcp
, FLAG_NAT_ACTIVE
)))
1878 /* Bridge media early */
1879 if (destpr
->set_rtp_peer(c0
, srcp
, vsrcp
, tsrcp
, srccodec
, nat_active
))
1880 ast_log(LOG_WARNING
, "Channel '%s' failed to setup early bridge to '%s'\n", c0
->name
, c1
? c1
->name
: "<unspecified>");
1881 ast_channel_unlock(c0
);
1883 ast_channel_unlock(c1
);
1884 ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", c0
->name
, c1
? c1
->name
: "<unspecified>");
1888 int ast_rtp_make_compatible(struct ast_channel
*dest
, struct ast_channel
*src
, int media
)
1890 struct ast_rtp
*destp
= NULL
, *srcp
= NULL
; /* Audio RTP Channels */
1891 struct ast_rtp
*vdestp
= NULL
, *vsrcp
= NULL
; /* Video RTP channels */
1892 struct ast_rtp
*tdestp
= NULL
, *tsrcp
= NULL
; /* Text RTP channels */
1893 struct ast_rtp_protocol
*destpr
= NULL
, *srcpr
= NULL
;
1894 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
;
1895 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
;
1896 int srccodec
, destcodec
;
1899 ast_channel_lock(dest
);
1900 while (ast_channel_trylock(src
)) {
1901 ast_channel_unlock(dest
);
1903 ast_channel_lock(dest
);
1906 /* Find channel driver interfaces */
1907 if (!(destpr
= get_proto(dest
))) {
1908 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", dest
->name
);
1909 ast_channel_unlock(dest
);
1910 ast_channel_unlock(src
);
1913 if (!(srcpr
= get_proto(src
))) {
1914 ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", src
->name
);
1915 ast_channel_unlock(dest
);
1916 ast_channel_unlock(src
);
1920 /* Get audio and video interface (if native bridge is possible) */
1921 audio_dest_res
= destpr
->get_rtp_info(dest
, &destp
);
1922 video_dest_res
= destpr
->get_vrtp_info
? destpr
->get_vrtp_info(dest
, &vdestp
) : AST_RTP_GET_FAILED
;
1923 text_dest_res
= destpr
->get_trtp_info
? destpr
->get_trtp_info(dest
, &tdestp
) : AST_RTP_GET_FAILED
;
1924 audio_src_res
= srcpr
->get_rtp_info(src
, &srcp
);
1925 video_src_res
= srcpr
->get_vrtp_info
? srcpr
->get_vrtp_info(src
, &vsrcp
) : AST_RTP_GET_FAILED
;
1926 text_src_res
= srcpr
->get_trtp_info
? srcpr
->get_trtp_info(src
, &tsrcp
) : AST_RTP_GET_FAILED
;
1928 /* Ensure we have at least one matching codec */
1929 if (srcpr
->get_codec
)
1930 srccodec
= srcpr
->get_codec(src
);
1933 if (destpr
->get_codec
)
1934 destcodec
= destpr
->get_codec(dest
);
1938 /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
1939 if (audio_dest_res
!= AST_RTP_TRY_NATIVE
|| audio_src_res
!= AST_RTP_TRY_NATIVE
|| !(srccodec
& destcodec
)) {
1940 /* Somebody doesn't want to play... */
1941 ast_channel_unlock(dest
);
1942 ast_channel_unlock(src
);
1945 ast_rtp_pt_copy(destp
, srcp
);
1946 if (vdestp
&& vsrcp
)
1947 ast_rtp_pt_copy(vdestp
, vsrcp
);
1948 if (tdestp
&& tsrcp
)
1949 ast_rtp_pt_copy(tdestp
, tsrcp
);
1952 if (destpr
->set_rtp_peer(dest
, srcp
, vsrcp
, tsrcp
, srccodec
, ast_test_flag(srcp
, FLAG_NAT_ACTIVE
)))
1953 ast_log(LOG_WARNING
, "Channel '%s' failed to setup early bridge to '%s'\n", dest
->name
, src
->name
);
1955 ast_channel_unlock(dest
);
1956 ast_channel_unlock(src
);
1957 ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n", dest
->name
, src
->name
);
1961 /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
1962 * By default, use the well-known value for this type (although it may
1963 * still be set to a different value by a subsequent "a=rtpmap:" line)
1965 void ast_rtp_set_m_type(struct ast_rtp
* rtp
, int pt
)
1967 if (pt
< 0 || pt
> MAX_RTP_PT
|| static_RTP_PT
[pt
].code
== 0)
1968 return; /* bogus payload type */
1970 rtp_bridge_lock(rtp
);
1971 rtp
->current_RTP_PT
[pt
] = static_RTP_PT
[pt
];
1972 rtp_bridge_unlock(rtp
);
1975 /*! \brief remove setting from payload type list if the rtpmap header indicates
1976 an unknown media type */
1977 void ast_rtp_unset_m_type(struct ast_rtp
* rtp
, int pt
)
1979 if (pt
< 0 || pt
> MAX_RTP_PT
)
1980 return; /* bogus payload type */
1982 rtp_bridge_lock(rtp
);
1983 rtp
->current_RTP_PT
[pt
].isAstFormat
= 0;
1984 rtp
->current_RTP_PT
[pt
].code
= 0;
1985 rtp_bridge_unlock(rtp
);
1988 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
1989 * an SDP "a=rtpmap:" line.
1990 * \return 0 if the MIME type was found and set, -1 if it wasn't found
1992 int ast_rtp_set_rtpmap_type(struct ast_rtp
*rtp
, int pt
,
1993 char *mimeType
, char *mimeSubtype
,
1994 enum ast_rtp_options options
)
1999 if (pt
< 0 || pt
> MAX_RTP_PT
)
2000 return -1; /* bogus payload type */
2002 rtp_bridge_lock(rtp
);
2004 for (i
= 0; i
< sizeof(mimeTypes
)/sizeof(mimeTypes
[0]); ++i
) {
2005 if (strcasecmp(mimeSubtype
, mimeTypes
[i
].subtype
) == 0 &&
2006 strcasecmp(mimeType
, mimeTypes
[i
].type
) == 0) {
2008 rtp
->current_RTP_PT
[pt
] = mimeTypes
[i
].payloadType
;
2009 if ((mimeTypes
[i
].payloadType
.code
== AST_FORMAT_G726
) &&
2010 mimeTypes
[i
].payloadType
.isAstFormat
&&
2011 (options
& AST_RTP_OPT_G726_NONSTANDARD
))
2012 rtp
->current_RTP_PT
[pt
].code
= AST_FORMAT_G726_AAL2
;
2017 rtp_bridge_unlock(rtp
);
2019 return (found
? 0 : -1);
2022 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
2023 * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
2024 void ast_rtp_get_current_formats(struct ast_rtp
* rtp
,
2025 int* astFormats
, int* nonAstFormats
)
2029 rtp_bridge_lock(rtp
);
2031 *astFormats
= *nonAstFormats
= 0;
2032 for (pt
= 0; pt
< MAX_RTP_PT
; ++pt
) {
2033 if (rtp
->current_RTP_PT
[pt
].isAstFormat
) {
2034 *astFormats
|= rtp
->current_RTP_PT
[pt
].code
;
2036 *nonAstFormats
|= rtp
->current_RTP_PT
[pt
].code
;
2040 rtp_bridge_unlock(rtp
);
2043 struct rtpPayloadType
ast_rtp_lookup_pt(struct ast_rtp
* rtp
, int pt
)
2045 struct rtpPayloadType result
;
2047 result
.isAstFormat
= result
.code
= 0;
2049 if (pt
< 0 || pt
> MAX_RTP_PT
)
2050 return result
; /* bogus payload type */
2052 /* Start with negotiated codecs */
2053 rtp_bridge_lock(rtp
);
2054 result
= rtp
->current_RTP_PT
[pt
];
2055 rtp_bridge_unlock(rtp
);
2057 /* If it doesn't exist, check our static RTP type list, just in case */
2059 result
= static_RTP_PT
[pt
];
2064 /*! \brief Looks up an RTP code out of our *static* outbound list */
2065 int ast_rtp_lookup_code(struct ast_rtp
* rtp
, const int isAstFormat
, const int code
)
2069 rtp_bridge_lock(rtp
);
2071 if (isAstFormat
== rtp
->rtp_lookup_code_cache_isAstFormat
&&
2072 code
== rtp
->rtp_lookup_code_cache_code
) {
2073 /* Use our cached mapping, to avoid the overhead of the loop below */
2074 pt
= rtp
->rtp_lookup_code_cache_result
;
2075 rtp_bridge_unlock(rtp
);
2079 /* Check the dynamic list first */
2080 for (pt
= 0; pt
< MAX_RTP_PT
; ++pt
) {
2081 if (rtp
->current_RTP_PT
[pt
].code
== code
&& rtp
->current_RTP_PT
[pt
].isAstFormat
== isAstFormat
) {
2082 rtp
->rtp_lookup_code_cache_isAstFormat
= isAstFormat
;
2083 rtp
->rtp_lookup_code_cache_code
= code
;
2084 rtp
->rtp_lookup_code_cache_result
= pt
;
2085 rtp_bridge_unlock(rtp
);
2090 /* Then the static list */
2091 for (pt
= 0; pt
< MAX_RTP_PT
; ++pt
) {
2092 if (static_RTP_PT
[pt
].code
== code
&& static_RTP_PT
[pt
].isAstFormat
== isAstFormat
) {
2093 rtp
->rtp_lookup_code_cache_isAstFormat
= isAstFormat
;
2094 rtp
->rtp_lookup_code_cache_code
= code
;
2095 rtp
->rtp_lookup_code_cache_result
= pt
;
2096 rtp_bridge_unlock(rtp
);
2101 rtp_bridge_unlock(rtp
);
2106 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat
, const int code
,
2107 enum ast_rtp_options options
)
2111 for (i
= 0; i
< sizeof(mimeTypes
)/sizeof(mimeTypes
[0]); ++i
) {
2112 if ((mimeTypes
[i
].payloadType
.code
== code
) && (mimeTypes
[i
].payloadType
.isAstFormat
== isAstFormat
)) {
2114 (code
== AST_FORMAT_G726_AAL2
) &&
2115 (options
& AST_RTP_OPT_G726_NONSTANDARD
))
2118 return mimeTypes
[i
].subtype
;
2125 char *ast_rtp_lookup_mime_multiple(char *buf
, size_t size
, const int capability
,
2126 const int isAstFormat
, enum ast_rtp_options options
)
2136 snprintf(end
, size
, "0x%x (", capability
);
2143 for (format
= 1; format
< AST_RTP_MAX
; format
<<= 1) {
2144 if (capability
& format
) {
2145 const char *name
= ast_rtp_lookup_mime_subtype(isAstFormat
, format
, options
);
2147 snprintf(end
, size
, "%s|", name
);
2155 ast_copy_string(start
, "nothing)", size
);
2162 /*! \brief Open RTP or RTCP socket for a session.
2163 * Print a message on failure.
2165 static int rtp_socket(const char *type
)
2167 int s
= socket(AF_INET
, SOCK_DGRAM
, 0);
2171 ast_log(LOG_WARNING
, "Unable to allocate %s socket: %s\n", type
, strerror(errno
));
2173 long flags
= fcntl(s
, F_GETFL
);
2174 fcntl(s
, F_SETFL
, flags
| O_NONBLOCK
);
2177 setsockopt(s
, SOL_SOCKET
, SO_NO_CHECK
, &nochecksums
, sizeof(nochecksums
));
2184 * \brief Initialize a new RTCP session.
2186 * \returns The newly initialized RTCP session.
2188 static struct ast_rtcp
*ast_rtcp_new(void)
2190 struct ast_rtcp
*rtcp
;
2192 if (!(rtcp
= ast_calloc(1, sizeof(*rtcp
))))
2194 rtcp
->s
= rtp_socket("RTCP");
2195 rtcp
->us
.sin_family
= AF_INET
;
2196 rtcp
->them
.sin_family
= AF_INET
;
2208 * \brief Initialize a new RTP structure.
2211 void ast_rtp_new_init(struct ast_rtp
*rtp
)
2214 ast_mutex_init(&rtp
->bridge_lock
);
2217 rtp
->them
.sin_family
= AF_INET
;
2218 rtp
->us
.sin_family
= AF_INET
;
2219 rtp
->ssrc
= ast_random();
2220 rtp
->seqno
= ast_random() & 0xffff;
2221 ast_set_flag(rtp
, FLAG_HAS_DTMF
);
2222 rtp
->strict_rtp_state
= (strictrtp
? STRICT_RTP_LEARN
: STRICT_RTP_OPEN
);
2225 struct ast_rtp
*ast_rtp_new_with_bindaddr(struct sched_context
*sched
, struct io_context
*io
, int rtcpenable
, int callbackmode
, struct in_addr addr
)
2227 struct ast_rtp
*rtp
;
2231 if (!(rtp
= ast_calloc(1, sizeof(*rtp
))))
2234 ast_rtp_new_init(rtp
);
2236 rtp
->s
= rtp_socket("RTP");
2239 if (sched
&& rtcpenable
) {
2241 rtp
->rtcp
= ast_rtcp_new();
2245 * Try to bind the RTP port, x, and possibly the RTCP port, x+1 as well.
2246 * Start from a random (even, by RTP spec) port number, and
2247 * iterate until success or no ports are available.
2248 * Note that the requirement of RTP port being even, or RTCP being the
2249 * next one, cannot be enforced in presence of a NAT box because the
2250 * mapping is not under our control.
2252 x
= (ast_random() % (rtpend
-rtpstart
)) + rtpstart
;
2253 x
= x
& ~1; /* make it an even number */
2254 startplace
= x
; /* remember the starting point */
2255 /* this is constant across the loop */
2256 rtp
->us
.sin_addr
= addr
;
2258 rtp
->rtcp
->us
.sin_addr
= addr
;
2260 rtp
->us
.sin_port
= htons(x
);
2261 if (!bind(rtp
->s
, (struct sockaddr
*)&rtp
->us
, sizeof(rtp
->us
))) {
2262 /* bind succeeded, if no rtcp then we are done */
2265 /* have rtcp, try to bind it */
2266 rtp
->rtcp
->us
.sin_port
= htons(x
+ 1);
2267 if (!bind(rtp
->rtcp
->s
, (struct sockaddr
*)&rtp
->rtcp
->us
, sizeof(rtp
->rtcp
->us
)))
2268 break; /* success again, we are really done */
2270 * RTCP bind failed, so close and recreate the
2271 * already bound RTP socket for the next round.
2274 rtp
->s
= rtp_socket("RTP");
2279 * If we get here, there was an error in one of the bind()
2280 * calls, so make sure it is nothing unexpected.
2282 if (errno
!= EADDRINUSE
) {
2283 /* We got an error that wasn't expected, abort! */
2284 ast_log(LOG_ERROR
, "Unexpected bind error: %s\n", strerror(errno
));
2288 * One of the ports is in use. For the next iteration,
2289 * increment by two and handle wraparound.
2290 * If we reach the starting point, then declare failure.
2294 x
= (rtpstart
+ 1) & ~1;
2295 if (x
== startplace
) {
2296 ast_log(LOG_ERROR
, "No RTP ports remaining. Can't setup media stream for this call.\n");
2303 rtp
->ioid
= ast_io_add(rtp
->io
, rtp
->s
, rtpread
, AST_IO_IN
, rtp
);
2304 ast_set_flag(rtp
, FLAG_CALLBACK_MODE
);
2306 ast_rtp_pt_default(rtp
);
2313 close(rtp
->rtcp
->s
);
2314 ast_free(rtp
->rtcp
);
2320 struct ast_rtp
*ast_rtp_new(struct sched_context
*sched
, struct io_context
*io
, int rtcpenable
, int callbackmode
)
2324 memset(&ia
, 0, sizeof(ia
));
2325 return ast_rtp_new_with_bindaddr(sched
, io
, rtcpenable
, callbackmode
, ia
);
2328 int ast_rtp_setqos(struct ast_rtp
*rtp
, int tos
, int cos
, char *desc
)
2330 return ast_netsock_set_qos(rtp
->s
, tos
, cos
, desc
);
2333 void ast_rtp_new_source(struct ast_rtp
*rtp
)
2335 rtp
->set_marker_bit
= 1;
2339 void ast_rtp_set_peer(struct ast_rtp
*rtp
, struct sockaddr_in
*them
)
2341 rtp
->them
.sin_port
= them
->sin_port
;
2342 rtp
->them
.sin_addr
= them
->sin_addr
;
2344 rtp
->rtcp
->them
.sin_port
= htons(ntohs(them
->sin_port
) + 1);
2345 rtp
->rtcp
->them
.sin_addr
= them
->sin_addr
;
2348 /* If strict RTP protection is enabled switch back to the learn state so we don't drop packets from above */
2350 rtp
->strict_rtp_state
= STRICT_RTP_LEARN
;
2353 int ast_rtp_get_peer(struct ast_rtp
*rtp
, struct sockaddr_in
*them
)
2355 if ((them
->sin_family
!= AF_INET
) ||
2356 (them
->sin_port
!= rtp
->them
.sin_port
) ||
2357 (them
->sin_addr
.s_addr
!= rtp
->them
.sin_addr
.s_addr
)) {
2358 them
->sin_family
= AF_INET
;
2359 them
->sin_port
= rtp
->them
.sin_port
;
2360 them
->sin_addr
= rtp
->them
.sin_addr
;
2366 void ast_rtp_get_us(struct ast_rtp
*rtp
, struct sockaddr_in
*us
)
2371 struct ast_rtp
*ast_rtp_get_bridged(struct ast_rtp
*rtp
)
2373 struct ast_rtp
*bridged
= NULL
;
2375 rtp_bridge_lock(rtp
);
2376 bridged
= rtp
->bridged
;
2377 rtp_bridge_unlock(rtp
);
2382 void ast_rtp_stop(struct ast_rtp
*rtp
)
2384 AST_SCHED_DEL(rtp
->sched
, rtp
->rtcp
->schedid
);
2386 memset(&rtp
->them
.sin_addr
, 0, sizeof(rtp
->them
.sin_addr
));
2387 memset(&rtp
->them
.sin_port
, 0, sizeof(rtp
->them
.sin_port
));
2389 memset(&rtp
->rtcp
->them
.sin_addr
, 0, sizeof(rtp
->rtcp
->them
.sin_addr
));
2390 memset(&rtp
->rtcp
->them
.sin_port
, 0, sizeof(rtp
->rtcp
->them
.sin_port
));
2393 ast_clear_flag(rtp
, FLAG_P2P_SENT_MARK
);
2396 void ast_rtp_reset(struct ast_rtp
*rtp
)
2398 memset(&rtp
->rxcore
, 0, sizeof(rtp
->rxcore
));
2399 memset(&rtp
->txcore
, 0, sizeof(rtp
->txcore
));
2400 memset(&rtp
->dtmfmute
, 0, sizeof(rtp
->dtmfmute
));
2402 rtp
->lastdigitts
= 0;
2404 rtp
->lastividtimestamp
= 0;
2405 rtp
->lastovidtimestamp
= 0;
2406 rtp
->lastitexttimestamp
= 0;
2407 rtp
->lastotexttimestamp
= 0;
2408 rtp
->lasteventseqn
= 0;
2410 rtp
->lasttxformat
= 0;
2411 rtp
->lastrxformat
= 0;
2413 rtp
->dtmfsamples
= 0;
2418 char *ast_rtp_get_quality(struct ast_rtp
*rtp
, struct ast_rtp_quality
*qual
)
2422 *themssrc their ssrc
2424 *rxjitter our calculated jitter(rx)
2425 *rxcount no. received packets
2426 *txjitter reported jitter of the other end
2427 *txcount transmitted packets
2428 *rlp remote lost packets
2429 *rtt round trip time
2433 qual
->local_ssrc
= rtp
->ssrc
;
2434 qual
->local_jitter
= rtp
->rxjitter
;
2435 qual
->local_count
= rtp
->rxcount
;
2436 qual
->remote_ssrc
= rtp
->themssrc
;
2437 qual
->remote_count
= rtp
->txcount
;
2439 qual
->local_lostpackets
= rtp
->rtcp
->expected_prior
- rtp
->rtcp
->received_prior
;
2440 qual
->remote_lostpackets
= rtp
->rtcp
->reported_lost
;
2441 qual
->remote_jitter
= rtp
->rtcp
->reported_jitter
/ 65536.0;
2442 qual
->rtt
= rtp
->rtcp
->rtt
;
2446 snprintf(rtp
->rtcp
->quality
, sizeof(rtp
->rtcp
->quality
),
2447 "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
2450 rtp
->rtcp
->expected_prior
- rtp
->rtcp
->received_prior
,
2453 (double)rtp
->rtcp
->reported_jitter
/ 65536.0,
2455 rtp
->rtcp
->reported_lost
,
2457 return rtp
->rtcp
->quality
;
2459 return "<Unknown> - RTP/RTCP has already been destroyed";
2462 void ast_rtp_destroy(struct ast_rtp
*rtp
)
2464 if (rtcp_debug_test_addr(&rtp
->them
) || rtcpstats
) {
2465 /*Print some info on the call here */
2466 ast_verbose(" RTP-stats\n");
2467 ast_verbose("* Our Receiver:\n");
2468 ast_verbose(" SSRC: %u\n", rtp
->themssrc
);
2469 ast_verbose(" Received packets: %u\n", rtp
->rxcount
);
2470 ast_verbose(" Lost packets: %u\n", rtp
->rtcp
->expected_prior
- rtp
->rtcp
->received_prior
);
2471 ast_verbose(" Jitter: %.4f\n", rtp
->rxjitter
);
2472 ast_verbose(" Transit: %.4f\n", rtp
->rxtransit
);
2473 ast_verbose(" RR-count: %u\n", rtp
->rtcp
->rr_count
);
2474 ast_verbose("* Our Sender:\n");
2475 ast_verbose(" SSRC: %u\n", rtp
->ssrc
);
2476 ast_verbose(" Sent packets: %u\n", rtp
->txcount
);
2477 ast_verbose(" Lost packets: %u\n", rtp
->rtcp
->reported_lost
);
2478 ast_verbose(" Jitter: %u\n", rtp
->rtcp
->reported_jitter
/ (unsigned int)65536.0);
2479 ast_verbose(" SR-count: %u\n", rtp
->rtcp
->sr_count
);
2480 ast_verbose(" RTT: %f\n", rtp
->rtcp
->rtt
);
2483 manager_event(EVENT_FLAG_REPORTING
, "RTPReceiverStat", "SSRC: %u\r\n"
2484 "ReceivedPackets: %u\r\n"
2485 "LostPackets: %u\r\n"
2491 rtp
->rtcp
->expected_prior
- rtp
->rtcp
->received_prior
,
2494 rtp
->rtcp
->rr_count
);
2495 manager_event(EVENT_FLAG_REPORTING
, "RTPSenderStat", "SSRC: %u\r\n"
2496 "SentPackets: %u\r\n"
2497 "LostPackets: %u\r\n"
2503 rtp
->rtcp
->reported_lost
,
2504 rtp
->rtcp
->reported_jitter
,
2505 rtp
->rtcp
->sr_count
,
2508 ast_smoother_free(rtp
->smoother
);
2510 ast_io_remove(rtp
->io
, rtp
->ioid
);
2514 AST_SCHED_DEL(rtp
->sched
, rtp
->rtcp
->schedid
);
2515 close(rtp
->rtcp
->s
);
2516 ast_free(rtp
->rtcp
);
2520 ast_mutex_destroy(&rtp
->bridge_lock
);
2525 static unsigned int calc_txstamp(struct ast_rtp
*rtp
, struct timeval
*delivery
)
2529 if (ast_tvzero(rtp
->txcore
)) {
2530 rtp
->txcore
= ast_tvnow();
2531 /* Round to 20ms for nice, pretty timestamps */
2532 rtp
->txcore
.tv_usec
-= rtp
->txcore
.tv_usec
% 20000;
2534 /* Use previous txcore if available */
2535 t
= (delivery
&& !ast_tvzero(*delivery
)) ? *delivery
: ast_tvnow();
2536 ms
= ast_tvdiff_ms(t
, rtp
->txcore
);
2539 /* Use what we just got for next time */
2541 return (unsigned int) ms
;
2544 /*! \brief Send begin frames for DTMF */
2545 int ast_rtp_senddigit_begin(struct ast_rtp
*rtp
, char digit
)
2547 unsigned int *rtpheader
;
2548 int hdrlen
= 12, res
= 0, i
= 0, payload
= 0;
2551 if ((digit
<= '9') && (digit
>= '0'))
2553 else if (digit
== '*')
2555 else if (digit
== '#')
2557 else if ((digit
>= 'A') && (digit
<= 'D'))
2558 digit
= digit
- 'A' + 12;
2559 else if ((digit
>= 'a') && (digit
<= 'd'))
2560 digit
= digit
- 'a' + 12;
2562 ast_log(LOG_WARNING
, "Don't know how to represent '%c'\n", digit
);
2566 /* If we have no peer, return immediately */
2567 if (!rtp
->them
.sin_addr
.s_addr
|| !rtp
->them
.sin_port
)
2570 payload
= ast_rtp_lookup_code(rtp
, 0, AST_RTP_DTMF
);
2572 rtp
->dtmfmute
= ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2573 rtp
->send_duration
= 160;
2575 /* Get a pointer to the header */
2576 rtpheader
= (unsigned int *)data
;
2577 rtpheader
[0] = htonl((2 << 30) | (1 << 23) | (payload
<< 16) | (rtp
->seqno
));
2578 rtpheader
[1] = htonl(rtp
->lastdigitts
);
2579 rtpheader
[2] = htonl(rtp
->ssrc
);
2581 for (i
= 0; i
< 2; i
++) {
2582 rtpheader
[3] = htonl((digit
<< 24) | (0xa << 16) | (rtp
->send_duration
));
2583 res
= sendto(rtp
->s
, (void *) rtpheader
, hdrlen
+ 4, 0, (struct sockaddr
*) &rtp
->them
, sizeof(rtp
->them
));
2585 ast_log(LOG_ERROR
, "RTP Transmission error to %s:%u: %s\n",
2586 ast_inet_ntoa(rtp
->them
.sin_addr
),
2587 ntohs(rtp
->them
.sin_port
), strerror(errno
));
2588 if (rtp_debug_test_addr(&rtp
->them
))
2589 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2590 ast_inet_ntoa(rtp
->them
.sin_addr
),
2591 ntohs(rtp
->them
.sin_port
), payload
, rtp
->seqno
, rtp
->lastdigitts
, res
- hdrlen
);
2592 /* Increment sequence number */
2594 /* Increment duration */
2595 rtp
->send_duration
+= 160;
2596 /* Clear marker bit and set seqno */
2597 rtpheader
[0] = htonl((2 << 30) | (payload
<< 16) | (rtp
->seqno
));
2600 /* Since we received a begin, we can safely store the digit and disable any compensation */
2601 rtp
->sending_digit
= 1;
2602 rtp
->send_digit
= digit
;
2603 rtp
->send_payload
= payload
;
2608 /*! \brief Send continuation frame for DTMF */
2609 static int ast_rtp_senddigit_continuation(struct ast_rtp
*rtp
)
2611 unsigned int *rtpheader
;
2612 int hdrlen
= 12, res
= 0;
2615 if (!rtp
->them
.sin_addr
.s_addr
|| !rtp
->them
.sin_port
)
2618 /* Setup packet to send */
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((rtp
->send_digit
<< 24) | (0xa << 16) | (rtp
->send_duration
));
2624 rtpheader
[0] = htonl((2 << 30) | (rtp
->send_payload
<< 16) | (rtp
->seqno
));
2627 res
= sendto(rtp
->s
, (void *) rtpheader
, hdrlen
+ 4, 0, (struct sockaddr
*) &rtp
->them
, sizeof(rtp
->them
));
2629 ast_log(LOG_ERROR
, "RTP Transmission error to %s:%d: %s\n",
2630 ast_inet_ntoa(rtp
->them
.sin_addr
),
2631 ntohs(rtp
->them
.sin_port
), strerror(errno
));
2632 if (rtp_debug_test_addr(&rtp
->them
))
2633 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2634 ast_inet_ntoa(rtp
->them
.sin_addr
),
2635 ntohs(rtp
->them
.sin_port
), rtp
->send_payload
, rtp
->seqno
, rtp
->lastdigitts
, res
- hdrlen
);
2637 /* Increment sequence number */
2639 /* Increment duration */
2640 rtp
->send_duration
+= 160;
2645 /*! \brief Send end packets for DTMF */
2646 int ast_rtp_senddigit_end(struct ast_rtp
*rtp
, char digit
)
2648 unsigned int *rtpheader
;
2649 int hdrlen
= 12, res
= 0, i
= 0;
2652 /* If no address, then bail out */
2653 if (!rtp
->them
.sin_addr
.s_addr
|| !rtp
->them
.sin_port
)
2656 if ((digit
<= '9') && (digit
>= '0'))
2658 else if (digit
== '*')
2660 else if (digit
== '#')
2662 else if ((digit
>= 'A') && (digit
<= 'D'))
2663 digit
= digit
- 'A' + 12;
2664 else if ((digit
>= 'a') && (digit
<= 'd'))
2665 digit
= digit
- 'a' + 12;
2667 ast_log(LOG_WARNING
, "Don't know how to represent '%c'\n", digit
);
2671 rtp
->dtmfmute
= ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2673 rtpheader
= (unsigned int *)data
;
2674 rtpheader
[0] = htonl((2 << 30) | (1 << 23) | (rtp
->send_payload
<< 16) | (rtp
->seqno
));
2675 rtpheader
[1] = htonl(rtp
->lastdigitts
);
2676 rtpheader
[2] = htonl(rtp
->ssrc
);
2677 rtpheader
[3] = htonl((digit
<< 24) | (0xa << 16) | (rtp
->send_duration
));
2679 rtpheader
[3] |= htonl((1 << 23));
2680 rtpheader
[0] = htonl((2 << 30) | (rtp
->send_payload
<< 16) | (rtp
->seqno
));
2681 /* Send 3 termination packets */
2682 for (i
= 0; i
< 3; i
++) {
2683 res
= sendto(rtp
->s
, (void *) rtpheader
, hdrlen
+ 4, 0, (struct sockaddr
*) &rtp
->them
, sizeof(rtp
->them
));
2685 ast_log(LOG_ERROR
, "RTP Transmission error to %s:%d: %s\n",
2686 ast_inet_ntoa(rtp
->them
.sin_addr
),
2687 ntohs(rtp
->them
.sin_port
), strerror(errno
));
2688 if (rtp_debug_test_addr(&rtp
->them
))
2689 ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
2690 ast_inet_ntoa(rtp
->them
.sin_addr
),
2691 ntohs(rtp
->them
.sin_port
), rtp
->send_payload
, rtp
->seqno
, rtp
->lastdigitts
, res
- hdrlen
);
2693 rtp
->sending_digit
= 0;
2694 rtp
->send_digit
= 0;
2695 /* Increment lastdigitts */
2696 rtp
->lastdigitts
+= 960;
2702 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
2703 int ast_rtcp_send_h261fur(void *data
)
2705 struct ast_rtp
*rtp
= data
;
2708 rtp
->rtcp
->sendfur
= 1;
2709 res
= ast_rtcp_write(data
);
2714 /*! \brief Send RTCP sender's report */
2715 static int ast_rtcp_write_sr(const void *data
)
2717 struct ast_rtp
*rtp
= (struct ast_rtp
*)data
;
2721 unsigned int now_lsw
;
2722 unsigned int now_msw
;
2723 unsigned int *rtcpheader
;
2725 unsigned int extended
;
2726 unsigned int expected
;
2727 unsigned int expected_interval
;
2728 unsigned int received_interval
;
2731 struct timeval dlsr
;
2734 /* Commented condition is always not NULL if rtp->rtcp is not NULL */
2735 if (!rtp
|| !rtp
->rtcp
/* || (&rtp->rtcp->them.sin_addr == 0)*/)
2738 if (!rtp
->rtcp
->them
.sin_addr
.s_addr
) { /* This'll stop rtcp for this rtp session */
2739 ast_verbose("RTCP SR transmission error, rtcp halted\n");
2740 AST_SCHED_DEL(rtp
->sched
, rtp
->rtcp
->schedid
);
2744 gettimeofday(&now
, NULL
);
2745 timeval2ntp(now
, &now_msw
, &now_lsw
); /* fill thses ones in from utils.c*/
2746 rtcpheader
= (unsigned int *)bdata
;
2747 rtcpheader
[1] = htonl(rtp
->ssrc
); /* Our SSRC */
2748 rtcpheader
[2] = htonl(now_msw
); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
2749 rtcpheader
[3] = htonl(now_lsw
); /* now, LSW */
2750 rtcpheader
[4] = htonl(rtp
->lastts
); /* FIXME shouldn't be that, it should be now */
2751 rtcpheader
[5] = htonl(rtp
->txcount
); /* No. packets sent */
2752 rtcpheader
[6] = htonl(rtp
->txoctetcount
); /* No. bytes sent */
2755 extended
= rtp
->cycles
+ rtp
->lastrxseqno
;
2756 expected
= extended
- rtp
->seedrxseqno
+ 1;
2757 if (rtp
->rxcount
> expected
)
2758 expected
+= rtp
->rxcount
- expected
;
2759 lost
= expected
- rtp
->rxcount
;
2760 expected_interval
= expected
- rtp
->rtcp
->expected_prior
;
2761 rtp
->rtcp
->expected_prior
= expected
;
2762 received_interval
= rtp
->rxcount
- rtp
->rtcp
->received_prior
;
2763 rtp
->rtcp
->received_prior
= rtp
->rxcount
;
2764 lost_interval
= expected_interval
- received_interval
;
2765 if (expected_interval
== 0 || lost_interval
<= 0)
2768 fraction
= (lost_interval
<< 8) / expected_interval
;
2769 timersub(&now
, &rtp
->rtcp
->rxlsr
, &dlsr
);
2770 rtcpheader
[7] = htonl(rtp
->themssrc
);
2771 rtcpheader
[8] = htonl(((fraction
& 0xff) << 24) | (lost
& 0xffffff));
2772 rtcpheader
[9] = htonl((rtp
->cycles
) | ((rtp
->lastrxseqno
& 0xffff)));
2773 rtcpheader
[10] = htonl((unsigned int)(rtp
->rxjitter
* 65536.));
2774 rtcpheader
[11] = htonl(rtp
->rtcp
->themrxlsr
);
2775 rtcpheader
[12] = htonl((((dlsr
.tv_sec
* 1000) + (dlsr
.tv_usec
/ 1000)) * 65536) / 1000);
2778 rtcpheader
[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR
<< 16) | ((len
/4)-1));
2780 if (rtp
->rtcp
->sendfur
) {
2781 rtcpheader
[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR
<< 16) | 1);
2782 rtcpheader
[14] = htonl(rtp
->ssrc
); /* Our SSRC */
2784 rtp
->rtcp
->sendfur
= 0;
2787 /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
2788 /* it can change mid call, and SDES can't) */
2789 rtcpheader
[len
/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES
<< 16) | 2);
2790 rtcpheader
[(len
/4)+1] = htonl(rtp
->ssrc
); /* Our SSRC */
2791 rtcpheader
[(len
/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2794 res
= sendto(rtp
->rtcp
->s
, (unsigned int *)rtcpheader
, len
, 0, (struct sockaddr
*)&rtp
->rtcp
->them
, sizeof(rtp
->rtcp
->them
));
2796 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
));
2797 AST_SCHED_DEL(rtp
->sched
, rtp
->rtcp
->schedid
);
2801 /* FIXME Don't need to get a new one */
2802 gettimeofday(&rtp
->rtcp
->txlsr
, NULL
);
2803 rtp
->rtcp
->sr_count
++;
2805 rtp
->rtcp
->lastsrtxcount
= rtp
->txcount
;
2807 if (rtcp_debug_test_addr(&rtp
->rtcp
->them
)) {
2808 ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp
->rtcp
->them
.sin_addr
), ntohs(rtp
->rtcp
->them
.sin_port
));
2809 ast_verbose(" Our SSRC: %u\n", rtp
->ssrc
);
2810 ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now
.tv_sec
, (unsigned int)now
.tv_usec
*4096);
2811 ast_verbose(" Sent(RTP): %u\n", rtp
->lastts
);
2812 ast_verbose(" Sent packets: %u\n", rtp
->txcount
);
2813 ast_verbose(" Sent octets: %u\n", rtp
->txoctetcount
);
2814 ast_verbose(" Report block:\n");
2815 ast_verbose(" Fraction lost: %u\n", fraction
);
2816 ast_verbose(" Cumulative loss: %u\n", lost
);
2817 ast_verbose(" IA jitter: %.4f\n", rtp
->rxjitter
);
2818 ast_verbose(" Their last SR: %u\n", rtp
->rtcp
->themrxlsr
);
2819 ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader
[12])/65536.0));
2821 manager_event(EVENT_FLAG_REPORTING
, "RTCPSent", "To %s:%d\r\n"
2823 "SentNTP: %u.%010u\r\n"
2825 "SentPackets: %u\r\n"
2826 "SentOctets: %u\r\n"
2828 "FractionLost: %u\r\n"
2829 "CumulativeLoss: %u\r\n"
2830 "IAJitter: %.4f\r\n"
2831 "TheirLastSR: %u\r\n"
2832 "DLSR: %4.4f (sec)\r\n",
2833 ast_inet_ntoa(rtp
->rtcp
->them
.sin_addr
), ntohs(rtp
->rtcp
->them
.sin_port
),
2835 (unsigned int)now
.tv_sec
, (unsigned int)now
.tv_usec
*4096,
2842 rtp
->rtcp
->themrxlsr
,
2843 (double)(ntohl(rtcpheader
[12])/65536.0));
2847 /*! \brief Send RTCP recipient's report */
2848 static int ast_rtcp_write_rr(const void *data
)
2850 struct ast_rtp
*rtp
= (struct ast_rtp
*)data
;
2854 unsigned int extended
;
2855 unsigned int expected
;
2856 unsigned int expected_interval
;
2857 unsigned int received_interval
;
2860 unsigned int *rtcpheader
;
2862 struct timeval dlsr
;
2865 if (!rtp
|| !rtp
->rtcp
|| (&rtp
->rtcp
->them
.sin_addr
== 0))
2868 if (!rtp
->rtcp
->them
.sin_addr
.s_addr
) {
2869 ast_log(LOG_ERROR
, "RTCP RR transmission error, rtcp halted\n");
2870 AST_SCHED_DEL(rtp
->sched
, rtp
->rtcp
->schedid
);
2874 extended
= rtp
->cycles
+ rtp
->lastrxseqno
;
2875 expected
= extended
- rtp
->seedrxseqno
+ 1;
2876 lost
= expected
- rtp
->rxcount
;
2877 expected_interval
= expected
- rtp
->rtcp
->expected_prior
;
2878 rtp
->rtcp
->expected_prior
= expected
;
2879 received_interval
= rtp
->rxcount
- rtp
->rtcp
->received_prior
;
2880 rtp
->rtcp
->received_prior
= rtp
->rxcount
;
2881 lost_interval
= expected_interval
- received_interval
;
2882 if (expected_interval
== 0 || lost_interval
<= 0)
2885 fraction
= (lost_interval
<< 8) / expected_interval
;
2886 gettimeofday(&now
, NULL
);
2887 timersub(&now
, &rtp
->rtcp
->rxlsr
, &dlsr
);
2888 rtcpheader
= (unsigned int *)bdata
;
2889 rtcpheader
[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR
<< 16) | ((len
/4)-1));
2890 rtcpheader
[1] = htonl(rtp
->ssrc
);
2891 rtcpheader
[2] = htonl(rtp
->themssrc
);
2892 rtcpheader
[3] = htonl(((fraction
& 0xff) << 24) | (lost
& 0xffffff));
2893 rtcpheader
[4] = htonl((rtp
->cycles
) | ((rtp
->lastrxseqno
& 0xffff)));
2894 rtcpheader
[5] = htonl((unsigned int)(rtp
->rxjitter
* 65536.));
2895 rtcpheader
[6] = htonl(rtp
->rtcp
->themrxlsr
);
2896 rtcpheader
[7] = htonl((((dlsr
.tv_sec
* 1000) + (dlsr
.tv_usec
/ 1000)) * 65536) / 1000);
2898 if (rtp
->rtcp
->sendfur
) {
2899 rtcpheader
[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR
<< 16) | 1); /* Header from page 36 in RFC 3550 */
2900 rtcpheader
[9] = htonl(rtp
->ssrc
); /* Our SSRC */
2902 rtp
->rtcp
->sendfur
= 0;
2905 /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
2906 it can change mid call, and SDES can't) */
2907 rtcpheader
[len
/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES
<< 16) | 2);
2908 rtcpheader
[(len
/4)+1] = htonl(rtp
->ssrc
); /* Our SSRC */
2909 rtcpheader
[(len
/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
2912 res
= sendto(rtp
->rtcp
->s
, (unsigned int *)rtcpheader
, len
, 0, (struct sockaddr
*)&rtp
->rtcp
->them
, sizeof(rtp
->rtcp
->them
));
2915 ast_log(LOG_ERROR
, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno
));
2916 /* Remove the scheduler */
2917 AST_SCHED_DEL(rtp
->sched
, rtp
->rtcp
->schedid
);
2921 rtp
->rtcp
->rr_count
++;
2923 if (rtcp_debug_test_addr(&rtp
->rtcp
->them
)) {
2924 ast_verbose("\n* Sending RTCP RR to %s:%d\n"
2925 " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
2926 " IA jitter: %.4f\n"
2927 " Their last SR: %u\n"
2928 " DLSR: %4.4f (sec)\n\n",
2929 ast_inet_ntoa(rtp
->rtcp
->them
.sin_addr
),
2930 ntohs(rtp
->rtcp
->them
.sin_port
),
2931 rtp
->ssrc
, rtp
->themssrc
, fraction
, lost
,
2933 rtp
->rtcp
->themrxlsr
,
2934 (double)(ntohl(rtcpheader
[7])/65536.0));
2940 /*! \brief Write and RTCP packet to the far end
2941 * \note Decide if we are going to send an SR (with Reception Block) or RR
2942 * RR is sent if we have not sent any rtp packets in the previous interval */
2943 static int ast_rtcp_write(const void *data
)
2945 struct ast_rtp
*rtp
= (struct ast_rtp
*)data
;
2948 if (!rtp
|| !rtp
->rtcp
)
2951 if (rtp
->txcount
> rtp
->rtcp
->lastsrtxcount
)
2952 res
= ast_rtcp_write_sr(data
);
2954 res
= ast_rtcp_write_rr(data
);
2959 /*! \brief generate comfort noice (CNG) */
2960 int ast_rtp_sendcng(struct ast_rtp
*rtp
, int level
)
2962 unsigned int *rtpheader
;
2967 level
= 127 - (level
& 0x7f);
2968 payload
= ast_rtp_lookup_code(rtp
, 0, AST_RTP_CN
);
2970 /* If we have no peer, return immediately */
2971 if (!rtp
->them
.sin_addr
.s_addr
)
2974 rtp
->dtmfmute
= ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
2976 /* Get a pointer to the header */
2977 rtpheader
= (unsigned int *)data
;
2978 rtpheader
[0] = htonl((2 << 30) | (1 << 23) | (payload
<< 16) | (rtp
->seqno
++));
2979 rtpheader
[1] = htonl(rtp
->lastts
);
2980 rtpheader
[2] = htonl(rtp
->ssrc
);
2982 if (rtp
->them
.sin_port
&& rtp
->them
.sin_addr
.s_addr
) {
2983 res
= sendto(rtp
->s
, (void *)rtpheader
, hdrlen
+ 1, 0, (struct sockaddr
*)&rtp
->them
, sizeof(rtp
->them
));
2985 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
));
2986 if (rtp_debug_test_addr(&rtp
->them
))
2987 ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
2988 , ast_inet_ntoa(rtp
->them
.sin_addr
), ntohs(rtp
->them
.sin_port
), payload
, rtp
->seqno
, rtp
->lastts
,res
- hdrlen
);
2994 /*! \brief Write RTP packet with audio or video media frames into UDP packet */
2995 static int ast_rtp_raw_write(struct ast_rtp
*rtp
, struct ast_frame
*f
, int codec
)
2997 unsigned char *rtpheader
;
3004 ms
= calc_txstamp(rtp
, &f
->delivery
);
3005 /* Default prediction */
3006 if (f
->frametype
== AST_FRAME_VOICE
) {
3007 pred
= rtp
->lastts
+ f
->samples
;
3009 /* Re-calculate last TS */
3010 rtp
->lastts
= rtp
->lastts
+ ms
* 8;
3011 if (ast_tvzero(f
->delivery
)) {
3012 /* If this isn't an absolute delivery time, Check if it is close to our prediction,
3013 and if so, go with our prediction */
3014 if (abs(rtp
->lastts
- pred
) < MAX_TIMESTAMP_SKEW
)
3017 ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp
->lastts
- pred
), ms
);
3021 } else if (f
->frametype
== AST_FRAME_VIDEO
) {
3022 mark
= f
->subclass
& 0x1;
3023 pred
= rtp
->lastovidtimestamp
+ f
->samples
;
3024 /* Re-calculate last TS */
3025 rtp
->lastts
= rtp
->lastts
+ ms
* 90;
3026 /* If it's close to our prediction, go for it */
3027 if (ast_tvzero(f
->delivery
)) {
3028 if (abs(rtp
->lastts
- pred
) < 7200) {
3030 rtp
->lastovidtimestamp
+= f
->samples
;
3032 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
);
3033 rtp
->lastovidtimestamp
= rtp
->lastts
;
3037 pred
= rtp
->lastotexttimestamp
+ f
->samples
;
3038 /* Re-calculate last TS */
3039 rtp
->lastts
= rtp
->lastts
+ ms
* 90;
3040 /* If it's close to our prediction, go for it */
3041 if (ast_tvzero(f
->delivery
)) {
3042 if (abs(rtp
->lastts
- pred
) < 7200) {
3044 rtp
->lastotexttimestamp
+= f
->samples
;
3046 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
);
3047 rtp
->lastotexttimestamp
= rtp
->lastts
;
3052 /* If we have been explicitly told to set the marker bit do so */
3053 if (rtp
->set_marker_bit
) {
3055 rtp
->set_marker_bit
= 0;
3058 /* If the timestamp for non-digit packets has moved beyond the timestamp
3059 for digits, update the digit timestamp.
3061 if (rtp
->lastts
> rtp
->lastdigitts
)
3062 rtp
->lastdigitts
= rtp
->lastts
;
3064 if (ast_test_flag(f
, AST_FRFLAG_HAS_TIMING_INFO
))
3065 rtp
->lastts
= f
->ts
* 8;
3067 /* Get a pointer to the header */
3068 rtpheader
= (unsigned char *)(f
->data
- hdrlen
);
3070 put_unaligned_uint32(rtpheader
, htonl((2 << 30) | (codec
<< 16) | (rtp
->seqno
) | (mark
<< 23)));
3071 put_unaligned_uint32(rtpheader
+ 4, htonl(rtp
->lastts
));
3072 put_unaligned_uint32(rtpheader
+ 8, htonl(rtp
->ssrc
));
3074 if (rtp
->them
.sin_port
&& rtp
->them
.sin_addr
.s_addr
) {
3075 res
= sendto(rtp
->s
, (void *)rtpheader
, f
->datalen
+ hdrlen
, 0, (struct sockaddr
*)&rtp
->them
, sizeof(rtp
->them
));
3077 if (!rtp
->nat
|| (rtp
->nat
&& (ast_test_flag(rtp
, FLAG_NAT_ACTIVE
) == FLAG_NAT_ACTIVE
))) {
3078 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
));
3079 } else if (((ast_test_flag(rtp
, FLAG_NAT_ACTIVE
) == FLAG_NAT_INACTIVE
) || rtpdebug
) && !ast_test_flag(rtp
, FLAG_NAT_INACTIVE_NOWARN
)) {
3080 /* Only give this error message once if we are not RTP debugging */
3081 if (option_debug
|| rtpdebug
)
3082 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
));
3083 ast_set_flag(rtp
, FLAG_NAT_INACTIVE_NOWARN
);
3087 rtp
->txoctetcount
+=(res
- hdrlen
);
3089 if (rtp
->rtcp
&& rtp
->rtcp
->schedid
< 1)
3090 rtp
->rtcp
->schedid
= ast_sched_add(rtp
->sched
, ast_rtcp_calc_interval(rtp
), ast_rtcp_write
, rtp
);
3093 if (rtp_debug_test_addr(&rtp
->them
))
3094 ast_verbose("Sent RTP packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
3095 ast_inet_ntoa(rtp
->them
.sin_addr
), ntohs(rtp
->them
.sin_port
), codec
, rtp
->seqno
, rtp
->lastts
,res
- hdrlen
);
3103 void ast_rtp_codec_setpref(struct ast_rtp
*rtp
, struct ast_codec_pref
*prefs
)
3106 for (x
= 0; x
< 32; x
++) { /* Ugly way */
3107 rtp
->pref
.order
[x
] = prefs
->order
[x
];
3108 rtp
->pref
.framing
[x
] = prefs
->framing
[x
];
3111 ast_smoother_free(rtp
->smoother
);
3112 rtp
->smoother
= NULL
;
3115 struct ast_codec_pref
*ast_rtp_codec_getpref(struct ast_rtp
*rtp
)
3120 int ast_rtp_codec_getformat(int pt
)
3122 if (pt
< 0 || pt
> MAX_RTP_PT
)
3123 return 0; /* bogus payload type */
3125 if (static_RTP_PT
[pt
].isAstFormat
)
3126 return static_RTP_PT
[pt
].code
;
3131 int ast_rtp_write(struct ast_rtp
*rtp
, struct ast_frame
*_f
)
3133 struct ast_frame
*f
;
3139 /* If we have no peer, return immediately */
3140 if (!rtp
->them
.sin_addr
.s_addr
)
3143 /* If there is no data length, return immediately */
3147 /* Make sure we have enough space for RTP header */
3148 if ((_f
->frametype
!= AST_FRAME_VOICE
) && (_f
->frametype
!= AST_FRAME_VIDEO
) && (_f
->frametype
!= AST_FRAME_TEXT
)) {
3149 ast_log(LOG_WARNING
, "RTP can only send voice, video and text\n");
3153 /* The bottom bit of a video subclass contains the marker bit */
3154 subclass
= _f
->subclass
;
3155 if (_f
->frametype
== AST_FRAME_VIDEO
)
3158 codec
= ast_rtp_lookup_code(rtp
, 1, subclass
);
3160 ast_log(LOG_WARNING
, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f
->subclass
));
3164 if (rtp
->lasttxformat
!= subclass
) {
3165 /* New format, reset the smoother */
3166 ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp
->lasttxformat
), ast_getformatname(subclass
));
3167 rtp
->lasttxformat
= subclass
;
3169 ast_smoother_free(rtp
->smoother
);
3170 rtp
->smoother
= NULL
;
3173 if (!rtp
->smoother
&& subclass
!= AST_FORMAT_SPEEX
&& subclass
!= AST_FORMAT_G723_1
) {
3174 struct ast_format_list fmt
= ast_codec_pref_getsize(&rtp
->pref
, subclass
);
3175 if (fmt
.inc_ms
) { /* if codec parameters is set / avoid division by zero */
3176 if (!(rtp
->smoother
= ast_smoother_new((fmt
.cur_ms
* fmt
.fr_len
) / fmt
.inc_ms
))) {
3177 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
));
3181 ast_smoother_set_flags(rtp
->smoother
, fmt
.flags
);
3182 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
));
3185 if (rtp
->smoother
) {
3186 if (ast_smoother_test_flag(rtp
->smoother
, AST_SMOOTHER_FLAG_BE
)) {
3187 ast_smoother_feed_be(rtp
->smoother
, _f
);
3189 ast_smoother_feed(rtp
->smoother
, _f
);
3192 while ((f
= ast_smoother_read(rtp
->smoother
)) && (f
->data
)) {
3193 if (f
->subclass
== AST_FORMAT_G722
) {
3194 /* G.722 is silllllllllllllly */
3198 ast_rtp_raw_write(rtp
, f
, codec
);
3201 /* Don't buffer outgoing frames; send them one-per-packet: */
3202 if (_f
->offset
< hdrlen
)
3203 f
= ast_frdup(_f
); /*! \bug XXX this might never be free'd. Why do we do this? */
3207 ast_rtp_raw_write(rtp
, f
, codec
);
3215 /*! \brief Unregister interface to channel driver */
3216 void ast_rtp_proto_unregister(struct ast_rtp_protocol
*proto
)
3218 AST_RWLIST_WRLOCK(&protos
);
3219 AST_RWLIST_REMOVE(&protos
, proto
, list
);
3220 AST_RWLIST_UNLOCK(&protos
);
3223 /*! \brief Register interface to channel driver */
3224 int ast_rtp_proto_register(struct ast_rtp_protocol
*proto
)
3226 struct ast_rtp_protocol
*cur
;
3228 AST_RWLIST_WRLOCK(&protos
);
3229 AST_RWLIST_TRAVERSE(&protos
, cur
, list
) {
3230 if (!strcmp(cur
->type
, proto
->type
)) {
3231 ast_log(LOG_WARNING
, "Tried to register same protocol '%s' twice\n", cur
->type
);
3232 AST_RWLIST_UNLOCK(&protos
);
3236 AST_RWLIST_INSERT_HEAD(&protos
, proto
, list
);
3237 AST_RWLIST_UNLOCK(&protos
);
3242 /*! \brief Bridge loop for true native bridge (reinvite) */
3243 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
)
3245 struct ast_frame
*fr
= NULL
;
3246 struct ast_channel
*who
= NULL
, *other
= NULL
, *cs
[3] = {NULL
, };
3247 int oldcodec0
= codec0
, oldcodec1
= codec1
;
3248 struct sockaddr_in ac1
= {0,}, vac1
= {0,}, tac1
= {0,}, ac0
= {0,}, vac0
= {0,}, tac0
= {0,};
3249 struct sockaddr_in t1
= {0,}, vt1
= {0,}, tt1
= {0,}, t0
= {0,}, vt0
= {0,}, tt0
= {0,};
3251 /* Set it up so audio goes directly between the two endpoints */
3253 /* Test the first channel */
3254 if (!(pr0
->set_rtp_peer(c0
, p1
, vp1
, tp1
, codec1
, ast_test_flag(p1
, FLAG_NAT_ACTIVE
)))) {
3255 ast_rtp_get_peer(p1
, &ac1
);
3257 ast_rtp_get_peer(vp1
, &vac1
);
3259 ast_rtp_get_peer(tp1
, &tac1
);
3261 ast_log(LOG_WARNING
, "Channel '%s' failed to talk to '%s'\n", c0
->name
, c1
->name
);
3263 /* Test the second channel */
3264 if (!(pr1
->set_rtp_peer(c1
, p0
, vp0
, tp0
, codec0
, ast_test_flag(p0
, FLAG_NAT_ACTIVE
)))) {
3265 ast_rtp_get_peer(p0
, &ac0
);
3267 ast_rtp_get_peer(vp0
, &vac0
);
3269 ast_rtp_get_peer(tp0
, &tac0
);
3271 ast_log(LOG_WARNING
, "Channel '%s' failed to talk to '%s'\n", c1
->name
, c0
->name
);
3273 /* Now we can unlock and move into our loop */
3274 ast_channel_unlock(c0
);
3275 ast_channel_unlock(c1
);
3277 ast_poll_channel_add(c0
, c1
);
3279 /* Throw our channels into the structure and enter the loop */
3284 /* Check if anything changed */
3285 if ((c0
->tech_pvt
!= pvt0
) ||
3286 (c1
->tech_pvt
!= pvt1
) ||
3287 (c0
->masq
|| c0
->masqr
|| c1
->masq
|| c1
->masqr
) ||
3288 (c0
->monitor
|| c0
->audiohooks
|| c1
->monitor
|| c1
->audiohooks
)) {
3289 ast_debug(1, "Oooh, something is weird, backing out\n");
3290 if (c0
->tech_pvt
== pvt0
)
3291 if (pr0
->set_rtp_peer(c0
, NULL
, NULL
, NULL
, 0, 0))
3292 ast_log(LOG_WARNING
, "Channel '%s' failed to break RTP bridge\n", c0
->name
);
3293 if (c1
->tech_pvt
== pvt1
)
3294 if (pr1
->set_rtp_peer(c1
, NULL
, NULL
, NULL
, 0, 0))
3295 ast_log(LOG_WARNING
, "Channel '%s' failed to break RTP bridge\n", c1
->name
);
3296 ast_poll_channel_del(c0
, c1
);
3297 return AST_BRIDGE_RETRY
;
3300 /* Check if they have changed their address */
3301 ast_rtp_get_peer(p1
, &t1
);
3303 ast_rtp_get_peer(vp1
, &vt1
);
3305 ast_rtp_get_peer(tp1
, &tt1
);
3307 codec1
= pr1
->get_codec(c1
);
3308 ast_rtp_get_peer(p0
, &t0
);
3310 ast_rtp_get_peer(vp0
, &vt0
);
3312 ast_rtp_get_peer(tp0
, &tt0
);
3314 codec0
= pr0
->get_codec(c0
);
3315 if ((inaddrcmp(&t1
, &ac1
)) ||
3316 (vp1
&& inaddrcmp(&vt1
, &vac1
)) ||
3317 (tp1
&& inaddrcmp(&tt1
, &tac1
)) ||
3318 (codec1
!= oldcodec1
)) {
3319 ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
3320 c1
->name
, ast_inet_ntoa(t1
.sin_addr
), ntohs(t1
.sin_port
), codec1
);
3321 ast_debug(2, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
3322 c1
->name
, ast_inet_ntoa(vt1
.sin_addr
), ntohs(vt1
.sin_port
), codec1
);
3323 ast_debug(2, "Oooh, '%s' changed end taddress to %s:%d (format %d)\n",
3324 c1
->name
, ast_inet_ntoa(tt1
.sin_addr
), ntohs(tt1
.sin_port
), codec1
);
3325 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3326 c1
->name
, ast_inet_ntoa(ac1
.sin_addr
), ntohs(ac1
.sin_port
), oldcodec1
);
3327 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3328 c1
->name
, ast_inet_ntoa(vac1
.sin_addr
), ntohs(vac1
.sin_port
), oldcodec1
);
3329 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3330 c1
->name
, ast_inet_ntoa(tac1
.sin_addr
), ntohs(tac1
.sin_port
), oldcodec1
);
3331 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
)))
3332 ast_log(LOG_WARNING
, "Channel '%s' failed to update to '%s'\n", c0
->name
, c1
->name
);
3333 memcpy(&ac1
, &t1
, sizeof(ac1
));
3334 memcpy(&vac1
, &vt1
, sizeof(vac1
));
3335 memcpy(&tac1
, &tt1
, sizeof(tac1
));
3338 if ((inaddrcmp(&t0
, &ac0
)) ||
3339 (vp0
&& inaddrcmp(&vt0
, &vac0
)) ||
3340 (tp0
&& inaddrcmp(&tt0
, &tac0
))) {
3341 ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
3342 c0
->name
, ast_inet_ntoa(t0
.sin_addr
), ntohs(t0
.sin_port
), codec0
);
3343 ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
3344 c0
->name
, ast_inet_ntoa(ac0
.sin_addr
), ntohs(ac0
.sin_port
), oldcodec0
);
3345 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
)))
3346 ast_log(LOG_WARNING
, "Channel '%s' failed to update to '%s'\n", c1
->name
, c0
->name
);
3347 memcpy(&ac0
, &t0
, sizeof(ac0
));
3348 memcpy(&vac0
, &vt0
, sizeof(vac0
));
3349 memcpy(&tac0
, &tt0
, sizeof(tac0
));
3353 /* Wait for frame to come in on the channels */
3354 if (!(who
= ast_waitfor_n(cs
, 2, &timeoutms
))) {
3356 if (pr0
->set_rtp_peer(c0
, NULL
, NULL
, NULL
, 0, 0))
3357 ast_log(LOG_WARNING
, "Channel '%s' failed to break RTP bridge\n", c0
->name
);
3358 if (pr1
->set_rtp_peer(c1
, NULL
, NULL
, NULL
, 0, 0))
3359 ast_log(LOG_WARNING
, "Channel '%s' failed to break RTP bridge\n", c1
->name
);
3360 return AST_BRIDGE_RETRY
;
3362 ast_debug(1, "Ooh, empty read...\n");
3363 if (ast_check_hangup(c0
) || ast_check_hangup(c1
))
3368 other
= (who
== c0
) ? c1
: c0
;
3369 if (!fr
|| ((fr
->frametype
== AST_FRAME_DTMF_BEGIN
|| fr
->frametype
== AST_FRAME_DTMF_END
) &&
3370 (((who
== c0
) && (flags
& AST_BRIDGE_DTMF_CHANNEL_0
)) ||
3371 ((who
== c1
) && (flags
& AST_BRIDGE_DTMF_CHANNEL_1
))))) {
3372 /* Break out of bridge */
3375 ast_debug(1, "Oooh, got a %s\n", fr
? "digit" : "hangup");
3376 if (c0
->tech_pvt
== pvt0
)
3377 if (pr0
->set_rtp_peer(c0
, NULL
, NULL
, NULL
, 0, 0))
3378 ast_log(LOG_WARNING
, "Channel '%s' failed to break RTP bridge\n", c0
->name
);
3379 if (c1
->tech_pvt
== pvt1
)
3380 if (pr1
->set_rtp_peer(c1
, NULL
, NULL
, NULL
, 0, 0))
3381 ast_log(LOG_WARNING
, "Channel '%s' failed to break RTP bridge\n", c1
->name
);
3382 ast_poll_channel_del(c0
, c1
);
3383 return AST_BRIDGE_COMPLETE
;
3384 } else if ((fr
->frametype
== AST_FRAME_CONTROL
) && !(flags
& AST_BRIDGE_IGNORE_SIGS
)) {
3385 if ((fr
->subclass
== AST_CONTROL_HOLD
) ||
3386 (fr
->subclass
== AST_CONTROL_UNHOLD
) ||
3387 (fr
->subclass
== AST_CONTROL_VIDUPDATE
) ||
3388 (fr
->subclass
== AST_CONTROL_T38
) ||
3389 (fr
->subclass
== AST_CONTROL_SRCUPDATE
)) {
3390 if (fr
->subclass
== AST_CONTROL_HOLD
) {
3391 /* If we someone went on hold we want the other side to reinvite back to us */
3393 pr1
->set_rtp_peer(c1
, NULL
, NULL
, NULL
, 0, 0);
3395 pr0
->set_rtp_peer(c0
, NULL
, NULL
, NULL
, 0, 0);
3396 } else if (fr
->subclass
== AST_CONTROL_UNHOLD
) {
3397 /* If they went off hold they should go back to being direct */
3399 pr1
->set_rtp_peer(c1
, p0
, vp0
, tp0
, codec0
, ast_test_flag(p0
, FLAG_NAT_ACTIVE
));
3401 pr0
->set_rtp_peer(c0
, p1
, vp1
, tp1
, codec1
, ast_test_flag(p1
, FLAG_NAT_ACTIVE
));
3403 /* Update local address information */
3404 ast_rtp_get_peer(p0
, &t0
);
3405 memcpy(&ac0
, &t0
, sizeof(ac0
));
3406 ast_rtp_get_peer(p1
, &t1
);
3407 memcpy(&ac1
, &t1
, sizeof(ac1
));
3408 /* Update codec information */
3409 if (pr0
->get_codec
&& c0
->tech_pvt
)
3410 oldcodec0
= codec0
= pr0
->get_codec(c0
);
3411 if (pr1
->get_codec
&& c1
->tech_pvt
)
3412 oldcodec1
= codec1
= pr1
->get_codec(c1
);
3413 ast_indicate_data(other
, fr
->subclass
, fr
->data
, fr
->datalen
);
3418 ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr
->subclass
, who
->name
);
3419 return AST_BRIDGE_COMPLETE
;
3422 if ((fr
->frametype
== AST_FRAME_DTMF_BEGIN
) ||
3423 (fr
->frametype
== AST_FRAME_DTMF_END
) ||
3424 (fr
->frametype
== AST_FRAME_VOICE
) ||
3425 (fr
->frametype
== AST_FRAME_VIDEO
) ||
3426 (fr
->frametype
== AST_FRAME_IMAGE
) ||
3427 (fr
->frametype
== AST_FRAME_HTML
) ||
3428 (fr
->frametype
== AST_FRAME_MODEM
) ||
3429 (fr
->frametype
== AST_FRAME_TEXT
)) {
3430 ast_write(other
, fr
);
3442 ast_poll_channel_del(c0
, c1
);
3444 if (pr0
->set_rtp_peer(c0
, NULL
, NULL
, NULL
, 0, 0))
3445 ast_log(LOG_WARNING
, "Channel '%s' failed to break RTP bridge\n", c0
->name
);
3446 if (pr1
->set_rtp_peer(c1
, NULL
, NULL
, NULL
, 0, 0))
3447 ast_log(LOG_WARNING
, "Channel '%s' failed to break RTP bridge\n", c1
->name
);
3449 return AST_BRIDGE_FAILED
;
3452 /*! \brief P2P RTP Callback */
3454 static int p2p_rtp_callback(int *id
, int fd
, short events
, void *cbdata
)
3456 int res
= 0, hdrlen
= 12;
3457 struct sockaddr_in sin
;
3459 unsigned int *header
;
3460 struct ast_rtp
*rtp
= cbdata
, *bridged
= NULL
;
3466 if ((res
= recvfrom(fd
, rtp
->rawdata
+ AST_FRIENDLY_OFFSET
, sizeof(rtp
->rawdata
) - AST_FRIENDLY_OFFSET
, 0, (struct sockaddr
*)&sin
, &len
)) < 0)
3469 header
= (unsigned int *)(rtp
->rawdata
+ AST_FRIENDLY_OFFSET
);
3471 /* If NAT support is turned on, then see if we need to change their address */
3473 ((rtp
->them
.sin_addr
.s_addr
!= sin
.sin_addr
.s_addr
) ||
3474 (rtp
->them
.sin_port
!= sin
.sin_port
))) {
3477 ast_set_flag(rtp
, FLAG_NAT_ACTIVE
);
3478 if (option_debug
|| rtpdebug
)
3479 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
));
3482 /* Write directly out to other RTP stream if bridged */
3483 if ((bridged
= ast_rtp_get_bridged(rtp
)))
3484 bridge_p2p_rtp_write(rtp
, bridged
, header
, res
, hdrlen
);
3489 /*! \brief Helper function to switch a channel and RTP stream into callback mode */
3490 static int p2p_callback_enable(struct ast_channel
*chan
, struct ast_rtp
*rtp
, int **iod
)
3492 /* If we need DTMF, are looking for STUN, or we have no IO structure then we can't do direct callback */
3493 if (ast_test_flag(rtp
, FLAG_P2P_NEED_DTMF
) || ast_test_flag(rtp
, FLAG_HAS_STUN
) || !rtp
->io
)
3496 /* If the RTP structure is already in callback mode, remove it temporarily */
3498 ast_io_remove(rtp
->io
, rtp
->ioid
);
3502 /* Steal the file descriptors from the channel */
3505 /* Now, fire up callback mode */
3506 iod
[0] = ast_io_add(rtp
->io
, ast_rtp_fd(rtp
), p2p_rtp_callback
, AST_IO_IN
, rtp
);
3511 static int p2p_callback_enable(struct ast_channel
*chan
, struct ast_rtp
*rtp
, int **iod
)
3517 /*! \brief Helper function to switch a channel and RTP stream out of callback mode */
3518 static int p2p_callback_disable(struct ast_channel
*chan
, struct ast_rtp
*rtp
, int **iod
)
3520 ast_channel_lock(chan
);
3522 /* Remove the callback from the IO context */
3523 ast_io_remove(rtp
->io
, iod
[0]);
3525 /* Restore file descriptors */
3526 chan
->fds
[0] = ast_rtp_fd(rtp
);
3527 ast_channel_unlock(chan
);
3529 /* Restore callback mode if previously used */
3530 if (ast_test_flag(rtp
, FLAG_CALLBACK_MODE
))
3531 rtp
->ioid
= ast_io_add(rtp
->io
, ast_rtp_fd(rtp
), rtpread
, AST_IO_IN
, rtp
);
3536 /*! \brief Helper function that sets what an RTP structure is bridged to */
3537 static void p2p_set_bridge(struct ast_rtp
*rtp0
, struct ast_rtp
*rtp1
)
3539 rtp_bridge_lock(rtp0
);
3540 rtp0
->bridged
= rtp1
;
3541 rtp_bridge_unlock(rtp0
);
3544 /*! \brief Bridge loop for partial native bridge (packet2packet)
3546 In p2p mode, Asterisk is a very basic RTP proxy, just forwarding whatever
3547 rtp/rtcp we get in to the channel.
3548 \note this currently only works for Audio
3550 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
)
3552 struct ast_frame
*fr
= NULL
;
3553 struct ast_channel
*who
= NULL
, *other
= NULL
, *cs
[3] = {NULL
, };
3554 int *p0_iod
[2] = {NULL
, NULL
}, *p1_iod
[2] = {NULL
, NULL
};
3555 int p0_callback
= 0, p1_callback
= 0;
3556 enum ast_bridge_result res
= AST_BRIDGE_FAILED
;
3558 /* Okay, setup each RTP structure to do P2P forwarding */
3559 ast_clear_flag(p0
, FLAG_P2P_SENT_MARK
);
3560 p2p_set_bridge(p0
, p1
);
3561 ast_clear_flag(p1
, FLAG_P2P_SENT_MARK
);
3562 p2p_set_bridge(p1
, p0
);
3564 /* Activate callback modes if possible */
3565 p0_callback
= p2p_callback_enable(c0
, p0
, &p0_iod
[0]);
3566 p1_callback
= p2p_callback_enable(c1
, p1
, &p1_iod
[0]);
3568 /* Now let go of the channel locks and be on our way */
3569 ast_channel_unlock(c0
);
3570 ast_channel_unlock(c1
);
3572 ast_poll_channel_add(c0
, c1
);
3574 /* Go into a loop forwarding frames until we don't need to anymore */
3579 /* If the underlying formats have changed force this bridge to break */
3580 if ((c0
->rawreadformat
!= c1
->rawwriteformat
) || (c1
->rawreadformat
!= c0
->rawwriteformat
)) {
3581 ast_debug(3, "p2p-rtp-bridge: Oooh, formats changed, backing out\n");
3582 res
= AST_BRIDGE_FAILED_NOWARN
;
3585 /* Check if anything changed */
3586 if ((c0
->tech_pvt
!= pvt0
) ||
3587 (c1
->tech_pvt
!= pvt1
) ||
3588 (c0
->masq
|| c0
->masqr
|| c1
->masq
|| c1
->masqr
) ||
3589 (c0
->monitor
|| c0
->audiohooks
|| c1
->monitor
|| c1
->audiohooks
)) {
3590 ast_debug(3, "p2p-rtp-bridge: Oooh, something is weird, backing out\n");
3591 /* 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 */
3592 if ((c0
->masq
|| c0
->masqr
) && (fr
= ast_read(c0
)))
3594 if ((c1
->masq
|| c1
->masqr
) && (fr
= ast_read(c1
)))
3596 res
= AST_BRIDGE_RETRY
;
3599 /* Wait on a channel to feed us a frame */
3600 if (!(who
= ast_waitfor_n(cs
, 2, &timeoutms
))) {
3602 res
= AST_BRIDGE_RETRY
;
3605 if (option_debug
> 2)
3606 ast_log(LOG_NOTICE
, "p2p-rtp-bridge: Ooh, empty read...\n");
3607 if (ast_check_hangup(c0
) || ast_check_hangup(c1
))
3611 /* Read in frame from channel */
3613 other
= (who
== c0
) ? c1
: c0
;
3614 /* Depending on the frame we may need to break out of our bridge */
3615 if (!fr
|| ((fr
->frametype
== AST_FRAME_DTMF_BEGIN
|| fr
->frametype
== AST_FRAME_DTMF_END
) &&
3616 ((who
== c0
) && (flags
& AST_BRIDGE_DTMF_CHANNEL_0
)) |
3617 ((who
== c1
) && (flags
& AST_BRIDGE_DTMF_CHANNEL_1
)))) {
3618 /* Record received frame and who */
3621 ast_debug(3, "p2p-rtp-bridge: Ooh, got a %s\n", fr
? "digit" : "hangup");
3622 res
= AST_BRIDGE_COMPLETE
;
3624 } else if ((fr
->frametype
== AST_FRAME_CONTROL
) && !(flags
& AST_BRIDGE_IGNORE_SIGS
)) {
3625 if ((fr
->subclass
== AST_CONTROL_HOLD
) ||
3626 (fr
->subclass
== AST_CONTROL_UNHOLD
) ||
3627 (fr
->subclass
== AST_CONTROL_VIDUPDATE
) ||
3628 (fr
->subclass
== AST_CONTROL_T38
) ||
3629 (fr
->subclass
== AST_CONTROL_SRCUPDATE
)) {
3630 /* If we are going on hold, then break callback mode and P2P bridging */
3631 if (fr
->subclass
== AST_CONTROL_HOLD
) {
3633 p0_callback
= p2p_callback_disable(c0
, p0
, &p0_iod
[0]);
3635 p1_callback
= p2p_callback_disable(c1
, p1
, &p1_iod
[0]);
3636 p2p_set_bridge(p0
, NULL
);
3637 p2p_set_bridge(p1
, NULL
);
3638 } else if (fr
->subclass
== AST_CONTROL_UNHOLD
) {
3639 /* If we are off hold, then go back to callback mode and P2P bridging */
3640 ast_clear_flag(p0
, FLAG_P2P_SENT_MARK
);
3641 p2p_set_bridge(p0
, p1
);
3642 ast_clear_flag(p1
, FLAG_P2P_SENT_MARK
);
3643 p2p_set_bridge(p1
, p0
);
3644 p0_callback
= p2p_callback_enable(c0
, p0
, &p0_iod
[0]);
3645 p1_callback
= p2p_callback_enable(c1
, p1
, &p1_iod
[0]);
3647 ast_indicate_data(other
, fr
->subclass
, fr
->data
, fr
->datalen
);
3652 ast_debug(3, "p2p-rtp-bridge: Got a FRAME_CONTROL (%d) frame on channel %s\n", fr
->subclass
, who
->name
);
3653 res
= AST_BRIDGE_COMPLETE
;
3657 if ((fr
->frametype
== AST_FRAME_DTMF_BEGIN
) ||
3658 (fr
->frametype
== AST_FRAME_DTMF_END
) ||
3659 (fr
->frametype
== AST_FRAME_VOICE
) ||
3660 (fr
->frametype
== AST_FRAME_VIDEO
) ||
3661 (fr
->frametype
== AST_FRAME_IMAGE
) ||
3662 (fr
->frametype
== AST_FRAME_HTML
) ||
3663 (fr
->frametype
== AST_FRAME_MODEM
) ||
3664 (fr
->frametype
== AST_FRAME_TEXT
)) {
3665 ast_write(other
, fr
);
3678 /* If we are totally avoiding the core, then restore our link to it */
3680 p0_callback
= p2p_callback_disable(c0
, p0
, &p0_iod
[0]);
3682 p1_callback
= p2p_callback_disable(c1
, p1
, &p1_iod
[0]);
3684 /* Break out of the direct bridge */
3685 p2p_set_bridge(p0
, NULL
);
3686 p2p_set_bridge(p1
, NULL
);
3688 ast_poll_channel_del(c0
, c1
);
3693 /*! \page AstRTPbridge The Asterisk RTP bridge
3694 The RTP bridge is called from the channel drivers that are using the RTP
3695 subsystem in Asterisk - like SIP, H.323 and Jingle/Google Talk.
3697 This bridge aims to offload the Asterisk server by setting up
3698 the media stream directly between the endpoints, keeping the
3699 signalling in Asterisk.
3701 It checks with the channel driver, using a callback function, if
3702 there are possibilities for a remote bridge.
3704 If this fails, the bridge hands off to the core bridge. Reasons
3705 can be NAT support needed, DTMF features in audio needed by
3706 the PBX for transfers or spying/monitoring on channels.
3708 If transcoding is needed - we can't do a remote bridge.
3709 If only NAT support is needed, we're using Asterisk in
3710 RTP proxy mode with the p2p RTP bridge, basically
3711 forwarding incoming audio packets to the outbound
3712 stream on a network level.
3716 - ast_channel_early_bridge()
3717 - ast_channel_bridge()
3721 /*! \brief Bridge calls. If possible and allowed, initiate
3722 re-invite so the peers exchange media directly outside
3725 enum ast_bridge_result
ast_rtp_bridge(struct ast_channel
*c0
, struct ast_channel
*c1
, int flags
, struct ast_frame
**fo
, struct ast_channel
**rc
, int timeoutms
)
3727 struct ast_rtp
*p0
= NULL
, *p1
= NULL
; /* Audio RTP Channels */
3728 struct ast_rtp
*vp0
= NULL
, *vp1
= NULL
; /* Video RTP channels */
3729 struct ast_rtp
*tp0
= NULL
, *tp1
= NULL
; /* Text RTP channels */
3730 struct ast_rtp_protocol
*pr0
= NULL
, *pr1
= NULL
;
3731 enum ast_rtp_get_result audio_p0_res
= AST_RTP_GET_FAILED
, video_p0_res
= AST_RTP_GET_FAILED
, text_p0_res
= AST_RTP_GET_FAILED
;
3732 enum ast_rtp_get_result audio_p1_res
= AST_RTP_GET_FAILED
, video_p1_res
= AST_RTP_GET_FAILED
, text_p1_res
= AST_RTP_GET_FAILED
;
3733 enum ast_bridge_result res
= AST_BRIDGE_FAILED
;
3734 int codec0
= 0, codec1
= 0;
3735 void *pvt0
= NULL
, *pvt1
= NULL
;
3738 ast_channel_lock(c0
);
3739 while (ast_channel_trylock(c1
)) {
3740 ast_channel_unlock(c0
);
3742 ast_channel_lock(c0
);
3745 /* Ensure neither channel got hungup during lock avoidance */
3746 if (ast_check_hangup(c0
) || ast_check_hangup(c1
)) {
3747 ast_log(LOG_WARNING
, "Got hangup while attempting to bridge '%s' and '%s'\n", c0
->name
, c1
->name
);
3748 ast_channel_unlock(c0
);
3749 ast_channel_unlock(c1
);
3750 return AST_BRIDGE_FAILED
;
3753 /* Find channel driver interfaces */
3754 if (!(pr0
= get_proto(c0
))) {
3755 ast_log(LOG_WARNING
, "Can't find native functions for channel '%s'\n", c0
->name
);
3756 ast_channel_unlock(c0
);
3757 ast_channel_unlock(c1
);
3758 return AST_BRIDGE_FAILED
;
3760 if (!(pr1
= get_proto(c1
))) {
3761 ast_log(LOG_WARNING
, "Can't find native functions for channel '%s'\n", c1
->name
);
3762 ast_channel_unlock(c0
);
3763 ast_channel_unlock(c1
);
3764 return AST_BRIDGE_FAILED
;
3767 /* Get channel specific interface structures */
3768 pvt0
= c0
->tech_pvt
;
3769 pvt1
= c1
->tech_pvt
;
3771 /* Get audio and video interface (if native bridge is possible) */
3772 audio_p0_res
= pr0
->get_rtp_info(c0
, &p0
);
3773 video_p0_res
= pr0
->get_vrtp_info
? pr0
->get_vrtp_info(c0
, &vp0
) : AST_RTP_GET_FAILED
;
3774 text_p0_res
= pr0
->get_trtp_info
? pr0
->get_trtp_info(c0
, &vp0
) : AST_RTP_GET_FAILED
;
3775 audio_p1_res
= pr1
->get_rtp_info(c1
, &p1
);
3776 video_p1_res
= pr1
->get_vrtp_info
? pr1
->get_vrtp_info(c1
, &vp1
) : AST_RTP_GET_FAILED
;
3777 text_p1_res
= pr1
->get_trtp_info
? pr1
->get_trtp_info(c1
, &vp1
) : AST_RTP_GET_FAILED
;
3779 /* If we are carrying video, and both sides are not reinviting... then fail the native bridge */
3780 if (video_p0_res
!= AST_RTP_GET_FAILED
&& (audio_p0_res
!= AST_RTP_TRY_NATIVE
|| video_p0_res
!= AST_RTP_TRY_NATIVE
))
3781 audio_p0_res
= AST_RTP_GET_FAILED
;
3782 if (video_p1_res
!= AST_RTP_GET_FAILED
&& (audio_p1_res
!= AST_RTP_TRY_NATIVE
|| video_p1_res
!= AST_RTP_TRY_NATIVE
))
3783 audio_p1_res
= AST_RTP_GET_FAILED
;
3785 /* Check if a bridge is possible (partial/native) */
3786 if (audio_p0_res
== AST_RTP_GET_FAILED
|| audio_p1_res
== AST_RTP_GET_FAILED
) {
3787 /* Somebody doesn't want to play... */
3788 ast_channel_unlock(c0
);
3789 ast_channel_unlock(c1
);
3790 return AST_BRIDGE_FAILED_NOWARN
;
3793 /* If we need to feed DTMF frames into the core then only do a partial native bridge */
3794 if (ast_test_flag(p0
, FLAG_HAS_DTMF
) && (flags
& AST_BRIDGE_DTMF_CHANNEL_0
)) {
3795 ast_set_flag(p0
, FLAG_P2P_NEED_DTMF
);
3796 audio_p0_res
= AST_RTP_TRY_PARTIAL
;
3799 if (ast_test_flag(p1
, FLAG_HAS_DTMF
) && (flags
& AST_BRIDGE_DTMF_CHANNEL_1
)) {
3800 ast_set_flag(p1
, FLAG_P2P_NEED_DTMF
);
3801 audio_p1_res
= AST_RTP_TRY_PARTIAL
;
3804 /* If both sides are not using the same method of DTMF transmission
3805 * (ie: one is RFC2833, other is INFO... then we can not do direct media.
3806 * --------------------------------------------------
3807 * | DTMF Mode | HAS_DTMF | Accepts Begin Frames |
3808 * |-----------|------------|-----------------------|
3809 * | Inband | False | True |
3810 * | RFC2833 | True | True |
3811 * | SIP INFO | False | False |
3812 * --------------------------------------------------
3813 * However, if DTMF from both channels is being monitored by the core, then
3814 * we can still do packet-to-packet bridging, because passing through the
3815 * core will handle DTMF mode translation.
3817 if ( (ast_test_flag(p0
, FLAG_HAS_DTMF
) != ast_test_flag(p1
, FLAG_HAS_DTMF
)) ||
3818 (!c0
->tech
->send_digit_begin
!= !c1
->tech
->send_digit_begin
)) {
3819 if (!ast_test_flag(p0
, FLAG_P2P_NEED_DTMF
) || !ast_test_flag(p1
, FLAG_P2P_NEED_DTMF
)) {
3820 ast_channel_unlock(c0
);
3821 ast_channel_unlock(c1
);
3822 return AST_BRIDGE_FAILED_NOWARN
;
3824 audio_p0_res
= AST_RTP_TRY_PARTIAL
;
3825 audio_p1_res
= AST_RTP_TRY_PARTIAL
;
3828 /* If we need to feed frames into the core don't do a P2P bridge */
3829 if ((audio_p0_res
== AST_RTP_TRY_PARTIAL
&& ast_test_flag(p0
, FLAG_P2P_NEED_DTMF
)) ||
3830 (audio_p1_res
== AST_RTP_TRY_PARTIAL
&& ast_test_flag(p1
, FLAG_P2P_NEED_DTMF
))) {
3831 ast_channel_unlock(c0
);
3832 ast_channel_unlock(c1
);
3833 return AST_BRIDGE_FAILED_NOWARN
;
3836 /* Get codecs from both sides */
3837 codec0
= pr0
->get_codec
? pr0
->get_codec(c0
) : 0;
3838 codec1
= pr1
->get_codec
? pr1
->get_codec(c1
) : 0;
3839 if (codec0
&& codec1
&& !(codec0
& codec1
)) {
3840 /* Hey, we can't do native bridging if both parties speak different codecs */
3841 ast_debug(3, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0
, codec1
);
3842 ast_channel_unlock(c0
);
3843 ast_channel_unlock(c1
);
3844 return AST_BRIDGE_FAILED_NOWARN
;
3847 /* If either side can only do a partial bridge, then don't try for a true native bridge */
3848 if (audio_p0_res
== AST_RTP_TRY_PARTIAL
|| audio_p1_res
== AST_RTP_TRY_PARTIAL
) {
3849 struct ast_format_list fmt0
, fmt1
;
3851 /* In order to do Packet2Packet bridging both sides must be in the same rawread/rawwrite */
3852 if (c0
->rawreadformat
!= c1
->rawwriteformat
|| c1
->rawreadformat
!= c0
->rawwriteformat
) {
3853 ast_debug(1, "Cannot packet2packet bridge - raw formats are incompatible\n");
3854 ast_channel_unlock(c0
);
3855 ast_channel_unlock(c1
);
3856 return AST_BRIDGE_FAILED_NOWARN
;
3858 /* They must also be using the same packetization */
3859 fmt0
= ast_codec_pref_getsize(&p0
->pref
, c0
->rawreadformat
);
3860 fmt1
= ast_codec_pref_getsize(&p1
->pref
, c1
->rawreadformat
);
3861 if (fmt0
.cur_ms
!= fmt1
.cur_ms
) {
3862 ast_debug(1, "Cannot packet2packet bridge - packetization settings prevent it\n");
3863 ast_channel_unlock(c0
);
3864 ast_channel_unlock(c1
);
3865 return AST_BRIDGE_FAILED_NOWARN
;
3868 ast_verb(3, "Packet2Packet bridging %s and %s\n", c0
->name
, c1
->name
);
3869 res
= bridge_p2p_loop(c0
, c1
, p0
, p1
, timeoutms
, flags
, fo
, rc
, pvt0
, pvt1
);
3871 ast_verb(3, "Native bridging %s and %s\n", c0
->name
, c1
->name
);
3872 res
= bridge_native_loop(c0
, c1
, p0
, p1
, vp0
, vp1
, tp0
, tp1
, pr0
, pr1
, codec0
, codec1
, timeoutms
, flags
, fo
, rc
, pvt0
, pvt1
);
3878 static char *rtp_do_debug_ip(struct ast_cli_args
*a
)
3881 struct ast_hostent ahp
;
3886 p
= strstr(arg
, ":");
3892 hp
= ast_gethostbyname(arg
, &ahp
);
3894 ast_cli(a
->fd
, "Lookup failed for '%s'\n", arg
);
3897 rtpdebugaddr
.sin_family
= AF_INET
;
3898 memcpy(&rtpdebugaddr
.sin_addr
, hp
->h_addr
, sizeof(rtpdebugaddr
.sin_addr
));
3899 rtpdebugaddr
.sin_port
= htons(port
);
3901 ast_cli(a
->fd
, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr
.sin_addr
));
3903 ast_cli(a
->fd
, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr
.sin_addr
), port
);
3908 static char *rtcp_do_debug_ip(struct ast_cli_args
*a
)
3911 struct ast_hostent ahp
;
3916 p
= strstr(arg
, ":");
3922 hp
= ast_gethostbyname(arg
, &ahp
);
3924 ast_cli(a
->fd
, "Lookup failed for '%s'\n", arg
);
3927 rtcpdebugaddr
.sin_family
= AF_INET
;
3928 memcpy(&rtcpdebugaddr
.sin_addr
, hp
->h_addr
, sizeof(rtcpdebugaddr
.sin_addr
));
3929 rtcpdebugaddr
.sin_port
= htons(port
);
3931 ast_cli(a
->fd
, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr
.sin_addr
));
3933 ast_cli(a
->fd
, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr
.sin_addr
), port
);
3938 static char *handle_cli_rtp_debug_deprecated(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
3942 e
->command
= "rtp debug [off|ip]";
3944 "Usage: rtp debug [off]|[ip host[:port]]\n"
3945 " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
3946 " specified, limit the dumped packets to those to and from\n"
3947 " the specified 'host' with optional port.\n";
3953 if (a
->argc
< 2 || a
->argc
> 4)
3954 return CLI_SHOWUSAGE
;
3957 memset(&rtpdebugaddr
, 0, sizeof(rtpdebugaddr
));
3958 ast_cli(a
->fd
, "RTP Debugging Enabled\n");
3959 } else if (a
->argc
== 3) {
3960 if (strncasecmp(a
->argv
[2], "off", 3))
3961 return CLI_SHOWUSAGE
;
3963 ast_cli(a
->fd
, "RTP Debugging Disabled\n");
3965 if (strncasecmp(a
->argv
[2], "ip", 2))
3966 return CLI_SHOWUSAGE
;
3967 return rtp_do_debug_ip(a
);
3973 static char *handle_cli_rtp_set_debug(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
3977 e
->command
= "rtp set debug {on|off|ip}";
3979 "Usage: rtp set debug {on|off|ip host[:port]}\n"
3980 " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
3981 " specified, limit the dumped packets to those to and from\n"
3982 " the specified 'host' with optional port.\n";
3988 if (a
->argc
== e
->args
) { /* set on or off */
3989 if (!strncasecmp(a
->argv
[e
->args
-1], "on", 2)) {
3991 memset(&rtpdebugaddr
, 0, sizeof(rtpdebugaddr
));
3992 ast_cli(a
->fd
, "RTP Debugging Enabled\n");
3994 } else if (!strncasecmp(a
->argv
[e
->args
-1], "off", 3)) {
3996 ast_cli(a
->fd
, "RTP Debugging Disabled\n");
3999 } else if (a
->argc
== e
->args
+1) { /* ip */
4000 return rtp_do_debug_ip(a
);
4003 return CLI_SHOWUSAGE
; /* default, failure */
4006 static char *handle_cli_rtcp_debug_deprecated(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4010 e
->command
= "rtcp debug [off|ip]";
4012 "Usage: rtcp debug [off]|[ip host[:port]]\n"
4013 " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
4014 " specified, limit the dumped packets to those to and from\n"
4015 " the specified 'host' with optional port.\n";
4021 if (a
->argc
< 2 || a
->argc
> 4)
4022 return CLI_SHOWUSAGE
;
4025 memset(&rtcpdebugaddr
, 0, sizeof(rtcpdebugaddr
));
4026 ast_cli(a
->fd
, "RTCP Debugging Enabled\n");
4027 } else if (a
->argc
== 3) {
4028 if (strncasecmp(a
->argv
[2], "off", 3))
4029 return CLI_SHOWUSAGE
;
4031 ast_cli(a
->fd
, "RTCP Debugging Disabled\n");
4033 if (strncasecmp(a
->argv
[2], "ip", 2))
4034 return CLI_SHOWUSAGE
;
4035 return rtcp_do_debug_ip(a
);
4041 static char *handle_cli_rtcp_set_debug(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4045 e
->command
= "rtcp set debug {on|off|ip}";
4047 "Usage: rtcp set debug {on|off|ip host[:port]}\n"
4048 " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
4049 " specified, limit the dumped packets to those to and from\n"
4050 " the specified 'host' with optional port.\n";
4056 if (a
->argc
== e
->args
) { /* set on or off */
4057 if (!strncasecmp(a
->argv
[e
->args
-1], "on", 2)) {
4059 memset(&rtcpdebugaddr
, 0, sizeof(rtcpdebugaddr
));
4060 ast_cli(a
->fd
, "RTCP Debugging Enabled\n");
4062 } else if (!strncasecmp(a
->argv
[e
->args
-1], "off", 3)) {
4064 ast_cli(a
->fd
, "RTCP Debugging Disabled\n");
4067 } else if (a
->argc
== e
->args
+1) { /* ip */
4068 return rtcp_do_debug_ip(a
);
4071 return CLI_SHOWUSAGE
; /* default, failure */
4074 static char *handle_cli_rtcp_stats_deprecated(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4078 e
->command
= "rtcp stats [off]";
4080 "Usage: rtcp stats [off]\n"
4081 " Enable/Disable dumping of RTCP stats.\n";
4087 if (a
->argc
< 2 || a
->argc
> 3)
4088 return CLI_SHOWUSAGE
;
4089 if (a
->argc
== 3 && strncasecmp(a
->argv
[2], "off", 3))
4090 return CLI_SHOWUSAGE
;
4092 rtcpstats
= (a
->argc
== 3) ? 0 : 1;
4093 ast_cli(a
->fd
, "RTCP Stats %s\n", rtcpstats
? "Enabled" : "Disabled");
4097 static char *handle_cli_rtcp_set_stats(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4101 e
->command
= "rtcp set stats {on|off}";
4103 "Usage: rtcp set stats {on|off}\n"
4104 " Enable/Disable dumping of RTCP stats.\n";
4110 if (a
->argc
!= e
->args
)
4111 return CLI_SHOWUSAGE
;
4113 if (!strncasecmp(a
->argv
[e
->args
-1], "on", 2))
4115 else if (!strncasecmp(a
->argv
[e
->args
-1], "off", 3))
4118 return CLI_SHOWUSAGE
;
4120 ast_cli(a
->fd
, "RTCP Stats %s\n", rtcpstats
? "Enabled" : "Disabled");
4124 static char *handle_cli_stun_debug_deprecated(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4128 e
->command
= "stun debug [off]";
4130 "Usage: stun debug [off]\n"
4131 " Enable/Disable STUN (Simple Traversal of UDP through NATs)\n"
4138 if (a
->argc
< 2 || a
->argc
> 3)
4139 return CLI_SHOWUSAGE
;
4140 if (a
->argc
== 3 && strncasecmp(a
->argv
[2], "off", 3))
4141 return CLI_SHOWUSAGE
;
4143 stundebug
= (a
->argc
== 3) ? 0 : 1;
4144 ast_cli(a
->fd
, "STUN Debugging %s\n", stundebug
? "Enabled" : "Disabled");
4148 static char *handle_cli_stun_set_debug(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4152 e
->command
= "stun set debug {on|off}";
4154 "Usage: stun set debug {on|off}\n"
4155 " Enable/Disable STUN (Simple Traversal of UDP through NATs)\n"
4162 if (a
->argc
!= e
->args
)
4163 return CLI_SHOWUSAGE
;
4165 if (!strncasecmp(a
->argv
[e
->args
-1], "on", 2))
4167 else if (!strncasecmp(a
->argv
[e
->args
-1], "off", 3))
4170 return CLI_SHOWUSAGE
;
4172 ast_cli(a
->fd
, "STUN Debugging %s\n", stundebug
? "Enabled" : "Disabled");
4176 static struct ast_cli_entry cli_rtp_debug_deprecated
= AST_CLI_DEFINE(handle_cli_rtp_debug_deprecated
, "Enable/Disable RTP debugging");
4177 static struct ast_cli_entry cli_rtcp_debug_deprecated
= AST_CLI_DEFINE(handle_cli_rtcp_debug_deprecated
, "Enable/Disable RTCP debugging");
4178 static struct ast_cli_entry cli_rtcp_stats_deprecated
= AST_CLI_DEFINE(handle_cli_rtcp_stats_deprecated
, "Enable/Disable RTCP stats");
4179 static struct ast_cli_entry cli_stun_debug_deprecated
= AST_CLI_DEFINE(handle_cli_stun_debug_deprecated
, "Enable/Disable STUN debugging");
4181 static struct ast_cli_entry cli_rtp
[] = {
4182 AST_CLI_DEFINE(handle_cli_rtp_set_debug
, "Enable/Disable RTP debugging", .deprecate_cmd
= &cli_rtp_debug_deprecated
),
4183 AST_CLI_DEFINE(handle_cli_rtcp_set_debug
, "Enable/Disable RTCP debugging", .deprecate_cmd
= &cli_rtcp_debug_deprecated
),
4184 AST_CLI_DEFINE(handle_cli_rtcp_set_stats
, "Enable/Disable RTCP stats", .deprecate_cmd
= &cli_rtcp_stats_deprecated
),
4185 AST_CLI_DEFINE(handle_cli_stun_set_debug
, "Enable/Disable STUN debugging", .deprecate_cmd
= &cli_stun_debug_deprecated
),
4188 static int __ast_rtp_reload(int reload
)
4190 struct ast_config
*cfg
;
4192 struct ast_flags config_flags
= { reload
? CONFIG_FLAG_FILEUNCHANGED
: 0 };
4194 if ((cfg
= ast_config_load2("rtp.conf", "rtp", config_flags
)) == CONFIG_STATUS_FILEUNCHANGED
)
4199 dtmftimeout
= DEFAULT_DTMF_TIMEOUT
;
4200 strictrtp
= STRICT_RTP_OPEN
;
4202 if ((s
= ast_variable_retrieve(cfg
, "general", "rtpstart"))) {
4204 if (rtpstart
< 1024)
4206 if (rtpstart
> 65535)
4209 if ((s
= ast_variable_retrieve(cfg
, "general", "rtpend"))) {
4216 if ((s
= ast_variable_retrieve(cfg
, "general", "rtcpinterval"))) {
4217 rtcpinterval
= atoi(s
);
4218 if (rtcpinterval
== 0)
4219 rtcpinterval
= 0; /* Just so we're clear... it's zero */
4220 if (rtcpinterval
< RTCP_MIN_INTERVALMS
)
4221 rtcpinterval
= RTCP_MIN_INTERVALMS
; /* This catches negative numbers too */
4222 if (rtcpinterval
> RTCP_MAX_INTERVALMS
)
4223 rtcpinterval
= RTCP_MAX_INTERVALMS
;
4225 if ((s
= ast_variable_retrieve(cfg
, "general", "rtpchecksums"))) {
4233 ast_log(LOG_WARNING
, "Disabling RTP checksums is not supported on this operating system!\n");
4236 if ((s
= ast_variable_retrieve(cfg
, "general", "dtmftimeout"))) {
4237 dtmftimeout
= atoi(s
);
4238 if ((dtmftimeout
< 0) || (dtmftimeout
> 20000)) {
4239 ast_log(LOG_WARNING
, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
4240 dtmftimeout
, DEFAULT_DTMF_TIMEOUT
);
4241 dtmftimeout
= DEFAULT_DTMF_TIMEOUT
;
4244 if ((s
= ast_variable_retrieve(cfg
, "general", "strictrtp"))) {
4245 strictrtp
= ast_true(s
);
4247 ast_config_destroy(cfg
);
4249 if (rtpstart
>= rtpend
) {
4250 ast_log(LOG_WARNING
, "Unreasonable values for RTP start/end port in rtp.conf\n");
4254 ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart
, rtpend
);
4258 int ast_rtp_reload(void)
4260 return __ast_rtp_reload(1);
4263 /*! \brief Initialize the RTP system in Asterisk */
4264 void ast_rtp_init(void)
4266 ast_cli_register_multiple(cli_rtp
, sizeof(cli_rtp
) / sizeof(struct ast_cli_entry
));
4267 __ast_rtp_reload(0);