Tue Aug 24 2010 19:41:32

Asterisk developer's documentation


rtp.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! 
00020  * \file 
00021  *
00022  * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
00023  *
00024  * \author Mark Spencer <markster@digium.com>
00025  * 
00026  * \note RTP is defined in RFC 3550.
00027  */
00028 
00029 #include "asterisk.h"
00030 
00031 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 274168 $")
00032 
00033 #include <sys/time.h>
00034 #include <signal.h>
00035 #include <fcntl.h>
00036 #include <math.h> 
00037 
00038 #include "asterisk/rtp.h"
00039 #include "asterisk/pbx.h"
00040 #include "asterisk/frame.h"
00041 #include "asterisk/channel.h"
00042 #include "asterisk/acl.h"
00043 #include "asterisk/config.h"
00044 #include "asterisk/lock.h"
00045 #include "asterisk/utils.h"
00046 #include "asterisk/netsock.h"
00047 #include "asterisk/cli.h"
00048 #include "asterisk/manager.h"
00049 #include "asterisk/unaligned.h"
00050 
00051 #define MAX_TIMESTAMP_SKEW 640
00052 
00053 #define RTP_SEQ_MOD     (1<<16)  /*!< A sequence number can't be more than 16 bits */
00054 #define RTCP_DEFAULT_INTERVALMS   5000 /*!< Default milli-seconds between RTCP reports we send */
00055 #define RTCP_MIN_INTERVALMS       500  /*!< Min milli-seconds between RTCP reports we send */
00056 #define RTCP_MAX_INTERVALMS       60000   /*!< Max milli-seconds between RTCP reports we send */
00057 
00058 #define RTCP_PT_FUR     192
00059 #define RTCP_PT_SR      200
00060 #define RTCP_PT_RR      201
00061 #define RTCP_PT_SDES    202
00062 #define RTCP_PT_BYE     203
00063 #define RTCP_PT_APP     204
00064 
00065 #define RTP_MTU      1200
00066 
00067 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
00068 
00069 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
00070 
00071 static int rtpstart = 5000;     /*!< First port for RTP sessions (set in rtp.conf) */
00072 static int rtpend = 31000;      /*!< Last port for RTP sessions (set in rtp.conf) */
00073 static int rtpdebug;       /*!< Are we debugging? */
00074 static int rtcpdebug;         /*!< Are we debugging RTCP? */
00075 static int rtcpstats;         /*!< Are we debugging RTCP? */
00076 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
00077 static int stundebug;         /*!< Are we debugging stun? */
00078 static struct sockaddr_in rtpdebugaddr;   /*!< Debug packets to/from this host */
00079 static struct sockaddr_in rtcpdebugaddr;  /*!< Debug RTCP packets to/from this host */
00080 #ifdef SO_NO_CHECK
00081 static int nochecksums;
00082 #endif
00083 static int strictrtp;
00084 
00085 enum strict_rtp_state {
00086    STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
00087    STRICT_RTP_LEARN,    /*! Accept next packet as source */
00088    STRICT_RTP_CLOSED,   /*! Drop all RTP packets not coming from source that was learned */
00089 };
00090 
00091 /* Uncomment this to enable more intense native bridging, but note: this is currently buggy */
00092 /* #define P2P_INTENSE */
00093 
00094 /*!
00095  * \brief Structure representing a RTP session.
00096  *
00097  * 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 [...]"
00098  *
00099  */
00100 
00101 /*! \brief RTP session description */
00102 struct ast_rtp {
00103    int s;
00104    struct ast_frame f;
00105    unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
00106    unsigned int ssrc;      /*!< Synchronization source, RFC 3550, page 10. */
00107    unsigned int themssrc;     /*!< Their SSRC */
00108    unsigned int rxssrc;
00109    unsigned int lastts;
00110    unsigned int lastrxts;
00111    unsigned int lastividtimestamp;
00112    unsigned int lastovidtimestamp;
00113    unsigned int lastitexttimestamp;
00114    unsigned int lastotexttimestamp;
00115    unsigned int lasteventseqn;
00116    int lastrxseqno;                /*!< Last received sequence number */
00117    unsigned short seedrxseqno;     /*!< What sequence number did they start with?*/
00118    unsigned int seedrxts;          /*!< What RTP timestamp did they start with? */
00119    unsigned int rxcount;           /*!< How many packets have we received? */
00120    unsigned int rxoctetcount;      /*!< How many octets have we received? should be rxcount *160*/
00121    unsigned int txcount;           /*!< How many packets have we sent? */
00122    unsigned int txoctetcount;      /*!< How many octets have we sent? (txcount*160)*/
00123    unsigned int cycles;            /*!< Shifted count of sequence number cycles */
00124    double rxjitter;                /*!< Interarrival jitter at the moment */
00125    double rxtransit;               /*!< Relative transit time for previous packet */
00126    int lasttxformat;
00127    int lastrxformat;
00128 
00129    int rtptimeout;         /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
00130    int rtpholdtimeout;     /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
00131    int rtpkeepalive;    /*!< Send RTP comfort noice packets for keepalive */
00132 
00133    /* DTMF Reception Variables */
00134    char resp;
00135    unsigned int lastevent;
00136    unsigned int dtmf_duration;     /*!< Total duration in samples since the digit start event */
00137    unsigned int dtmf_timeout;      /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
00138    unsigned int dtmfsamples;
00139    /* DTMF Transmission Variables */
00140    unsigned int lastdigitts;
00141    char sending_digit;  /*!< boolean - are we sending digits */
00142    char send_digit;  /*!< digit we are sending */
00143    int send_payload;
00144    int send_duration;
00145    int nat;
00146    unsigned int flags;
00147    struct sockaddr_in us;     /*!< Socket representation of the local endpoint. */
00148    struct sockaddr_in them;   /*!< Socket representation of the remote endpoint. */
00149    struct sockaddr_in altthem;   /*!< Alternate source of remote media */
00150    struct timeval rxcore;
00151    struct timeval txcore;
00152    double drxcore;                 /*!< The double representation of the first received packet */
00153    struct timeval lastrx;          /*!< timeval when we last received a packet */
00154    struct timeval dtmfmute;
00155    struct ast_smoother *smoother;
00156    int *ioid;
00157    unsigned short seqno;      /*!< Sequence number, RFC 3550, page 13. */
00158    unsigned short rxseqno;
00159    struct sched_context *sched;
00160    struct io_context *io;
00161    void *data;
00162    ast_rtp_callback callback;
00163 #ifdef P2P_INTENSE
00164    ast_mutex_t bridge_lock;
00165 #endif
00166    struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
00167    int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
00168    int rtp_lookup_code_cache_code;
00169    int rtp_lookup_code_cache_result;
00170    struct ast_rtcp *rtcp;
00171    struct ast_codec_pref pref;
00172    struct ast_rtp *bridged;        /*!< Who we are Packet bridged to */
00173 
00174    enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
00175    struct sockaddr_in strict_rtp_address;  /*!< Remote address information for strict RTP purposes */
00176 
00177    int set_marker_bit:1;           /*!< Whether to set the marker bit or not */
00178    struct rtp_red *red;
00179 };
00180 
00181 static struct ast_frame *red_t140_to_red(struct rtp_red *red);
00182 static int red_write(const void *data);
00183  
00184 struct rtp_red {
00185    struct ast_frame t140;  /*!< Primary data  */
00186    struct ast_frame t140red;   /*!< Redundant t140*/
00187    unsigned char pt[RED_MAX_GENERATION];  /*!< Payload types for redundancy data */
00188    unsigned char ts[RED_MAX_GENERATION]; /*!< Time stamps */
00189    unsigned char len[RED_MAX_GENERATION]; /*!< length of each generation */
00190    int num_gen; /*!< Number of generations */
00191    int schedid; /*!< Timer id */
00192    int ti; /*!< How long to buffer data before send */
00193    unsigned char t140red_data[64000];  
00194    unsigned char buf_data[64000]; /*!< buffered primary data */
00195    int hdrlen; 
00196    long int prev_ts;
00197 };
00198 
00199 AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
00200 
00201 /* Forward declarations */
00202 static int ast_rtcp_write(const void *data);
00203 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
00204 static int ast_rtcp_write_sr(const void *data);
00205 static int ast_rtcp_write_rr(const void *data);
00206 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
00207 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
00208 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
00209 
00210 #define FLAG_3389_WARNING     (1 << 0)
00211 #define FLAG_NAT_ACTIVE       (3 << 1)
00212 #define FLAG_NAT_INACTIVE     (0 << 1)
00213 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
00214 #define FLAG_HAS_DTMF         (1 << 3)
00215 #define FLAG_P2P_SENT_MARK              (1 << 4)
00216 #define FLAG_P2P_NEED_DTMF              (1 << 5)
00217 #define FLAG_CALLBACK_MODE              (1 << 6)
00218 #define FLAG_DTMF_COMPENSATE            (1 << 7)
00219 #define FLAG_HAS_STUN                   (1 << 8)
00220 
00221 /*!
00222  * \brief Structure defining an RTCP session.
00223  * 
00224  * The concept "RTCP session" is not defined in RFC 3550, but since 
00225  * this structure is analogous to ast_rtp, which tracks a RTP session, 
00226  * it is logical to think of this as a RTCP session.
00227  *
00228  * RTCP packet is defined on page 9 of RFC 3550.
00229  * 
00230  */
00231 struct ast_rtcp {
00232    int rtcp_info;
00233    int s;            /*!< Socket */
00234    struct sockaddr_in us;     /*!< Socket representation of the local endpoint. */
00235    struct sockaddr_in them;   /*!< Socket representation of the remote endpoint. */
00236    struct sockaddr_in altthem;   /*!< Alternate source for RTCP */
00237    unsigned int soc;    /*!< What they told us */
00238    unsigned int spc;    /*!< What they told us */
00239    unsigned int themrxlsr;    /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
00240    struct timeval rxlsr;      /*!< Time when we got their last SR */
00241    struct timeval txlsr;      /*!< Time when we sent or last SR*/
00242    unsigned int expected_prior;  /*!< no. packets in previous interval */
00243    unsigned int received_prior;  /*!< no. packets received in previous interval */
00244    int schedid;         /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
00245    unsigned int rr_count;     /*!< number of RRs we've sent, not including report blocks in SR's */
00246    unsigned int sr_count;     /*!< number of SRs we've sent */
00247    unsigned int lastsrtxcount;     /*!< Transmit packet count when last SR sent */
00248    double accumulated_transit;   /*!< accumulated a-dlsr-lsr */
00249    double rtt;       /*!< Last reported rtt */
00250    unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
00251    unsigned int reported_lost;   /*!< Reported lost packets in their RR */
00252    char quality[AST_MAX_USER_FIELD];
00253    char quality_jitter[AST_MAX_USER_FIELD];
00254    char quality_loss[AST_MAX_USER_FIELD];
00255    char quality_rtt[AST_MAX_USER_FIELD];
00256 
00257    double reported_maxjitter;
00258    double reported_minjitter;
00259    double reported_normdev_jitter;
00260    double reported_stdev_jitter;
00261    unsigned int reported_jitter_count;
00262 
00263    double reported_maxlost;
00264    double reported_minlost;
00265    double reported_normdev_lost;
00266    double reported_stdev_lost;
00267 
00268    double rxlost;
00269    double maxrxlost;
00270    double minrxlost;
00271    double normdev_rxlost;
00272    double stdev_rxlost;
00273    unsigned int rxlost_count;
00274 
00275    double maxrxjitter;
00276    double minrxjitter;
00277    double normdev_rxjitter;
00278    double stdev_rxjitter;
00279    unsigned int rxjitter_count;
00280    double maxrtt;
00281    double minrtt;
00282    double normdevrtt;
00283    double stdevrtt;
00284    unsigned int rtt_count;
00285    int sendfur;
00286 };
00287 
00288 /*!
00289  * \brief STUN support code
00290  *
00291  * This code provides some support for doing STUN transactions.
00292  * Eventually it should be moved elsewhere as other protocols
00293  * than RTP can benefit from it - e.g. SIP.
00294  * STUN is described in RFC3489 and it is based on the exchange
00295  * of UDP packets between a client and one or more servers to
00296  * determine the externally visible address (and port) of the client
00297  * once it has gone through the NAT boxes that connect it to the
00298  * outside.
00299  * The simplest request packet is just the header defined in
00300  * struct stun_header, and from the response we may just look at
00301  * one attribute, STUN_MAPPED_ADDRESS, that we find in the response.
00302  * By doing more transactions with different server addresses we
00303  * may determine more about the behaviour of the NAT boxes, of
00304  * course - the details are in the RFC.
00305  *
00306  * All STUN packets start with a simple header made of a type,
00307  * length (excluding the header) and a 16-byte random transaction id.
00308  * Following the header we may have zero or more attributes, each
00309  * structured as a type, length and a value (whose format depends
00310  * on the type, but often contains addresses).
00311  * Of course all fields are in network format.
00312  */
00313 
00314 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
00315 
00316 struct stun_header {
00317    unsigned short msgtype;
00318    unsigned short msglen;
00319    stun_trans_id  id;
00320    unsigned char ies[0];
00321 } __attribute__((packed));
00322 
00323 struct stun_attr {
00324    unsigned short attr;
00325    unsigned short len;
00326    unsigned char value[0];
00327 } __attribute__((packed));
00328 
00329 /*
00330  * The format normally used for addresses carried by STUN messages.
00331  */
00332 struct stun_addr {
00333    unsigned char unused;
00334    unsigned char family;
00335    unsigned short port;
00336    unsigned int addr;
00337 } __attribute__((packed));
00338 
00339 #define STUN_IGNORE     (0)
00340 #define STUN_ACCEPT     (1)
00341 
00342 /*! \brief STUN message types
00343  * 'BIND' refers to transactions used to determine the externally
00344  * visible addresses. 'SEC' refers to transactions used to establish
00345  * a session key for subsequent requests.
00346  * 'SEC' functionality is not supported here.
00347  */
00348  
00349 #define STUN_BINDREQ 0x0001
00350 #define STUN_BINDRESP   0x0101
00351 #define STUN_BINDERR 0x0111
00352 #define STUN_SECREQ  0x0002
00353 #define STUN_SECRESP 0x0102
00354 #define STUN_SECERR  0x0112
00355 
00356 /*! \brief Basic attribute types in stun messages.
00357  * Messages can also contain custom attributes (codes above 0x7fff)
00358  */
00359 #define STUN_MAPPED_ADDRESS   0x0001
00360 #define STUN_RESPONSE_ADDRESS 0x0002
00361 #define STUN_CHANGE_REQUEST   0x0003
00362 #define STUN_SOURCE_ADDRESS   0x0004
00363 #define STUN_CHANGED_ADDRESS  0x0005
00364 #define STUN_USERNAME      0x0006
00365 #define STUN_PASSWORD      0x0007
00366 #define STUN_MESSAGE_INTEGRITY   0x0008
00367 #define STUN_ERROR_CODE    0x0009
00368 #define STUN_UNKNOWN_ATTRIBUTES  0x000a
00369 #define STUN_REFLECTED_FROM   0x000b
00370 
00371 /*! \brief helper function to print message names */
00372 static const char *stun_msg2str(int msg)
00373 {
00374    switch (msg) {
00375    case STUN_BINDREQ:
00376       return "Binding Request";
00377    case STUN_BINDRESP:
00378       return "Binding Response";
00379    case STUN_BINDERR:
00380       return "Binding Error Response";
00381    case STUN_SECREQ:
00382       return "Shared Secret Request";
00383    case STUN_SECRESP:
00384       return "Shared Secret Response";
00385    case STUN_SECERR:
00386       return "Shared Secret Error Response";
00387    }
00388    return "Non-RFC3489 Message";
00389 }
00390 
00391 /*! \brief helper function to print attribute names */
00392 static const char *stun_attr2str(int msg)
00393 {
00394    switch (msg) {
00395    case STUN_MAPPED_ADDRESS:
00396       return "Mapped Address";
00397    case STUN_RESPONSE_ADDRESS:
00398       return "Response Address";
00399    case STUN_CHANGE_REQUEST:
00400       return "Change Request";
00401    case STUN_SOURCE_ADDRESS:
00402       return "Source Address";
00403    case STUN_CHANGED_ADDRESS:
00404       return "Changed Address";
00405    case STUN_USERNAME:
00406       return "Username";
00407    case STUN_PASSWORD:
00408       return "Password";
00409    case STUN_MESSAGE_INTEGRITY:
00410       return "Message Integrity";
00411    case STUN_ERROR_CODE:
00412       return "Error Code";
00413    case STUN_UNKNOWN_ATTRIBUTES:
00414       return "Unknown Attributes";
00415    case STUN_REFLECTED_FROM:
00416       return "Reflected From";
00417    }
00418    return "Non-RFC3489 Attribute";
00419 }
00420 
00421 /*! \brief here we store credentials extracted from a message */
00422 struct stun_state {
00423    const char *username;
00424    const char *password;
00425 };
00426 
00427 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
00428 {
00429    if (stundebug)
00430       ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
00431              stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
00432    switch (ntohs(attr->attr)) {
00433    case STUN_USERNAME:
00434       state->username = (const char *) (attr->value);
00435       break;
00436    case STUN_PASSWORD:
00437       state->password = (const char *) (attr->value);
00438       break;
00439    default:
00440       if (stundebug)
00441          ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n", 
00442                 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
00443    }
00444    return 0;
00445 }
00446 
00447 /*! \brief append a string to an STUN message */
00448 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
00449 {
00450    int size = sizeof(**attr) + strlen(s);
00451    if (*left > size) {
00452       (*attr)->attr = htons(attrval);
00453       (*attr)->len = htons(strlen(s));
00454       memcpy((*attr)->value, s, strlen(s));
00455       (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
00456       *len += size;
00457       *left -= size;
00458    }
00459 }
00460 
00461 /*! \brief append an address to an STUN message */
00462 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sock_in, int *len, int *left)
00463 {
00464    int size = sizeof(**attr) + 8;
00465    struct stun_addr *addr;
00466    if (*left > size) {
00467       (*attr)->attr = htons(attrval);
00468       (*attr)->len = htons(8);
00469       addr = (struct stun_addr *)((*attr)->value);
00470       addr->unused = 0;
00471       addr->family = 0x01;
00472       addr->port = sock_in->sin_port;
00473       addr->addr = sock_in->sin_addr.s_addr;
00474       (*attr) = (struct stun_attr *)((*attr)->value + 8);
00475       *len += size;
00476       *left -= size;
00477    }
00478 }
00479 
00480 /*! \brief wrapper to send an STUN message */
00481 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
00482 {
00483    return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
00484             (struct sockaddr *)dst, sizeof(*dst));
00485 }
00486 
00487 /*! \brief helper function to generate a random request id */
00488 static void stun_req_id(struct stun_header *req)
00489 {
00490    int x;
00491    for (x = 0; x < 4; x++)
00492       req->id.id[x] = ast_random();
00493 }
00494 
00495 size_t ast_rtp_alloc_size(void)
00496 {
00497    return sizeof(struct ast_rtp);
00498 }
00499 
00500 /*! \brief callback type to be invoked on stun responses. */
00501 typedef int (stun_cb_f)(struct stun_attr *attr, void *arg);
00502 
00503 /*! \brief handle an incoming STUN message.
00504  *
00505  * Do some basic sanity checks on packet size and content,
00506  * try to extract a bit of information, and possibly reply.
00507  * At the moment this only processes BIND requests, and returns
00508  * the externally visible address of the request.
00509  * If a callback is specified, invoke it with the attribute.
00510  */
00511 static int stun_handle_packet(int s, struct sockaddr_in *src,
00512    unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
00513 {
00514    struct stun_header *hdr = (struct stun_header *)data;
00515    struct stun_attr *attr;
00516    struct stun_state st;
00517    int ret = STUN_IGNORE;  
00518    int x;
00519 
00520    /* On entry, 'len' is the length of the udp payload. After the
00521     * initial checks it becomes the size of unprocessed options,
00522     * while 'data' is advanced accordingly.
00523     */
00524    if (len < sizeof(struct stun_header)) {
00525       ast_debug(1, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
00526       return -1;
00527    }
00528    len -= sizeof(struct stun_header);
00529    data += sizeof(struct stun_header);
00530    x = ntohs(hdr->msglen); /* len as advertised in the message */
00531    if (stundebug)
00532       ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), x);
00533    if (x > len) {
00534       ast_debug(1, "Scrambled STUN packet length (got %d, expecting %d)\n", x, (int)len);
00535    } else
00536       len = x;
00537    memset(&st, 0, sizeof(st));
00538    while (len) {
00539       if (len < sizeof(struct stun_attr)) {
00540          ast_debug(1, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
00541          break;
00542       }
00543       attr = (struct stun_attr *)data;
00544       /* compute total attribute length */
00545       x = ntohs(attr->len) + sizeof(struct stun_attr);
00546       if (x > len) {
00547          ast_debug(1, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x, (int)len);
00548          break;
00549       }
00550       if (stun_cb)
00551          stun_cb(attr, arg);
00552       if (stun_process_attr(&st, attr)) {
00553          ast_debug(1, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
00554          break;
00555       }
00556       /* Clear attribute id: in case previous entry was a string,
00557        * this will act as the terminator for the string.
00558        */
00559       attr->attr = 0;
00560       data += x;
00561       len -= x;
00562    }
00563    /* Null terminate any string.
00564     * XXX NOTE, we write past the size of the buffer passed by the
00565     * caller, so this is potentially dangerous. The only thing that
00566     * saves us is that usually we read the incoming message in a
00567     * much larger buffer in the struct ast_rtp
00568     */
00569    *data = '\0';
00570 
00571    /* Now prepare to generate a reply, which at the moment is done
00572     * only for properly formed (len == 0) STUN_BINDREQ messages.
00573     */
00574    if (len == 0) {
00575       unsigned char respdata[1024];
00576       struct stun_header *resp = (struct stun_header *)respdata;
00577       int resplen = 0;  /* len excluding header */
00578       int respleft = sizeof(respdata) - sizeof(struct stun_header);
00579 
00580       resp->id = hdr->id;
00581       resp->msgtype = 0;
00582       resp->msglen = 0;
00583       attr = (struct stun_attr *)resp->ies;
00584       switch (ntohs(hdr->msgtype)) {
00585       case STUN_BINDREQ:
00586          if (stundebug)
00587             ast_verbose("STUN Bind Request, username: %s\n", 
00588                    st.username ? st.username : "<none>");
00589          if (st.username)
00590             append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
00591          append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
00592          resp->msglen = htons(resplen);
00593          resp->msgtype = htons(STUN_BINDRESP);
00594          stun_send(s, src, resp);
00595          ret = STUN_ACCEPT;
00596          break;
00597       default:
00598          if (stundebug)
00599             ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
00600       }
00601    }
00602    return ret;
00603 }
00604 
00605 /*! \brief Extract the STUN_MAPPED_ADDRESS from the stun response.
00606  * This is used as a callback for stun_handle_response
00607  * when called from ast_stun_request.
00608  */
00609 static int stun_get_mapped(struct stun_attr *attr, void *arg)
00610 {
00611    struct stun_addr *addr = (struct stun_addr *)(attr + 1);
00612    struct sockaddr_in *sa = (struct sockaddr_in *)arg;
00613 
00614    if (ntohs(attr->attr) != STUN_MAPPED_ADDRESS || ntohs(attr->len) != 8)
00615       return 1;   /* not us. */
00616    sa->sin_port = addr->port;
00617    sa->sin_addr.s_addr = addr->addr;
00618    return 0;
00619 }
00620 
00621 /*! \brief Generic STUN request
00622  * Send a generic stun request to the server specified,
00623  * possibly waiting for a reply and filling the 'reply' field with
00624  * the externally visible address. Note that in this case the request
00625  * will be blocking.
00626  * (Note, the interface may change slightly in the future).
00627  *
00628  * \param s the socket used to send the request
00629  * \param dst the address of the STUN server
00630  * \param username if non null, add the username in the request
00631  * \param answer if non null, the function waits for a response and
00632  *    puts here the externally visible address.
00633  * \return 0 on success, other values on error.
00634  */
00635 int ast_stun_request(int s, struct sockaddr_in *dst,
00636    const char *username, struct sockaddr_in *answer)
00637 {
00638    struct stun_header *req;
00639    unsigned char reqdata[1024];
00640    int reqlen, reqleft;
00641    struct stun_attr *attr;
00642    int res = 0;
00643    int retry;
00644    
00645    req = (struct stun_header *)reqdata;
00646    stun_req_id(req);
00647    reqlen = 0;
00648    reqleft = sizeof(reqdata) - sizeof(struct stun_header);
00649    req->msgtype = 0;
00650    req->msglen = 0;
00651    attr = (struct stun_attr *)req->ies;
00652    if (username)
00653       append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
00654    req->msglen = htons(reqlen);
00655    req->msgtype = htons(STUN_BINDREQ);
00656    for (retry = 0; retry < 3; retry++) {  /* XXX make retries configurable */
00657       /* send request, possibly wait for reply */
00658       unsigned char reply_buf[1024];
00659       fd_set rfds;
00660       struct timeval to = { 3, 0 }; /* timeout, make it configurable */
00661       struct sockaddr_in src;
00662       socklen_t srclen;
00663 
00664       res = stun_send(s, dst, req);
00665       if (res < 0) {
00666          ast_log(LOG_WARNING, "ast_stun_request send #%d failed error %d, retry\n",
00667             retry, res);
00668          continue;
00669       }
00670       if (answer == NULL)
00671          break;
00672       FD_ZERO(&rfds);
00673       FD_SET(s, &rfds);
00674       res = ast_select(s + 1, &rfds, NULL, NULL, &to);
00675       if (res <= 0)  /* timeout or error */
00676          continue;
00677       memset(&src, '\0', sizeof(src));
00678       srclen = sizeof(src);
00679       /* XXX pass -1 in the size, because stun_handle_packet might
00680        * write past the end of the buffer.
00681        */
00682       res = recvfrom(s, reply_buf, sizeof(reply_buf) - 1,
00683          0, (struct sockaddr *)&src, &srclen);
00684       if (res < 0) {
00685          ast_log(LOG_WARNING, "ast_stun_request recvfrom #%d failed error %d, retry\n",
00686             retry, res);
00687          continue;
00688       }
00689       memset(answer, '\0', sizeof(struct sockaddr_in));
00690       stun_handle_packet(s, &src, reply_buf, res,
00691          stun_get_mapped, answer);
00692       res = 0; /* signal regular exit */
00693       break;
00694    }
00695    return res;
00696 }
00697 
00698 /*! \brief send a STUN BIND request to the given destination.
00699  * Optionally, add a username if specified.
00700  */
00701 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
00702 {
00703    ast_stun_request(rtp->s, suggestion, username, NULL);
00704 }
00705 
00706 /*! \brief List of current sessions */
00707 static AST_RWLIST_HEAD_STATIC(protos, ast_rtp_protocol);
00708 
00709 static void timeval2ntp(struct timeval when, unsigned int *msw, unsigned int *lsw)
00710 {
00711    unsigned int sec, usec, frac;
00712    sec = when.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
00713    usec = when.tv_usec;
00714    frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
00715    *msw = sec;
00716    *lsw = frac;
00717 }
00718 
00719 int ast_rtp_fd(struct ast_rtp *rtp)
00720 {
00721    return rtp->s;
00722 }
00723 
00724 int ast_rtcp_fd(struct ast_rtp *rtp)
00725 {
00726    if (rtp->rtcp)
00727       return rtp->rtcp->s;
00728    return -1;
00729 }
00730 
00731 static int rtp_get_rate(int subclass)
00732 {
00733    return (subclass == AST_FORMAT_G722) ? 8000 : ast_format_rate(subclass);
00734 }
00735 
00736 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
00737 {
00738    unsigned int interval;
00739    /*! \todo XXX Do a more reasonable calculation on this one
00740     * Look in RFC 3550 Section A.7 for an example*/
00741    interval = rtcpinterval;
00742    return interval;
00743 }
00744 
00745 /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
00746 void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
00747 {
00748    rtp->rtptimeout = (-1) * rtp->rtptimeout;
00749    rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
00750 }
00751 
00752 /*! \brief Set rtp timeout */
00753 void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
00754 {
00755    rtp->rtptimeout = timeout;
00756 }
00757 
00758 /*! \brief Set rtp hold timeout */
00759 void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
00760 {
00761    rtp->rtpholdtimeout = timeout;
00762 }
00763 
00764 /*! \brief set RTP keepalive interval */
00765 void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
00766 {
00767    rtp->rtpkeepalive = period;
00768 }
00769 
00770 /*! \brief Get rtp timeout */
00771 int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
00772 {
00773    if (rtp->rtptimeout < 0)   /* We're not checking, but remembering the setting (during T.38 transmission) */
00774       return 0;
00775    return rtp->rtptimeout;
00776 }
00777 
00778 /*! \brief Get rtp hold timeout */
00779 int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
00780 {
00781    if (rtp->rtptimeout < 0)   /* We're not checking, but remembering the setting (during T.38 transmission) */
00782       return 0;
00783    return rtp->rtpholdtimeout;
00784 }
00785 
00786 /*! \brief Get RTP keepalive interval */
00787 int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
00788 {
00789    return rtp->rtpkeepalive;
00790 }
00791 
00792 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
00793 {
00794    rtp->data = data;
00795 }
00796 
00797 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
00798 {
00799    rtp->callback = callback;
00800 }
00801 
00802 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
00803 {
00804    rtp->nat = nat;
00805 }
00806 
00807 int ast_rtp_getnat(struct ast_rtp *rtp)
00808 {
00809    return ast_test_flag(rtp, FLAG_NAT_ACTIVE);
00810 }
00811 
00812 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
00813 {
00814    ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
00815 }
00816 
00817 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
00818 {
00819    ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
00820 }
00821 
00822 void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
00823 {
00824    ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
00825 }
00826 
00827 static void rtp_bridge_lock(struct ast_rtp *rtp)
00828 {
00829 #ifdef P2P_INTENSE
00830    ast_mutex_lock(&rtp->bridge_lock);
00831 #endif
00832    return;
00833 }
00834 
00835 static void rtp_bridge_unlock(struct ast_rtp *rtp)
00836 {
00837 #ifdef P2P_INTENSE
00838    ast_mutex_unlock(&rtp->bridge_lock);
00839 #endif
00840    return;
00841 }
00842 
00843 /*! \brief Calculate normal deviation */
00844 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
00845 {
00846    normdev = normdev * sample_count + sample;
00847    sample_count++;
00848 
00849    return normdev / sample_count;
00850 }
00851 
00852 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
00853 {
00854 /*
00855       for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
00856       return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
00857       we can compute the sigma^2 and that way we would have to do the sqrt only 1 time at the end and would save another pow 2 compute
00858       optimized formula
00859 */
00860 #define SQUARE(x) ((x) * (x))
00861 
00862    stddev = sample_count * stddev;
00863    sample_count++;
00864 
00865    return stddev + 
00866           ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) + 
00867           ( SQUARE(sample - normdev_curent) / sample_count );
00868 
00869 #undef SQUARE
00870 }
00871 
00872 static struct ast_frame *create_dtmf_frame(struct ast_rtp *rtp, enum ast_frame_type type)
00873 {
00874    if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
00875         (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
00876       ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
00877       rtp->resp = 0;
00878       rtp->dtmfsamples = 0;
00879       return &ast_null_frame;
00880    }
00881    ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
00882    if (rtp->resp == 'X') {
00883       rtp->f.frametype = AST_FRAME_CONTROL;
00884       rtp->f.subclass = AST_CONTROL_FLASH;
00885    } else {
00886       rtp->f.frametype = type;
00887       rtp->f.subclass = rtp->resp;
00888    }
00889    rtp->f.datalen = 0;
00890    rtp->f.samples = 0;
00891    rtp->f.mallocd = 0;
00892    rtp->f.src = "RTP";
00893    AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
00894    return &rtp->f;
00895    
00896 }
00897 
00898 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
00899 {
00900    if (rtpdebug == 0)
00901       return 0;
00902    if (rtpdebugaddr.sin_addr.s_addr) {
00903       if (((ntohs(rtpdebugaddr.sin_port) != 0)
00904            && (rtpdebugaddr.sin_port != addr->sin_port))
00905           || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
00906          return 0;
00907    }
00908    return 1;
00909 }
00910 
00911 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
00912 {
00913    if (rtcpdebug == 0)
00914       return 0;
00915    if (rtcpdebugaddr.sin_addr.s_addr) {
00916       if (((ntohs(rtcpdebugaddr.sin_port) != 0)
00917            && (rtcpdebugaddr.sin_port != addr->sin_port))
00918           || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
00919          return 0;
00920    }
00921    return 1;
00922 }
00923 
00924 
00925 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
00926 {
00927    unsigned int event;
00928    char resp = 0;
00929    struct ast_frame *f = NULL;
00930    unsigned char seq;
00931    unsigned int flags;
00932    unsigned int power;
00933 
00934    /* We should have at least 4 bytes in RTP data */
00935    if (len < 4)
00936       return f;
00937 
00938    /* The format of Cisco RTP DTMF packet looks like next:
00939       +0          - sequence number of DTMF RTP packet (begins from 1,
00940                     wrapped to 0)
00941       +1          - set of flags
00942       +1 (bit 0)     - flaps by different DTMF digits delimited by audio
00943                     or repeated digit without audio???
00944       +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
00945                     then falls to 0 at its end)
00946       +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
00947       Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
00948       by each new packet and thus provides some redudancy.
00949       
00950       Sample of Cisco RTP DTMF packet is (all data in hex):
00951          19 07 00 02 12 02 20 02
00952       showing end of DTMF digit '2'.
00953 
00954       The packets
00955          27 07 00 02 0A 02 20 02
00956          28 06 20 02 00 02 0A 02
00957       shows begin of new digit '2' with very short pause (20 ms) after
00958       previous digit '2'. Bit +1.0 flips at begin of new digit.
00959       
00960       Cisco RTP DTMF packets comes as replacement of audio RTP packets
00961       so its uses the same sequencing and timestamping rules as replaced
00962       audio packets. Repeat interval of DTMF packets is 20 ms and not rely
00963       on audio framing parameters. Marker bit isn't used within stream of
00964       DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
00965       are not sequential at borders between DTMF and audio streams,
00966    */
00967 
00968    seq = data[0];
00969    flags = data[1];
00970    power = data[2];
00971    event = data[3] & 0x1f;
00972 
00973    if (option_debug > 2 || rtpdebug)
00974       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);
00975    if (event < 10) {
00976       resp = '0' + event;
00977    } else if (event < 11) {
00978       resp = '*';
00979    } else if (event < 12) {
00980       resp = '#';
00981    } else if (event < 16) {
00982       resp = 'A' + (event - 12);
00983    } else if (event < 17) {
00984       resp = 'X';
00985    }
00986    if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
00987       rtp->resp = resp;
00988       /* Why we should care on DTMF compensation at reception? */
00989       if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
00990          f = create_dtmf_frame(rtp, AST_FRAME_DTMF_BEGIN);
00991          rtp->dtmfsamples = 0;
00992       }
00993    } else if ((rtp->resp == resp) && !power) {
00994       f = create_dtmf_frame(rtp, AST_FRAME_DTMF_END);
00995       f->samples = rtp->dtmfsamples * (rtp->lastrxformat ? (rtp_get_rate(rtp->lastrxformat) / 1000) : 8);
00996       rtp->resp = 0;
00997    } else if (rtp->resp == resp)
00998       rtp->dtmfsamples += 20 * (rtp->lastrxformat ? (rtp_get_rate(rtp->lastrxformat) / 1000) : 8);
00999    rtp->dtmf_timeout = dtmftimeout;
01000    return f;
01001 }
01002 
01003 /*! 
01004  * \brief Process RTP DTMF and events according to RFC 2833.
01005  * 
01006  * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
01007  * 
01008  * \param rtp
01009  * \param data
01010  * \param len
01011  * \param seqno
01012  * \param timestamp
01013  * \param frames
01014  * \returns
01015  */
01016 static void process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct frame_list *frames)
01017 {
01018    unsigned int event;
01019    unsigned int event_end;
01020    unsigned int samples;
01021    char resp = 0;
01022    struct ast_frame *f = NULL;
01023 
01024    /* Figure out event, event end, and samples */
01025    event = ntohl(*((unsigned int *)(data)));
01026    event >>= 24;
01027    event_end = ntohl(*((unsigned int *)(data)));
01028    event_end <<= 8;
01029    event_end >>= 24;
01030    samples = ntohl(*((unsigned int *)(data)));
01031    samples &= 0xFFFF;
01032 
01033    /* Print out debug if turned on */
01034    if (rtpdebug || option_debug > 2)
01035       ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
01036 
01037    /* Figure out what digit was pressed */
01038    if (event < 10) {
01039       resp = '0' + event;
01040    } else if (event < 11) {
01041       resp = '*';
01042    } else if (event < 12) {
01043       resp = '#';
01044    } else if (event < 16) {
01045       resp = 'A' + (event - 12);
01046    } else if (event < 17) {   /* Event 16: Hook flash */
01047       resp = 'X'; 
01048    } else {
01049       /* Not a supported event */
01050       ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
01051       return;
01052    }
01053 
01054    if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
01055       if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
01056          rtp->resp = resp;
01057          rtp->dtmf_timeout = 0;
01058          f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_END));
01059          f->len = 0;
01060          rtp->lastevent = timestamp;
01061          AST_LIST_INSERT_TAIL(frames, f, frame_list);
01062       }
01063    } else {
01064       /*  The duration parameter measures the complete
01065           duration of the event (from the beginning) - RFC2833.
01066           Account for the fact that duration is only 16 bits long
01067           (about 8 seconds at 8000 Hz) and can wrap is digit
01068           is hold for too long. */
01069       unsigned int new_duration = rtp->dtmf_duration;
01070       unsigned int last_duration = new_duration & 0xFFFF;
01071 
01072       if (last_duration > 64000 && samples < last_duration)
01073          new_duration += 0xFFFF + 1;
01074       new_duration = (new_duration & ~0xFFFF) | samples;
01075       /* The second portion of this check is to not mistakenly
01076        * stop accepting DTMF if the seqno rolls over beyond
01077        * 65535.
01078        */
01079       if (rtp->lastevent > seqno && rtp->lastevent - seqno < 50) {
01080          /* Out of order frame. Processing this can cause us to
01081           * improperly duplicate incoming DTMF, so just drop
01082           * this.
01083           */
01084          return;
01085       }
01086 
01087       if (event_end & 0x80) {
01088          /* End event */
01089          if ((rtp->lastevent != seqno) && rtp->resp) {
01090             rtp->dtmf_duration = new_duration;
01091             f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_END));
01092             f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
01093             rtp->resp = 0;
01094             rtp->dtmf_duration = rtp->dtmf_timeout = 0;
01095             AST_LIST_INSERT_TAIL(frames, f, frame_list);
01096          }
01097       } else {
01098          /* Begin/continuation */
01099 
01100          if (rtp->resp && rtp->resp != resp) {
01101             /* Another digit already began. End it */
01102             f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_END));
01103             f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
01104             rtp->resp = 0;
01105             rtp->dtmf_duration = rtp->dtmf_timeout = 0;
01106             AST_LIST_INSERT_TAIL(frames, f, frame_list);
01107          }
01108 
01109 
01110          if (rtp->resp) {
01111             /* Digit continues */
01112             rtp->dtmf_duration = new_duration;
01113          } else {
01114             /* New digit began */
01115             rtp->resp = resp;
01116             f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_BEGIN));
01117             rtp->dtmf_duration = samples;
01118             AST_LIST_INSERT_TAIL(frames, f, frame_list);
01119          }
01120 
01121          rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
01122       }
01123 
01124       rtp->lastevent = seqno;
01125    }
01126 
01127    rtp->dtmfsamples = samples;
01128 }
01129 
01130 /*!
01131  * \brief Process Comfort Noise RTP.
01132  * 
01133  * This is incomplete at the moment.
01134  * 
01135 */
01136 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
01137 {
01138    struct ast_frame *f = NULL;
01139    /* Convert comfort noise into audio with various codecs.  Unfortunately this doesn't
01140       totally help us out becuase we don't have an engine to keep it going and we are not
01141       guaranteed to have it every 20ms or anything */
01142    if (rtpdebug)
01143       ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
01144 
01145    if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
01146       ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
01147          ast_inet_ntoa(rtp->them.sin_addr));
01148       ast_set_flag(rtp, FLAG_3389_WARNING);
01149    }
01150    
01151    /* Must have at least one byte */
01152    if (!len)
01153       return NULL;
01154    if (len < 24) {
01155       rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
01156       rtp->f.datalen = len - 1;
01157       rtp->f.offset = AST_FRIENDLY_OFFSET;
01158       memcpy(rtp->f.data.ptr, data + 1, len - 1);
01159    } else {
01160       rtp->f.data.ptr = NULL;
01161       rtp->f.offset = 0;
01162       rtp->f.datalen = 0;
01163    }
01164    rtp->f.frametype = AST_FRAME_CNG;
01165    rtp->f.subclass = data[0] & 0x7f;
01166    rtp->f.samples = 0;
01167    rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
01168    f = &rtp->f;
01169    return f;
01170 }
01171 
01172 static int rtpread(int *id, int fd, short events, void *cbdata)
01173 {
01174    struct ast_rtp *rtp = cbdata;
01175    struct ast_frame *f;
01176    f = ast_rtp_read(rtp);
01177    if (f) {
01178       if (rtp->callback)
01179          rtp->callback(rtp, f, rtp->data);
01180    }
01181    return 1;
01182 }
01183 
01184 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
01185 {
01186    socklen_t len;
01187    int position, i, packetwords;
01188    int res;
01189    struct sockaddr_in sock_in;
01190    unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
01191    unsigned int *rtcpheader;
01192    int pt;
01193    struct timeval now;
01194    unsigned int length;
01195    int rc;
01196    double rttsec;
01197    uint64_t rtt = 0;
01198    unsigned int dlsr;
01199    unsigned int lsr;
01200    unsigned int msw;
01201    unsigned int lsw;
01202    unsigned int comp;
01203    struct ast_frame *f = &ast_null_frame;
01204    
01205    double reported_jitter;
01206    double reported_normdev_jitter_current;
01207    double normdevrtt_current;
01208    double reported_lost;
01209    double reported_normdev_lost_current;
01210 
01211    if (!rtp || !rtp->rtcp)
01212       return &ast_null_frame;
01213 
01214    len = sizeof(sock_in);
01215    
01216    res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
01217                0, (struct sockaddr *)&sock_in, &len);
01218    rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
01219    
01220    if (res < 0) {
01221       ast_assert(errno != EBADF);
01222       if (errno != EAGAIN) {
01223          ast_log(LOG_WARNING, "RTCP Read error: %s.  Hanging up.\n", strerror(errno));
01224          return NULL;
01225       }
01226       return &ast_null_frame;
01227    }
01228 
01229    packetwords = res / 4;
01230    
01231    if (rtp->nat) {
01232       /* Send to whoever sent to us */
01233       if (((rtp->rtcp->them.sin_addr.s_addr != sock_in.sin_addr.s_addr) ||
01234           (rtp->rtcp->them.sin_port != sock_in.sin_port)) && 
01235           ((rtp->rtcp->altthem.sin_addr.s_addr != sock_in.sin_addr.s_addr) || 
01236           (rtp->rtcp->altthem.sin_port != sock_in.sin_port))) {
01237          memcpy(&rtp->rtcp->them, &sock_in, sizeof(rtp->rtcp->them));
01238          if (option_debug || rtpdebug)
01239             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));
01240       }
01241    }
01242 
01243    ast_debug(1, "Got RTCP report of %d bytes\n", res);
01244 
01245    /* Process a compound packet */
01246    position = 0;
01247    while (position < packetwords) {
01248       i = position;
01249       length = ntohl(rtcpheader[i]);
01250       pt = (length & 0xff0000) >> 16;
01251       rc = (length & 0x1f000000) >> 24;
01252       length &= 0xffff;
01253  
01254       if ((i + length) > packetwords) {
01255          if (option_debug || rtpdebug)
01256             ast_log(LOG_DEBUG, "RTCP Read too short\n");
01257          return &ast_null_frame;
01258       }
01259       
01260       if (rtcp_debug_test_addr(&sock_in)) {
01261          ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port));
01262          ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
01263          ast_verbose("Reception reports: %d\n", rc);
01264          ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
01265       }
01266  
01267       i += 2; /* Advance past header and ssrc */
01268       
01269       switch (pt) {
01270       case RTCP_PT_SR:
01271          gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
01272          rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
01273          rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
01274          rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
01275  
01276          if (rtcp_debug_test_addr(&sock_in)) {
01277             ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
01278             ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
01279             ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
01280          }
01281          i += 5;
01282          if (rc < 1)
01283             break;
01284          /* Intentional fall through */
01285       case RTCP_PT_RR:
01286          /* Don't handle multiple reception reports (rc > 1) yet */
01287          /* Calculate RTT per RFC */
01288          gettimeofday(&now, NULL);
01289          timeval2ntp(now, &msw, &lsw);
01290          if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
01291             comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
01292             lsr = ntohl(rtcpheader[i + 4]);
01293             dlsr = ntohl(rtcpheader[i + 5]);
01294             rtt = comp - lsr - dlsr;
01295 
01296             /* Convert end to end delay to usec (keeping the calculation in 64bit space)
01297                sess->ee_delay = (eedelay * 1000) / 65536; */
01298             if (rtt < 4294) {
01299                 rtt = (rtt * 1000000) >> 16;
01300             } else {
01301                 rtt = (rtt * 1000) >> 16;
01302                 rtt *= 1000;
01303             }
01304             rtt = rtt / 1000.;
01305             rttsec = rtt / 1000.;
01306             rtp->rtcp->rtt = rttsec;
01307 
01308             if (comp - dlsr >= lsr) {
01309                rtp->rtcp->accumulated_transit += rttsec;
01310 
01311                if (rtp->rtcp->rtt_count == 0) 
01312                   rtp->rtcp->minrtt = rttsec;
01313 
01314                if (rtp->rtcp->maxrtt<rttsec)
01315                   rtp->rtcp->maxrtt = rttsec;
01316 
01317                if (rtp->rtcp->minrtt>rttsec)
01318                   rtp->rtcp->minrtt = rttsec;
01319 
01320                normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt, rttsec, rtp->rtcp->rtt_count);
01321 
01322                rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt, rttsec, rtp->rtcp->normdevrtt, normdevrtt_current, rtp->rtcp->rtt_count);
01323 
01324                rtp->rtcp->normdevrtt = normdevrtt_current;
01325 
01326                rtp->rtcp->rtt_count++;
01327             } else if (rtcp_debug_test_addr(&sock_in)) {
01328                ast_verbose("Internal RTCP NTP clock skew detected: "
01329                         "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
01330                         "diff=%d\n",
01331                         lsr, comp, dlsr, dlsr / 65536,
01332                         (dlsr % 65536) * 1000 / 65536,
01333                         dlsr - (comp - lsr));
01334             }
01335          }
01336 
01337          rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
01338          reported_jitter = (double) rtp->rtcp->reported_jitter;
01339 
01340          if (rtp->rtcp->reported_jitter_count == 0) 
01341             rtp->rtcp->reported_minjitter = reported_jitter;
01342 
01343          if (reported_jitter < rtp->rtcp->reported_minjitter) 
01344             rtp->rtcp->reported_minjitter = reported_jitter;
01345 
01346          if (reported_jitter > rtp->rtcp->reported_maxjitter) 
01347             rtp->rtcp->reported_maxjitter = reported_jitter;
01348 
01349          reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);
01350 
01351          rtp->rtcp->reported_stdev_jitter = stddev_compute(rtp->rtcp->reported_stdev_jitter, reported_jitter, rtp->rtcp->reported_normdev_jitter, reported_normdev_jitter_current, rtp->rtcp->reported_jitter_count);
01352 
01353          rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;
01354 
01355          rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
01356 
01357          reported_lost = (double) rtp->rtcp->reported_lost;
01358 
01359          /* using same counter as for jitter */
01360          if (rtp->rtcp->reported_jitter_count == 0)
01361             rtp->rtcp->reported_minlost = reported_lost;
01362 
01363          if (reported_lost < rtp->rtcp->reported_minlost)
01364             rtp->rtcp->reported_minlost = reported_lost;
01365 
01366          if (reported_lost > rtp->rtcp->reported_maxlost) 
01367             rtp->rtcp->reported_maxlost = reported_lost;
01368 
01369          reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);
01370 
01371          rtp->rtcp->reported_stdev_lost = stddev_compute(rtp->rtcp->reported_stdev_lost, reported_lost, rtp->rtcp->reported_normdev_lost, reported_normdev_lost_current, rtp->rtcp->reported_jitter_count);
01372 
01373          rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;
01374 
01375          rtp->rtcp->reported_jitter_count++;
01376 
01377          if (rtcp_debug_test_addr(&sock_in)) {
01378             ast_verbose("  Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
01379             ast_verbose("  Packets lost so far: %d\n", rtp->rtcp->reported_lost);
01380             ast_verbose("  Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
01381             ast_verbose("  Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
01382             ast_verbose("  Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
01383             ast_verbose("  Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
01384             ast_verbose("  DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
01385             if (rtt)
01386                ast_verbose("  RTT: %lu(sec)\n", (unsigned long) rtt);
01387          }
01388 
01389          if (rtt) {
01390             manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s:%d\r\n"
01391                             "PT: %d(%s)\r\n"
01392                             "ReceptionReports: %d\r\n"
01393                             "SenderSSRC: %u\r\n"
01394                             "FractionLost: %ld\r\n"
01395                             "PacketsLost: %d\r\n"
01396                             "HighestSequence: %ld\r\n"
01397                             "SequenceNumberCycles: %ld\r\n"
01398                             "IAJitter: %u\r\n"
01399                             "LastSR: %lu.%010lu\r\n"
01400                             "DLSR: %4.4f(sec)\r\n"
01401                             "RTT: %llu(sec)\r\n",
01402                             ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port),
01403                             pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
01404                             rc,
01405                             rtcpheader[i + 1],
01406                             (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
01407                             rtp->rtcp->reported_lost,
01408                             (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
01409                             (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
01410                             rtp->rtcp->reported_jitter,
01411                             (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
01412                             ntohl(rtcpheader[i + 5])/65536.0,
01413                             (unsigned long long)rtt);
01414          } else {
01415             manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s:%d\r\n"
01416                             "PT: %d(%s)\r\n"
01417                             "ReceptionReports: %d\r\n"
01418                             "SenderSSRC: %u\r\n"
01419                             "FractionLost: %ld\r\n"
01420                             "PacketsLost: %d\r\n"
01421                             "HighestSequence: %ld\r\n"
01422                             "SequenceNumberCycles: %ld\r\n"
01423                             "IAJitter: %u\r\n"
01424                             "LastSR: %lu.%010lu\r\n"
01425                             "DLSR: %4.4f(sec)\r\n",
01426                             ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port),
01427                             pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
01428                             rc,
01429                             rtcpheader[i + 1],
01430                             (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
01431                             rtp->rtcp->reported_lost,
01432                             (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
01433                             (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
01434                             rtp->rtcp->reported_jitter,
01435                             (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
01436                             ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
01437                             ntohl(rtcpheader[i + 5])/65536.0);
01438          }
01439          break;
01440       case RTCP_PT_FUR:
01441          if (rtcp_debug_test_addr(&sock_in))
01442             ast_verbose("Received an RTCP Fast Update Request\n");
01443          rtp->f.frametype = AST_FRAME_CONTROL;
01444          rtp->f.subclass = AST_CONTROL_VIDUPDATE;
01445          rtp->f.datalen = 0;
01446          rtp->f.samples = 0;
01447          rtp->f.mallocd = 0;
01448          rtp->f.src = "RTP";
01449          f = &rtp->f;
01450          break;
01451       case RTCP_PT_SDES:
01452          if (rtcp_debug_test_addr(&sock_in))
01453             ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
01454          break;
01455       case RTCP_PT_BYE:
01456          if (rtcp_debug_test_addr(&sock_in))
01457             ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
01458          break;
01459       default:
01460          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));
01461          break;
01462       }
01463       position += (length + 1);
01464    }
01465    rtp->rtcp->rtcp_info = 1;  
01466    return f;
01467 }
01468 
01469 static void calc_rxstamp(struct timeval *when, struct ast_rtp *rtp, unsigned int timestamp, int mark)
01470 {
01471    struct timeval now;
01472    struct timeval tmp;
01473    double transit;
01474    double current_time;
01475    double d;
01476    double dtv;
01477    double prog;
01478    double normdev_rxjitter_current;
01479    int rate = rtp_get_rate(rtp->f.subclass);
01480 
01481    if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
01482       gettimeofday(&rtp->rxcore, NULL);
01483       rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
01484       /* map timestamp to a real time */
01485       rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
01486       tmp = ast_samp2tv(timestamp, rate);
01487       rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
01488       /* Round to 0.1ms for nice, pretty timestamps */
01489       rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
01490    }
01491 
01492    gettimeofday(&now,NULL);
01493    /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
01494    tmp = ast_samp2tv(timestamp, rate);
01495    *when = ast_tvadd(rtp->rxcore, tmp);
01496 
01497    prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
01498    dtv = (double)rtp->drxcore + (double)(prog);
01499    current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
01500    transit = current_time - dtv;
01501    d = transit - rtp->rxtransit;
01502    rtp->rxtransit = transit;
01503    if (d<0)
01504       d=-d;
01505    rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
01506 
01507    if (rtp->rtcp) {
01508       if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
01509          rtp->rtcp->maxrxjitter = rtp->rxjitter;
01510       if (rtp->rtcp->rxjitter_count == 1) 
01511          rtp->rtcp->minrxjitter = rtp->rxjitter;
01512       if (rtp->rxjitter < rtp->rtcp->minrxjitter)
01513          rtp->rtcp->minrxjitter = rtp->rxjitter;
01514          
01515       normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
01516       rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
01517 
01518       rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
01519       rtp->rtcp->rxjitter_count++;
01520    }
01521 }
01522 
01523 /*! \brief Perform a Packet2Packet RTP write */
01524 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, struct ast_rtp *bridged, unsigned int *rtpheader, int len, int hdrlen)
01525 {
01526    int res = 0, payload = 0, bridged_payload = 0, mark;
01527    struct rtpPayloadType rtpPT;
01528    int reconstruct = ntohl(rtpheader[0]);
01529 
01530    /* Get fields from packet */
01531    payload = (reconstruct & 0x7f0000) >> 16;
01532    mark = (((reconstruct & 0x800000) >> 23) != 0);
01533 
01534    /* Check what the payload value should be */
01535    rtpPT = ast_rtp_lookup_pt(rtp, payload);
01536 
01537    /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
01538    if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
01539       return -1;
01540 
01541    /* Otherwise adjust bridged payload to match */
01542    bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
01543 
01544    /* 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 */
01545    if (!bridged->current_RTP_PT[bridged_payload].code)
01546       return -1;
01547 
01548 
01549    /* If the mark bit has not been sent yet... do it now */
01550    if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
01551       mark = 1;
01552       ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
01553    }
01554 
01555    /* Reconstruct part of the packet */
01556    reconstruct &= 0xFF80FFFF;
01557    reconstruct |= (bridged_payload << 16);
01558    reconstruct |= (mark << 23);
01559    rtpheader[0] = htonl(reconstruct);
01560 
01561    /* Send the packet back out */
01562    res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
01563    if (res < 0) {
01564       if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
01565          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));
01566       } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
01567          if (option_debug || rtpdebug)
01568             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));
01569          ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
01570       }
01571       return 0;
01572    } else if (rtp_debug_test_addr(&bridged->them))
01573          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);
01574 
01575    return 0;
01576 }
01577 
01578 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
01579 {
01580    int res;
01581    struct sockaddr_in sock_in;
01582    socklen_t len;
01583    unsigned int seqno;
01584    int version;
01585    int payloadtype;
01586    int hdrlen = 12;
01587    int padding;
01588    int mark;
01589    int ext;
01590    int cc;
01591    unsigned int ssrc;
01592    unsigned int timestamp;
01593    unsigned int *rtpheader;
01594    struct rtpPayloadType rtpPT;
01595    struct ast_rtp *bridged = NULL;
01596    int prev_seqno;
01597    struct frame_list frames;
01598    
01599    /* If time is up, kill it */
01600    if (rtp->sending_digit)
01601       ast_rtp_senddigit_continuation(rtp);
01602 
01603    len = sizeof(sock_in);
01604    
01605    /* Cache where the header will go */
01606    res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
01607                0, (struct sockaddr *)&sock_in, &len);
01608 
01609    /* If strict RTP protection is enabled see if we need to learn this address or if the packet should be dropped */
01610    if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
01611       /* Copy over address that this packet was received on */
01612       memcpy(&rtp->strict_rtp_address, &sock_in, sizeof(rtp->strict_rtp_address));
01613       /* Now move over to actually protecting the RTP port */
01614       rtp->strict_rtp_state = STRICT_RTP_CLOSED;
01615       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));
01616    } else if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
01617       /* If the address we previously learned doesn't match the address this packet came in on simply drop it */
01618       if ((rtp->strict_rtp_address.sin_addr.s_addr != sock_in.sin_addr.s_addr) || (rtp->strict_rtp_address.sin_port != sock_in.sin_port)) {
01619          ast_debug(1, "Received RTP packet from %s:%d, dropping due to strict RTP protection. Expected it to be from %s:%d\n", ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port), ast_inet_ntoa(rtp->strict_rtp_address.sin_addr), ntohs(rtp->strict_rtp_address.sin_port));
01620          return &ast_null_frame;
01621       }
01622    }
01623 
01624    rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
01625    if (res < 0) {
01626       ast_assert(errno != EBADF);
01627       if (errno != EAGAIN) {
01628          ast_log(LOG_WARNING, "RTP Read error: %s.  Hanging up.\n", strerror(errno));
01629          return NULL;
01630       }
01631       return &ast_null_frame;
01632    }
01633    
01634    if (res < hdrlen) {
01635       ast_log(LOG_WARNING, "RTP Read too short\n");
01636       return &ast_null_frame;
01637    }
01638 
01639    /* Get fields */
01640    seqno = ntohl(rtpheader[0]);
01641 
01642    /* Check RTP version */
01643    version = (seqno & 0xC0000000) >> 30;
01644    if (!version) {
01645       /* If the two high bits are 0, this might be a
01646        * STUN message, so process it. stun_handle_packet()
01647        * answers to requests, and it returns STUN_ACCEPT
01648        * if the request is valid.
01649        */
01650       if ((stun_handle_packet(rtp->s, &sock_in, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == STUN_ACCEPT) &&
01651          (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
01652          memcpy(&rtp->them, &sock_in, sizeof(rtp->them));
01653       }
01654       return &ast_null_frame;
01655    }
01656 
01657 #if 0 /* Allow to receive RTP stream with closed transmission path */
01658    /* If we don't have the other side's address, then ignore this */
01659    if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
01660       return &ast_null_frame;
01661 #endif
01662 
01663    /* Send to whoever send to us if NAT is turned on */
01664    if (rtp->nat) {
01665       if (((rtp->them.sin_addr.s_addr != sock_in.sin_addr.s_addr) ||
01666           (rtp->them.sin_port != sock_in.sin_port)) && 
01667           ((rtp->altthem.sin_addr.s_addr != sock_in.sin_addr.s_addr) ||
01668           (rtp->altthem.sin_port != sock_in.sin_port))) {
01669          rtp->them = sock_in;
01670          if (rtp->rtcp) {
01671             int h = 0;
01672             memcpy(&rtp->rtcp->them, &sock_in, sizeof(rtp->rtcp->them));
01673             h = ntohs(rtp->them.sin_port);
01674             rtp->rtcp->them.sin_port = htons(h + 1);
01675          }
01676          rtp->rxseqno = 0;
01677          ast_set_flag(rtp, FLAG_NAT_ACTIVE);
01678          if (option_debug || rtpdebug)
01679             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));
01680       }
01681    }
01682 
01683    /* If we are bridged to another RTP stream, send direct */
01684    if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
01685       return &ast_null_frame;
01686 
01687    if (version != 2)
01688       return &ast_null_frame;
01689 
01690    payloadtype = (seqno & 0x7f0000) >> 16;
01691    padding = seqno & (1 << 29);
01692    mark = seqno & (1 << 23);
01693    ext = seqno & (1 << 28);
01694    cc = (seqno & 0xF000000) >> 24;
01695    seqno &= 0xffff;
01696    timestamp = ntohl(rtpheader[1]);
01697    ssrc = ntohl(rtpheader[2]);
01698    
01699    AST_LIST_HEAD_INIT_NOLOCK(&frames);
01700    /* Force a marker bit and change SSRC if the SSRC changes */
01701    if (rtp->rxssrc && rtp->rxssrc != ssrc) {
01702       struct ast_frame *f, srcupdate = {
01703          AST_FRAME_CONTROL,
01704          .subclass = AST_CONTROL_SRCCHANGE,
01705       };
01706 
01707       if (!mark) {
01708          if (option_debug || rtpdebug) {
01709             ast_debug(0, "Forcing Marker bit, because SSRC has changed\n");
01710          }
01711          mark = 1;
01712       }
01713       f = ast_frisolate(&srcupdate);
01714       AST_LIST_INSERT_TAIL(&frames, f, frame_list);
01715    }
01716 
01717    rtp->rxssrc = ssrc;
01718    
01719    if (padding) {
01720       /* Remove padding bytes */
01721       res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
01722    }
01723    
01724    if (cc) {
01725       /* CSRC fields present */
01726       hdrlen += cc*4;
01727    }
01728 
01729    if (ext) {
01730       /* RTP Extension present */
01731       hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
01732       hdrlen += 4;
01733       if (option_debug) {
01734          int profile;
01735          profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
01736          if (profile == 0x505a)
01737             ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
01738          else
01739             ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
01740       }
01741    }
01742 
01743    if (res < hdrlen) {
01744       ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
01745       return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
01746    }
01747 
01748    rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
01749 
01750    if (rtp->rxcount==1) {
01751       /* This is the first RTP packet successfully received from source */
01752       rtp->seedrxseqno = seqno;
01753    }
01754 
01755    /* Do not schedule RR if RTCP isn't run */
01756    if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
01757       /* Schedule transmission of Receiver Report */
01758       rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
01759    }
01760    if ((int)rtp->lastrxseqno - (int)seqno  > 100) /* if so it would indicate that the sender cycled; allow for misordering */
01761       rtp->cycles += RTP_SEQ_MOD;
01762    
01763    prev_seqno = rtp->lastrxseqno;
01764 
01765    rtp->lastrxseqno = seqno;
01766    
01767    if (!rtp->themssrc)
01768       rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
01769    
01770    if (rtp_debug_test_addr(&sock_in))
01771       ast_verbose("Got  RTP packet from    %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
01772          ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
01773 
01774    rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
01775    if (!rtpPT.isAstFormat) {
01776       struct ast_frame *f = NULL;
01777 
01778       /* This is special in-band data that's not one of our codecs */
01779       if (rtpPT.code == AST_RTP_DTMF) {
01780          /* It's special -- rfc2833 process it */
01781          if (rtp_debug_test_addr(&sock_in)) {
01782             unsigned char *data;
01783             unsigned int event;
01784             unsigned int event_end;
01785             unsigned int duration;
01786             data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
01787             event = ntohl(*((unsigned int *)(data)));
01788             event >>= 24;
01789             event_end = ntohl(*((unsigned int *)(data)));
01790             event_end <<= 8;
01791             event_end >>= 24;
01792             duration = ntohl(*((unsigned int *)(data)));
01793             duration &= 0xFFFF;
01794             ast_verbose("Got  RTP RFC2833 from   %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n", ast_inet_ntoa(sock_in.sin_addr), ntohs(sock_in.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
01795          }
01796          /* process_rfc2833 may need to return multiple frames. We do this
01797           * by passing the pointer to the frame list to it so that the method
01798           * can append frames to the list as needed
01799           */
01800          process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &frames);
01801       } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
01802          /* It's really special -- process it the Cisco way */
01803          if (rtp->lastevent <= seqno || (rtp->lastevent >= 65530 && seqno <= 6)) {
01804             f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
01805             rtp->lastevent = seqno;
01806          }
01807       } else if (rtpPT.code == AST_RTP_CN) {
01808          /* Comfort Noise */
01809          f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
01810       } else {
01811          ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
01812       }
01813       if (f) {
01814          AST_LIST_INSERT_TAIL(&frames, f, frame_list);
01815       }
01816       /* Even if no frame was returned by one of the above methods,
01817        * we may have a frame to return in our frame list
01818        */
01819       if (!AST_LIST_EMPTY(&frames)) {
01820          return AST_LIST_FIRST(&frames);
01821       }
01822       return &ast_null_frame;
01823    }
01824    rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
01825    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;
01826 
01827    rtp->rxseqno = seqno;
01828 
01829    if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
01830       rtp->dtmf_timeout = 0;
01831 
01832       if (rtp->resp) {
01833          struct ast_frame *f;
01834          f = create_dtmf_frame(rtp, AST_FRAME_DTMF_END);
01835          f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
01836          rtp->resp = 0;
01837          rtp->dtmf_timeout = rtp->dtmf_duration = 0;
01838          AST_LIST_INSERT_TAIL(&frames, f, frame_list);
01839          return AST_LIST_FIRST(&frames);
01840       }
01841    }
01842 
01843    /* Record received timestamp as last received now */
01844    rtp->lastrxts = timestamp;
01845 
01846    rtp->f.mallocd = 0;
01847    rtp->f.datalen = res - hdrlen;
01848    rtp->f.data.ptr = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
01849    rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
01850    rtp->f.seqno = seqno;
01851 
01852    if (rtp->f.subclass == AST_FORMAT_T140 && (int)seqno - (prev_seqno+1) > 0 && (int)seqno - (prev_seqno+1) < 10) {
01853         unsigned char *data = rtp->f.data.ptr;
01854         
01855         memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
01856         rtp->f.datalen +=3;
01857         *data++ = 0xEF;
01858         *data++ = 0xBF;
01859         *data = 0xBD;
01860    }
01861  
01862    if (rtp->f.subclass == AST_FORMAT_T140RED) {
01863       unsigned char *data = rtp->f.data.ptr;
01864       unsigned char *header_end;
01865       int num_generations;
01866       int header_length;
01867       int length;
01868       int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
01869       int x;
01870 
01871       rtp->f.subclass = AST_FORMAT_T140;
01872       header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
01873       if (header_end == NULL) {
01874          return &ast_null_frame;
01875       }
01876       header_end++;
01877       
01878       header_length = header_end - data;
01879       num_generations = header_length / 4;
01880       length = header_length;
01881 
01882       if (!diff) {
01883          for (x = 0; x < num_generations; x++)
01884             length += data[x * 4 + 3];
01885          
01886          if (!(rtp->f.datalen - length))
01887             return &ast_null_frame;
01888          
01889          rtp->f.data.ptr += length;
01890          rtp->f.datalen -= length;
01891       } else if (diff > num_generations && diff < 10) {
01892          length -= 3;
01893          rtp->f.data.ptr += length;
01894          rtp->f.datalen -= length;
01895          
01896          data = rtp->f.data.ptr;
01897          *data++ = 0xEF;
01898          *data++ = 0xBF;
01899          *data = 0xBD;
01900       } else   {
01901          for ( x = 0; x < num_generations - diff; x++) 
01902             length += data[x * 4 + 3];
01903          
01904          rtp->f.data.ptr += length;
01905          rtp->f.datalen -= length;
01906       }
01907    }
01908 
01909    if (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) {
01910       rtp->f.samples = ast_codec_get_samples(&rtp->f);
01911       if (rtp->f.subclass == AST_FORMAT_SLINEAR) 
01912          ast_frame_byteswap_be(&rtp->f);
01913       calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
01914       /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
01915       ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
01916       rtp->f.ts = timestamp / (rtp_get_rate(rtp->f.subclass) / 1000);
01917       rtp->f.len = rtp->f.samples / ((ast_format_rate(rtp->f.subclass) / 1000));
01918    } else if (rtp->f.subclass & AST_FORMAT_VIDEO_MASK) {
01919       /* Video -- samples is # of samples vs. 90000 */
01920       if (!rtp->lastividtimestamp)
01921          rtp->lastividtimestamp = timestamp;
01922       rtp->f.samples = timestamp - rtp->lastividtimestamp;
01923       rtp->lastividtimestamp = timestamp;
01924       rtp->f.delivery.tv_sec = 0;
01925       rtp->f.delivery.tv_usec = 0;
01926       /* Pass the RTP marker bit as bit 0 in the subclass field.
01927        * This is ok because subclass is actually a bitmask, and
01928        * the low bits represent audio formats, that are not
01929        * involved here since we deal with video.
01930        */
01931       if (mark)
01932          rtp->f.subclass |= 0x1;
01933    } else {
01934       /* TEXT -- samples is # of samples vs. 1000 */
01935       if (!rtp->lastitexttimestamp)
01936          rtp->lastitexttimestamp = timestamp;
01937       rtp->f.samples = timestamp - rtp->lastitexttimestamp;
01938       rtp->lastitexttimestamp = timestamp;
01939       rtp->f.delivery.tv_sec = 0;
01940       rtp->f.delivery.tv_usec = 0;
01941    }
01942    rtp->f.src = "RTP";
01943 
01944    AST_LIST_INSERT_TAIL(&frames, &rtp->f, frame_list);
01945    return AST_LIST_FIRST(&frames);
01946 }
01947 
01948 /* The following array defines the MIME Media type (and subtype) for each
01949    of our codecs, or RTP-specific data type. */
01950 static const struct mimeType {
01951    struct rtpPayloadType payloadType;
01952    char *type;
01953    char *subtype;
01954    unsigned int sample_rate;
01955 } mimeTypes[] = {
01956    {{1, AST_FORMAT_G723_1}, "audio", "G723", 8000},
01957    {{1, AST_FORMAT_GSM}, "audio", "GSM", 8000},
01958    {{1, AST_FORMAT_ULAW}, "audio", "PCMU", 8000},
01959    {{1, AST_FORMAT_ULAW}, "audio", "G711U", 8000},
01960    {{1, AST_FORMAT_ALAW}, "audio", "PCMA", 8000},
01961    {{1, AST_FORMAT_ALAW}, "audio", "G711A", 8000},
01962    {{1, AST_FORMAT_G726}, "audio", "G726-32", 8000},
01963    {{1, AST_FORMAT_ADPCM}, "audio", "DVI4", 8000},
01964    {{1, AST_FORMAT_SLINEAR}, "audio", "L16", 8000},
01965    {{1, AST_FORMAT_LPC10}, "audio", "LPC", 8000},
01966    {{1, AST_FORMAT_G729A}, "audio", "G729", 8000},
01967    {{1, AST_FORMAT_G729A}, "audio", "G729A", 8000},
01968    {{1, AST_FORMAT_G729A}, "audio", "G.729", 8000},
01969    {{1, AST_FORMAT_SPEEX}, "audio", "speex", 8000},
01970    {{1, AST_FORMAT_ILBC}, "audio", "iLBC", 8000},
01971    /* this is the sample rate listed in the RTP profile for the G.722
01972       codec, *NOT* the actual sample rate of the media stream
01973    */
01974    {{1, AST_FORMAT_G722}, "audio", "G722", 8000},
01975    {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32", 8000},
01976    {{0, AST_RTP_DTMF}, "audio", "telephone-event", 8000},
01977    {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event", 8000},
01978    {{0, AST_RTP_CN}, "audio", "CN", 8000},
01979    {{1, AST_FORMAT_JPEG}, "video", "JPEG", 90000},
01980    {{1, AST_FORMAT_PNG}, "video", "PNG", 90000},
01981    {{1, AST_FORMAT_H261}, "video", "H261", 90000},
01982    {{1, AST_FORMAT_H263}, "video", "H263", 90000},
01983    {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998", 90000},
01984    {{1, AST_FORMAT_H264}, "video", "H264", 90000},
01985    {{1, AST_FORMAT_MP4_VIDEO}, "video", "MP4V-ES", 90000},
01986    {{1, AST_FORMAT_T140RED}, "text", "RED", 1000},
01987    {{1, AST_FORMAT_T140}, "text", "T140", 1000},
01988    {{1, AST_FORMAT_SIREN7}, "audio", "G7221", 16000},
01989    {{1, AST_FORMAT_SIREN14}, "audio", "G7221", 32000},
01990 };
01991 
01992 /*! 
01993  * \brief Mapping between Asterisk codecs and rtp payload types
01994  *
01995  * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
01996  * also, our own choices for dynamic payload types.  This is our master
01997  * table for transmission 
01998  * 
01999  * See http://www.iana.org/assignments/rtp-parameters for a list of
02000  * assigned values
02001  */
02002 static const struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
02003    [0] = {1, AST_FORMAT_ULAW},
02004 #ifdef USE_DEPRECATED_G726
02005    [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
02006 #endif
02007    [3] = {1, AST_FORMAT_GSM},
02008    [4] = {1, AST_FORMAT_G723_1},
02009    [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
02010    [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
02011    [7] = {1, AST_FORMAT_LPC10},
02012    [8] = {1, AST_FORMAT_ALAW},
02013    [9] = {1, AST_FORMAT_G722},
02014    [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
02015    [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
02016    [13] = {0, AST_RTP_CN},
02017    [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
02018    [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
02019    [18] = {1, AST_FORMAT_G729A},
02020    [19] = {0, AST_RTP_CN},    /* Also used for CN */
02021    [26] = {1, AST_FORMAT_JPEG},
02022    [31] = {1, AST_FORMAT_H261},
02023    [34] = {1, AST_FORMAT_H263},
02024    [97] = {1, AST_FORMAT_ILBC},
02025    [98] = {1, AST_FORMAT_H263_PLUS},
02026    [99] = {1, AST_FORMAT_H264},
02027    [101] = {0, AST_RTP_DTMF},
02028    [102] = {1, AST_FORMAT_SIREN7},
02029    [103] = {1, AST_FORMAT_H263_PLUS},
02030    [104] = {1, AST_FORMAT_MP4_VIDEO},
02031    [105] = {1, AST_FORMAT_T140RED}, /* Real time text chat (with redundancy encoding) */
02032    [106] = {1, AST_FORMAT_T140}, /* Real time text chat */
02033    [110] = {1, AST_FORMAT_SPEEX},
02034    [111] = {1, AST_FORMAT_G726},
02035    [112] = {1, AST_FORMAT_G726_AAL2},
02036    [115] = {1, AST_FORMAT_SIREN14},
02037    [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
02038 };
02039 
02040 void ast_rtp_pt_clear(struct ast_rtp* rtp) 
02041 {
02042    int i;
02043 
02044    if (!rtp)
02045       return;
02046 
02047    rtp_bridge_lock(rtp);
02048 
02049    for (i = 0; i < MAX_RTP_PT; ++i) {
02050       rtp->current_RTP_PT[i].isAstFormat = 0;
02051       rtp->current_RTP_PT[i].code = 0;
02052    }
02053 
02054    rtp->rtp_lookup_code_cache_isAstFormat = 0;
02055    rtp->rtp_lookup_code_cache_code = 0;
02056    rtp->rtp_lookup_code_cache_result = 0;
02057 
02058    rtp_bridge_unlock(rtp);
02059 }
02060 
02061 void ast_rtp_pt_default(struct ast_rtp* rtp) 
02062 {
02063    int i;
02064 
02065    rtp_bridge_lock(rtp);
02066 
02067    /* Initialize to default payload types */
02068    for (i = 0; i < MAX_RTP_PT; ++i) {
02069       rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
02070       rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
02071    }
02072 
02073    rtp->rtp_lookup_code_cache_isAstFormat = 0;
02074    rtp->rtp_lookup_code_cache_code = 0;
02075    rtp->rtp_lookup_code_cache_result = 0;
02076 
02077    rtp_bridge_unlock(rtp);
02078 }
02079 
02080 void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
02081 {
02082    unsigned int i;
02083 
02084    rtp_bridge_lock(dest);
02085    rtp_bridge_lock(src);
02086 
02087    for (i = 0; i < MAX_RTP_PT; ++i) {
02088       dest->current_RTP_PT[i].isAstFormat = 
02089          src->current_RTP_PT[i].isAstFormat;
02090       dest->current_RTP_PT[i].code = 
02091          src->current_RTP_PT[i].code; 
02092    }
02093    dest->rtp_lookup_code_cache_isAstFormat = 0;
02094    dest->rtp_lookup_code_cache_code = 0;
02095    dest->rtp_lookup_code_cache_result = 0;
02096 
02097    rtp_bridge_unlock(src);
02098    rtp_bridge_unlock(dest);
02099 }
02100 
02101 /*! \brief Get channel driver interface structure */
02102 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
02103 {
02104    struct ast_rtp_protocol *cur = NULL;
02105 
02106    AST_RWLIST_RDLOCK(&protos);
02107    AST_RWLIST_TRAVERSE(&protos, cur, list) {
02108       if (cur->type == chan->tech->type)
02109          break;
02110    }
02111    AST_RWLIST_UNLOCK(&protos);
02112 
02113    return cur;
02114 }
02115 
02116 int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
02117 {
02118    struct ast_rtp *destp = NULL, *srcp = NULL;     /* Audio RTP Channels */
02119    struct ast_rtp *vdestp = NULL, *vsrcp = NULL;      /* Video RTP channels */
02120    struct ast_rtp *tdestp = NULL, *tsrcp = NULL;      /* Text RTP channels */
02121    struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
02122    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;
02123    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;
02124    int srccodec, destcodec, nat_active = 0;
02125 
02126    /* Lock channels */
02127    ast_channel_lock(c0);
02128    if (c1) {
02129       while (ast_channel_trylock(c1)) {
02130          ast_channel_unlock(c0);
02131          usleep(1);
02132          ast_channel_lock(c0);
02133       }
02134    }
02135 
02136    /* Find channel driver interfaces */
02137    destpr = get_proto(c0);
02138    if (c1)
02139       srcpr = get_proto(c1);
02140    if (!destpr) {
02141       ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c0->name);
02142       ast_channel_unlock(c0);
02143       if (c1)
02144          ast_channel_unlock(c1);
02145       return -1;
02146    }
02147    if (!srcpr) {
02148       ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
02149       ast_channel_unlock(c0);
02150       if (c1)
02151          ast_channel_unlock(c1);
02152       return -1;
02153    }
02154 
02155    /* Get audio, video  and text interface (if native bridge is possible) */
02156    audio_dest_res = destpr->get_rtp_info(c0, &destp);
02157    video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
02158    text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(c0, &tdestp) : AST_RTP_GET_FAILED;
02159    if (srcpr) {
02160       audio_src_res = srcpr->get_rtp_info(c1, &srcp);
02161       video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
02162       text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(c1, &tsrcp) : AST_RTP_GET_FAILED;
02163    }
02164 
02165    /* Check if bridge is still possible (In SIP directmedia=no stops this, like NAT) */
02166    if (audio_dest_res != AST_RTP_TRY_NATIVE || (video_dest_res != AST_RTP_GET_FAILED && video_dest_res != AST_RTP_TRY_NATIVE)) {
02167       /* Somebody doesn't want to play... */
02168       ast_channel_unlock(c0);
02169       if (c1)
02170          ast_channel_unlock(c1);
02171       return -1;
02172    }
02173    if (audio_src_res == AST_RTP_TRY_NATIVE && (video_src_res == AST_RTP_GET_FAILED || video_src_res == AST_RTP_TRY_NATIVE) && srcpr->get_codec)
02174       srccodec = srcpr->get_codec(c1);
02175    else
02176       srccodec = 0;
02177    if (audio_dest_res == AST_RTP_TRY_NATIVE && (video_dest_res == AST_RTP_GET_FAILED || video_dest_res == AST_RTP_TRY_NATIVE) && destpr->get_codec)
02178       destcodec = destpr->get_codec(c0);
02179    else
02180       destcodec = 0;
02181    /* Ensure we have at least one matching codec */
02182    if (srcp && !(srccodec & destcodec)) {
02183       ast_channel_unlock(c0);
02184       ast_channel_unlock(c1);
02185       return 0;
02186    }
02187    /* Consider empty media as non-existent */
02188    if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
02189       srcp = NULL;
02190    if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
02191       nat_active = 1;
02192    /* Bridge media early */
02193    if (destpr->set_rtp_peer(c0, srcp, vsrcp, tsrcp, srccodec, nat_active))
02194       ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
02195    ast_channel_unlock(c0);
02196    if (c1)
02197       ast_channel_unlock(c1);
02198    ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
02199    return 0;
02200 }
02201 
02202 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
02203 {
02204    struct ast_rtp *destp = NULL, *srcp = NULL;     /* Audio RTP Channels */
02205    struct ast_rtp *vdestp = NULL, *vsrcp = NULL;      /* Video RTP channels */
02206    struct ast_rtp *tdestp = NULL, *tsrcp = NULL;      /* Text RTP channels */
02207    struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
02208    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;
02209    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; 
02210    int srccodec, destcodec;
02211 
02212    /* Lock channels */
02213    ast_channel_lock(dest);
02214    while (ast_channel_trylock(src)) {
02215       ast_channel_unlock(dest);
02216       usleep(1);
02217       ast_channel_lock(dest);
02218    }
02219 
02220    /* Find channel driver interfaces */
02221    if (!(destpr = get_proto(dest))) {
02222       ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", dest->name);
02223       ast_channel_unlock(dest);
02224       ast_channel_unlock(src);
02225       return 0;
02226    }
02227    if (!(srcpr = get_proto(src))) {
02228       ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", src->name);
02229       ast_channel_unlock(dest);
02230       ast_channel_unlock(src);
02231       return 0;
02232    }
02233 
02234    /* Get audio and video interface (if native bridge is possible) */
02235    audio_dest_res = destpr->get_rtp_info(dest, &destp);
02236    video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
02237    text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(dest, &tdestp) : AST_RTP_GET_FAILED;
02238    audio_src_res = srcpr->get_rtp_info(src, &srcp);
02239    video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
02240    text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(src, &tsrcp) : AST_RTP_GET_FAILED;
02241 
02242    /* Ensure we have at least one matching codec */
02243    if (srcpr->get_codec)
02244       srccodec = srcpr->get_codec(src);
02245    else
02246       srccodec = 0;
02247    if (destpr->get_codec)
02248       destcodec = destpr->get_codec(dest);
02249    else
02250       destcodec = 0;
02251 
02252    /* Check if bridge is still possible (In SIP directmedia=no stops this, like NAT) */
02253    if (audio_dest_res != AST_RTP_TRY_NATIVE || (video_dest_res != AST_RTP_GET_FAILED && video_dest_res != AST_RTP_TRY_NATIVE) || audio_src_res != AST_RTP_TRY_NATIVE || (video_src_res != AST_RTP_GET_FAILED && video_src_res != AST_RTP_TRY_NATIVE) || !(srccodec & destcodec)) {
02254       /* Somebody doesn't want to play... */
02255       ast_channel_unlock(dest);
02256       ast_channel_unlock(src);
02257       return 0;
02258    }
02259    ast_rtp_pt_copy(destp, srcp);
02260    if (vdestp && vsrcp)
02261       ast_rtp_pt_copy(vdestp, vsrcp);
02262    if (tdestp && tsrcp)
02263       ast_rtp_pt_copy(tdestp, tsrcp);
02264    if (media) {
02265       /* Bridge early */
02266       if (destpr->set_rtp_peer(dest, srcp, vsrcp, tsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
02267          ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
02268    }
02269    ast_channel_unlock(dest);
02270    ast_channel_unlock(src);
02271    ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
02272    return 1;
02273 }
02274 
02275 /*! \brief  Make a note of a RTP payload type that was seen in a SDP "m=" line.
02276  * By default, use the well-known value for this type (although it may 
02277  * still be set to a different value by a subsequent "a=rtpmap:" line)
02278  */
02279 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt) 
02280 {
02281    if (pt < 0 || pt >= MAX_RTP_PT || static_RTP_PT[pt].code == 0) 
02282       return; /* bogus payload type */
02283 
02284    rtp_bridge_lock(rtp);
02285    rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
02286    rtp_bridge_unlock(rtp);
02287 } 
02288 
02289 /*! \brief remove setting from payload type list if the rtpmap header indicates
02290    an unknown media type */
02291 void ast_rtp_unset_m_type(struct ast_rtp* rtp, int pt) 
02292 {
02293    if (pt < 0 || pt >= MAX_RTP_PT)
02294       return; /* bogus payload type */
02295 
02296    rtp_bridge_lock(rtp);
02297    rtp->current_RTP_PT[pt].isAstFormat = 0;
02298    rtp->current_RTP_PT[pt].code = 0;
02299    rtp_bridge_unlock(rtp);
02300 }
02301 
02302 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
02303  * an SDP "a=rtpmap:" line.
02304  * \return 0 if the MIME type was found and set, -1 if it wasn't found
02305  */
02306 int ast_rtp_set_rtpmap_type_rate(struct ast_rtp *rtp, int pt,
02307              char *mimeType, char *mimeSubtype,
02308              enum ast_rtp_options options,
02309              unsigned int sample_rate)
02310 {
02311    unsigned int i;
02312    int found = 0;
02313 
02314    if (pt < 0 || pt >= MAX_RTP_PT)
02315       return -1; /* bogus payload type */
02316 
02317    rtp_bridge_lock(rtp);
02318 
02319    for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
02320       const struct mimeType *t = &mimeTypes[i];
02321 
02322       if (strcasecmp(mimeSubtype, t->subtype)) {
02323          continue;
02324       }
02325 
02326       if (strcasecmp(mimeType, t->type)) {
02327          continue;
02328       }
02329 
02330       /* if both sample rates have been supplied, and they don't match,
02331          then this not a match; if one has not been supplied, then the
02332          rates are not compared */
02333       if (sample_rate && t->sample_rate &&
02334           (sample_rate != t->sample_rate)) {
02335          continue;
02336       }
02337 
02338       found = 1;
02339       rtp->current_RTP_PT[pt] = t->payloadType;
02340 
02341       if ((t->payloadType.code == AST_FORMAT_G726) &&
02342           t->payloadType.isAstFormat &&
02343           (options & AST_RTP_OPT_G726_NONSTANDARD)) {
02344          rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
02345       }
02346 
02347       break;
02348    }
02349 
02350    rtp_bridge_unlock(rtp);
02351 
02352    return (found ? 0 : -2);
02353 }
02354 
02355 int ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
02356              char *mimeType, char *mimeSubtype,
02357              enum ast_rtp_options options)
02358 {
02359    return ast_rtp_set_rtpmap_type_rate(rtp, pt, mimeType, mimeSubtype, options, 0);
02360 }
02361 
02362 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls 
02363  * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
02364 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
02365              int* astFormats, int* nonAstFormats)
02366 {
02367    int pt;
02368    
02369    rtp_bridge_lock(rtp);
02370    
02371    *astFormats = *nonAstFormats = 0;
02372    for (pt = 0; pt < MAX_RTP_PT; ++pt) {
02373       if (rtp->current_RTP_PT[pt].isAstFormat) {
02374          *astFormats |= rtp->current_RTP_PT[pt].code;
02375       } else {
02376          *nonAstFormats |= rtp->current_RTP_PT[pt].code;
02377       }
02378    }
02379 
02380    rtp_bridge_unlock(rtp);
02381 }
02382 
02383 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt) 
02384 {
02385    struct rtpPayloadType result;
02386 
02387    result.isAstFormat = result.code = 0;
02388 
02389    if (pt < 0 || pt >= MAX_RTP_PT) 
02390       return result; /* bogus payload type */
02391 
02392    /* Start with negotiated codecs */
02393    rtp_bridge_lock(rtp);
02394    result = rtp->current_RTP_PT[pt];
02395    rtp_bridge_unlock(rtp);
02396 
02397    /* If it doesn't exist, check our static RTP type list, just in case */
02398    if (!result.code) 
02399       result = static_RTP_PT[pt];
02400 
02401    return result;
02402 }
02403 
02404 /*! \brief Looks up an RTP code out of our *static* outbound list */
02405 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
02406 {
02407    int pt = 0;
02408 
02409    rtp_bridge_lock(rtp);
02410 
02411    if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
02412       code == rtp->rtp_lookup_code_cache_code) {
02413       /* Use our cached mapping, to avoid the overhead of the loop below */
02414       pt = rtp->rtp_lookup_code_cache_result;
02415       rtp_bridge_unlock(rtp);
02416       return pt;
02417    }
02418 
02419    /* Check the dynamic list first */
02420    for (pt = 0; pt < MAX_RTP_PT; ++pt) {
02421       if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
02422          rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
02423          rtp->rtp_lookup_code_cache_code = code;
02424          rtp->rtp_lookup_code_cache_result = pt;
02425          rtp_bridge_unlock(rtp);
02426          return pt;
02427       }
02428    }
02429 
02430    /* Then the static list */
02431    for (pt = 0; pt < MAX_RTP_PT; ++pt) {
02432       if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
02433          rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
02434          rtp->rtp_lookup_code_cache_code = code;
02435          rtp->rtp_lookup_code_cache_result = pt;
02436          rtp_bridge_unlock(rtp);
02437          return pt;
02438       }
02439    }
02440 
02441    rtp_bridge_unlock(rtp);
02442 
02443    return -1;
02444 }
02445 
02446 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
02447               enum ast_rtp_options options)
02448 {
02449    unsigned int i;
02450 
02451    for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
02452       if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
02453          if (isAstFormat &&
02454              (code == AST_FORMAT_G726_AAL2) &&
02455              (options & AST_RTP_OPT_G726_NONSTANDARD))
02456             return "G726-32";
02457          else
02458             return mimeTypes[i].subtype;
02459       }
02460    }
02461 
02462    return "";
02463 }
02464 
02465 unsigned int ast_rtp_lookup_sample_rate(int isAstFormat, int code)
02466 {
02467    unsigned int i;
02468 
02469    for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
02470       if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
02471          return mimeTypes[i].sample_rate;
02472       }
02473    }
02474 
02475    return 0;
02476 }
02477 
02478 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
02479                const int isAstFormat, enum ast_rtp_options options)
02480 {
02481    int format;
02482    unsigned len;
02483    char *end = buf;
02484    char *start = buf;
02485 
02486    if (!buf || !size)
02487       return NULL;
02488 
02489    snprintf(end, size, "0x%x (", capability);
02490 
02491    len = strlen(end);
02492    end += len;
02493    size -= len;
02494    start = end;
02495 
02496    for (format = 1; format < AST_RTP_MAX; format <<= 1) {
02497       if (capability & format) {
02498          const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
02499 
02500          snprintf(end, size, "%s|", name);
02501          len = strlen(end);
02502          end += len;
02503          size -= len;
02504       }
02505    }
02506 
02507    if (start == end)
02508       ast_copy_string(start, "nothing)", size); 
02509    else if (size > 1)
02510       *(end -1) = ')';
02511    
02512    return buf;
02513 }
02514 
02515 /*! \brief Open RTP or RTCP socket for a session.
02516  * Print a message on failure. 
02517  */
02518 static int rtp_socket(const char *type)
02519 {
02520    int s = socket(AF_INET, SOCK_DGRAM, 0);
02521    if (s < 0) {
02522       if (type == NULL)
02523          type = "RTP/RTCP";
02524       ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
02525    } else {
02526       long flags = fcntl(s, F_GETFL);
02527       fcntl(s, F_SETFL, flags | O_NONBLOCK);
02528 #ifdef SO_NO_CHECK
02529       if (nochecksums)
02530          setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
02531 #endif
02532    }
02533    return s;
02534 }
02535 
02536 /*!
02537  * \brief Initialize a new RTCP session.
02538  * 
02539  * \returns The newly initialized RTCP session.
02540  */
02541 static struct ast_rtcp *ast_rtcp_new(void)
02542 {
02543    struct ast_rtcp *rtcp;
02544 
02545    if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
02546       return NULL;
02547    rtcp->s = rtp_socket("RTCP");
02548    rtcp->us.sin_family = AF_INET;
02549    rtcp->them.sin_family = AF_INET;
02550    rtcp->schedid = -1;
02551 
02552    if (rtcp->s < 0) {
02553       ast_free(rtcp);
02554       return NULL;
02555    }
02556 
02557    return rtcp;
02558 }
02559 
02560 /*!
02561  * \brief Initialize a new RTP structure.
02562  *
02563  */
02564 void ast_rtp_new_init(struct ast_rtp *rtp)
02565 {
02566 #ifdef P2P_INTENSE
02567    ast_mutex_init(&rtp->bridge_lock);
02568 #endif
02569 
02570    rtp->them.sin_family = AF_INET;
02571    rtp->us.sin_family = AF_INET;
02572    rtp->ssrc = ast_random();
02573    rtp->seqno = ast_random() & 0xffff;
02574    ast_set_flag(rtp, FLAG_HAS_DTMF);
02575    rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
02576 }
02577 
02578 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
02579 {
02580    struct ast_rtp *rtp;
02581    int x;
02582    int startplace;
02583    
02584    if (!(rtp = ast_calloc(1, sizeof(*rtp))))
02585       return NULL;
02586 
02587    ast_rtp_new_init(rtp);
02588 
02589    rtp->s = rtp_socket("RTP");
02590    if (rtp->s < 0)
02591       goto fail;
02592    if (sched && rtcpenable) {
02593       rtp->sched = sched;
02594       rtp->rtcp = ast_rtcp_new();
02595    }
02596    
02597    /*
02598     * Try to bind the RTP port, x, and possibly the RTCP port, x+1 as well.
02599     * Start from a random (even, by RTP spec) port number, and
02600     * iterate until success or no ports are available.
02601     * Note that the requirement of RTP port being even, or RTCP being the
02602     * next one, cannot be enforced in presence of a NAT box because the
02603     * mapping is not under our control.
02604     */
02605    x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
02606    x = x & ~1;    /* make it an even number */
02607    startplace = x;      /* remember the starting point */
02608    /* this is constant across the loop */
02609    rtp->us.sin_addr = addr;
02610    if (rtp->rtcp)
02611       rtp->rtcp->us.sin_addr = addr;
02612    for (;;) {
02613       rtp->us.sin_port = htons(x);
02614       if (!bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) {
02615          /* bind succeeded, if no rtcp then we are done */
02616          if (!rtp->rtcp)
02617             break;
02618          /* have rtcp, try to bind it */
02619          rtp->rtcp->us.sin_port = htons(x + 1);
02620          if (!bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us)))
02621             break;   /* success again, we are really done */
02622          /*
02623           * RTCP bind failed, so close and recreate the
02624           * already bound RTP socket for the next round.
02625           */
02626          close(rtp->s);
02627          rtp->s = rtp_socket("RTP");
02628          if (rtp->s < 0)
02629             goto fail;
02630       }
02631       /*
02632        * If we get here, there was an error in one of the bind()
02633        * calls, so make sure it is nothing unexpected.
02634        */
02635       if (errno != EADDRINUSE) {
02636          /* We got an error that wasn't expected, abort! */
02637          ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
02638          goto fail;
02639       }
02640       /*
02641        * One of the ports is in use. For the next iteration,
02642        * increment by two and handle wraparound.
02643        * If we reach the starting point, then declare failure.
02644        */
02645       x += 2;
02646       if (x > rtpend)
02647          x = (rtpstart + 1) & ~1;
02648       if (x == startplace) {
02649          ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
02650          goto fail;
02651       }
02652    }
02653    rtp->sched = sched;
02654    rtp->io = io;
02655    if (callbackmode) {
02656       rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
02657       ast_set_flag(rtp, FLAG_CALLBACK_MODE);
02658    }
02659    ast_rtp_pt_default(rtp);
02660    return rtp;
02661 
02662 fail:
02663    if (rtp->s >= 0)
02664       close(rtp->s);
02665    if (rtp->rtcp) {
02666       close(rtp->rtcp->s);
02667       ast_free(rtp->rtcp);
02668    }
02669    ast_free(rtp);
02670    return NULL;
02671 }
02672 
02673 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
02674 {
02675    struct in_addr ia;
02676 
02677    memset(&ia, 0, sizeof(ia));
02678    return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
02679 }
02680 
02681 int ast_rtp_setqos(struct ast_rtp *rtp, int type_of_service, int class_of_service, char *desc)
02682 {
02683    return ast_netsock_set_qos(rtp->s, type_of_service, class_of_service, desc);
02684 }
02685 
02686 void ast_rtp_new_source(struct ast_rtp *rtp)
02687 {
02688    if (rtp) {
02689       rtp->set_marker_bit = 1;
02690       ast_debug(3, "Setting the marker bit due to a source update\n");
02691    }
02692 }
02693 
02694 void ast_rtp_change_source(struct ast_rtp *rtp)
02695 {
02696    if (rtp) {
02697       unsigned int ssrc = ast_random();
02698 
02699       rtp->set_marker_bit = 1;
02700       ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
02701       rtp->ssrc = ssrc;
02702    }
02703 }
02704 
02705 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
02706 {
02707    rtp->them.sin_port = them->sin_port;
02708    rtp->them.sin_addr = them->sin_addr;
02709    if (rtp->rtcp) {
02710       int h = ntohs(them->sin_port);
02711       rtp->rtcp->them.sin_port = htons(h + 1);
02712       rtp->rtcp->them.sin_addr = them->sin_addr;
02713    }
02714    rtp->rxseqno = 0;
02715    /* If strict RTP protection is enabled switch back to the learn state so we don't drop packets from above */
02716    if (strictrtp)
02717       rtp->strict_rtp_state = STRICT_RTP_LEARN;
02718 }
02719 
02720 void ast_rtp_set_alt_peer(struct ast_rtp *rtp, struct sockaddr_in *alt)
02721 {
02722    rtp->altthem.sin_port = alt->sin_port;
02723    rtp->altthem.sin_addr = alt->sin_addr;
02724    if (rtp->rtcp) {
02725       rtp->rtcp->altthem.sin_port = htons(ntohs(alt->sin_port) + 1);
02726       rtp->rtcp->altthem.sin_addr = alt->sin_addr;
02727    }
02728 }
02729 
02730 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
02731 {
02732    if ((them->sin_family != AF_INET) ||
02733       (them->sin_port != rtp->them.sin_port) ||
02734       (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
02735       them->sin_family = AF_INET;
02736       them->sin_port = rtp->them.sin_port;
02737       them->sin_addr = rtp->them.sin_addr;
02738       return 1;
02739    }
02740    return 0;
02741 }
02742 
02743 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
02744 {
02745    *us = rtp->us;
02746 }
02747 
02748 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
02749 {
02750    struct ast_rtp *bridged = NULL;
02751 
02752    rtp_bridge_lock(rtp);
02753    bridged = rtp->bridged;
02754    rtp_bridge_unlock(rtp);
02755 
02756    return bridged;
02757 }
02758 
02759 void ast_rtp_stop(struct ast_rtp *rtp)
02760 {
02761    if (rtp->rtcp) {
02762       AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
02763    }
02764    if (rtp->red) {
02765       AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
02766       free(rtp->red);
02767       rtp->red = NULL;
02768    }
02769 
02770    memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
02771    memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
02772    if (rtp->rtcp) {
02773       memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
02774       memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
02775    }
02776    
02777    ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
02778 }
02779 
02780 void ast_rtp_reset(struct ast_rtp *rtp)
02781 {
02782    memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
02783    memset(&rtp->txcore, 0, sizeof(rtp->txcore));
02784    memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
02785    rtp->lastts = 0;
02786    rtp->lastdigitts = 0;
02787    rtp->lastrxts = 0;
02788    rtp->lastividtimestamp = 0;
02789    rtp->lastovidtimestamp = 0;
02790    rtp->lastitexttimestamp = 0;
02791    rtp->lastotexttimestamp = 0;
02792    rtp->lasteventseqn = 0;
02793    rtp->lastevent = 0;
02794    rtp->lasttxformat = 0;
02795    rtp->lastrxformat = 0;
02796    rtp->dtmf_timeout = 0;
02797    rtp->dtmfsamples = 0;
02798    rtp->seqno = 0;
02799    rtp->rxseqno = 0;
02800 }
02801 
02802 /*! Get QoS values from RTP and RTCP data (used in "sip show channelstats") */
02803 unsigned int ast_rtp_get_qosvalue(struct ast_rtp *rtp, enum ast_rtp_qos_vars value)
02804 {
02805    if (rtp == NULL) {
02806       if (option_debug > 1)
02807          ast_log(LOG_DEBUG, "NO RTP Structure? Kidding me? \n");
02808       return 0;
02809    }
02810    if (option_debug > 1 && rtp->rtcp == NULL) {
02811       ast_log(LOG_DEBUG, "NO RTCP structure. Maybe in RTP p2p bridging mode? \n");
02812    }
02813 
02814    switch (value) {
02815    case AST_RTP_TXCOUNT:
02816       return (unsigned int) rtp->txcount;
02817    case AST_RTP_RXCOUNT:
02818       return (unsigned int) rtp->rxcount;
02819    case AST_RTP_TXJITTER:
02820       return (unsigned int) (rtp->rxjitter * 1000.0);
02821    case AST_RTP_RXJITTER:
02822       return (unsigned int) (rtp->rtcp ? (rtp->rtcp->reported_jitter / (unsigned int) 65536.0) : 0);
02823    case AST_RTP_RXPLOSS:
02824       return rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0;
02825    case AST_RTP_TXPLOSS:
02826       return rtp->rtcp ? rtp->rtcp->reported_lost : 0;
02827    case AST_RTP_RTT:
02828       return (unsigned int) (rtp->rtcp ? (rtp->rtcp->rtt * 100) : 0);
02829    }
02830    return 0;   /* To make the compiler happy */
02831 }
02832 
02833 static double __ast_rtp_get_qos(struct ast_rtp *rtp, const char *qos, int *found)
02834 {
02835    *found = 1;
02836 
02837    if (!strcasecmp(qos, "remote_maxjitter"))
02838       return rtp->rtcp->reported_maxjitter * 1000.0;
02839    if (!strcasecmp(qos, "remote_minjitter"))
02840       return rtp->rtcp->reported_minjitter * 1000.0;
02841    if (!strcasecmp(qos, "remote_normdevjitter"))
02842       return rtp->rtcp->reported_normdev_jitter * 1000.0;
02843    if (!strcasecmp(qos, "remote_stdevjitter"))
02844       return sqrt(rtp->rtcp->reported_stdev_jitter) * 1000.0;
02845 
02846    if (!strcasecmp(qos, "local_maxjitter"))
02847       return rtp->rtcp->maxrxjitter * 1000.0;
02848    if (!strcasecmp(qos, "local_minjitter"))
02849       return rtp->rtcp->minrxjitter * 1000.0;
02850    if (!strcasecmp(qos, "local_normdevjitter"))
02851       return rtp->rtcp->normdev_rxjitter * 1000.0;
02852    if (!strcasecmp(qos, "local_stdevjitter"))
02853       return sqrt(rtp->rtcp->stdev_rxjitter) * 1000.0;
02854 
02855    if (!strcasecmp(qos, "maxrtt"))
02856       return rtp->rtcp->maxrtt * 1000.0;
02857    if (!strcasecmp(qos, "minrtt"))
02858       return rtp->rtcp->minrtt * 1000.0;
02859    if (!strcasecmp(qos, "normdevrtt"))
02860       return rtp->rtcp->normdevrtt * 1000.0;
02861    if (!strcasecmp(qos, "stdevrtt"))
02862       return sqrt(rtp->rtcp->stdevrtt) * 1000.0;
02863 
02864    *found = 0;
02865 
02866    return 0.0;
02867 }
02868 
02869 int ast_rtp_get_qos(struct ast_rtp *rtp, const char *qos, char *buf, unsigned int buflen)
02870 {
02871    double value;
02872    int found;
02873 
02874    value = __ast_rtp_get_qos(rtp, qos, &found);
02875 
02876    if (!found)
02877       return -1;
02878 
02879    snprintf(buf, buflen, "%.0lf", value);
02880 
02881    return 0;
02882 }
02883 
02884 void ast_rtp_set_vars(struct ast_channel *chan, struct ast_rtp *rtp) {
02885    char *audioqos;
02886    char *audioqos_jitter;
02887    char *audioqos_loss;
02888    char *audioqos_rtt;
02889    struct ast_channel *bridge;
02890 
02891    if (!rtp || !chan)
02892       return;
02893 
02894    bridge = ast_bridged_channel(chan);
02895 
02896    audioqos        = ast_rtp_get_quality(rtp, NULL, RTPQOS_SUMMARY);
02897    audioqos_jitter = ast_rtp_get_quality(rtp, NULL, RTPQOS_JITTER);
02898    audioqos_loss   = ast_rtp_get_quality(rtp, NULL, RTPQOS_LOSS);
02899    audioqos_rtt    = ast_rtp_get_quality(rtp, NULL, RTPQOS_RTT);
02900 
02901    pbx_builtin_setvar_helper(chan, "RTPAUDIOQOS", audioqos);
02902    pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSJITTER", audioqos_jitter);
02903    pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSLOSS", audioqos_loss);
02904    pbx_builtin_setvar_helper(chan, "RTPAUDIOQOSRTT", audioqos_rtt);
02905 
02906    if (!bridge)
02907       return;
02908 
02909    pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSBRIDGED", audioqos);
02910    pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSJITTERBRIDGED", audioqos_jitter);
02911    pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSLOSSBRIDGED", audioqos_loss);
02912    pbx_builtin_setvar_helper(bridge, "RTPAUDIOQOSRTTBRIDGED", audioqos_rtt);
02913 }
02914 
02915 static char *__ast_rtp_get_quality_jitter(struct ast_rtp *rtp)
02916 {
02917    /*
02918    *ssrc          our ssrc
02919    *themssrc      their ssrc
02920    *lp            lost packets
02921    *rxjitter      our calculated jitter(rx)
02922    *rxcount       no. received packets
02923    *txjitter      reported jitter of the other end
02924    *txcount       transmitted packets
02925    *rlp           remote lost packets
02926    *rtt           round trip time
02927    */
02928 #define RTCP_JITTER_FORMAT1 \
02929    "minrxjitter=%f;" \
02930    "maxrxjitter=%f;" \
02931    "avgrxjitter=%f;" \
02932    "stdevrxjitter=%f;" \
02933    "reported_minjitter=%f;" \
02934    "reported_maxjitter=%f;" \
02935    "reported_avgjitter=%f;" \
02936    "reported_stdevjitter=%f;"
02937 
02938 #define RTCP_JITTER_FORMAT2 \
02939    "rxjitter=%f;"
02940 
02941    if (rtp->rtcp && rtp->rtcp->rtcp_info) {
02942       snprintf(rtp->rtcp->quality_jitter, sizeof(rtp->rtcp->quality_jitter), RTCP_JITTER_FORMAT1,
02943          rtp->rtcp->minrxjitter,
02944          rtp->rtcp->maxrxjitter,
02945          rtp->rtcp->normdev_rxjitter,
02946          sqrt(rtp->rtcp->stdev_rxjitter),
02947          rtp->rtcp->reported_minjitter,
02948          rtp->rtcp->reported_maxjitter,
02949          rtp->rtcp->reported_normdev_jitter,
02950          sqrt(rtp->rtcp->reported_stdev_jitter)
02951       );
02952    } else {
02953       snprintf(rtp->rtcp->quality_jitter, sizeof(rtp->rtcp->quality_jitter), RTCP_JITTER_FORMAT2,
02954          rtp->rxjitter
02955       );
02956    }
02957 
02958    return rtp->rtcp->quality_jitter;
02959 
02960 #undef RTCP_JITTER_FORMAT1
02961 #undef RTCP_JITTER_FORMAT2
02962 }
02963 
02964 static char *__ast_rtp_get_quality_loss(struct ast_rtp *rtp)
02965 {
02966    unsigned int lost;
02967    unsigned int extended;
02968    unsigned int expected;
02969    int fraction;
02970 
02971 #define RTCP_LOSS_FORMAT1 \
02972    "minrxlost=%f;" \
02973    "maxrxlost=%f;" \
02974    "avgrxlostr=%f;" \
02975    "stdevrxlost=%f;" \
02976    "reported_minlost=%f;" \
02977    "reported_maxlost=%f;" \
02978    "reported_avglost=%f;" \
02979    "reported_stdevlost=%f;"
02980 
02981 #define RTCP_LOSS_FORMAT2 \
02982    "lost=%d;" \
02983    "expected=%d;"
02984    
02985    if (rtp->rtcp && rtp->rtcp->rtcp_info && rtp->rtcp->maxrxlost > 0) {
02986       snprintf(rtp->rtcp->quality_loss, sizeof(rtp->rtcp->quality_loss), RTCP_LOSS_FORMAT1,
02987          rtp->rtcp->minrxlost,
02988          rtp->rtcp->maxrxlost,
02989          rtp->rtcp->normdev_rxlost,
02990          sqrt(rtp->rtcp->stdev_rxlost),
02991          rtp->rtcp->reported_minlost,
02992          rtp->rtcp->reported_maxlost,
02993          rtp->rtcp->reported_normdev_lost,
02994          sqrt(rtp->rtcp->reported_stdev_lost)
02995       );
02996    } else {
02997       extended = rtp->cycles + rtp->lastrxseqno;
02998       expected = extended - rtp->seedrxseqno + 1;
02999       if (rtp->rxcount > expected) 
03000          expected += rtp->rxcount - expected;
03001       lost = expected - rtp->rxcount;
03002 
03003       if (!expected || lost <= 0)
03004          fraction = 0;
03005       else
03006          fraction = (lost << 8) / expected;
03007 
03008       snprintf(rtp->rtcp->quality_loss, sizeof(rtp->rtcp->quality_loss), RTCP_LOSS_FORMAT2,
03009          lost,
03010          expected
03011       );
03012    }
03013 
03014    return rtp->rtcp->quality_loss;
03015 
03016 #undef RTCP_LOSS_FORMAT1
03017 #undef RTCP_LOSS_FORMAT2
03018 }
03019 
03020 static char *__ast_rtp_get_quality_rtt(struct ast_rtp *rtp)
03021 {
03022    if (rtp->rtcp && rtp->rtcp->rtcp_info) {
03023       snprintf(rtp->rtcp->quality_rtt, sizeof(rtp->rtcp->quality_rtt), "minrtt=%f;maxrtt=%f;avgrtt=%f;stdevrtt=%f;",
03024          rtp->rtcp->minrtt,
03025          rtp->rtcp->maxrtt,
03026          rtp->rtcp->normdevrtt,
03027          sqrt(rtp->rtcp->stdevrtt)
03028       );
03029    } else {
03030       snprintf(rtp->rtcp->quality_rtt, sizeof(rtp->rtcp->quality_rtt), "Not available");
03031    }
03032 
03033    return rtp->rtcp->quality_rtt;
03034 }
03035 
03036 static char *__ast_rtp_get_quality(struct ast_rtp *rtp)
03037 {
03038    /*
03039    *ssrc          our ssrc
03040    *themssrc      their ssrc
03041    *lp            lost packets
03042    *rxjitter      our calculated jitter(rx)
03043    *rxcount       no. received packets
03044    *txjitter      reported jitter of the other end
03045    *txcount       transmitted packets
03046    *rlp           remote lost packets
03047    *rtt           round trip time
03048    */ 
03049 
03050    if (rtp->rtcp && rtp->rtcp->rtcp_info) {
03051       snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality),
03052          "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
03053          rtp->ssrc,
03054          rtp->themssrc,
03055          rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
03056          rtp->rxjitter,
03057          rtp->rxcount,
03058          (double)rtp->rtcp->reported_jitter / 65536.0,
03059          rtp->txcount,
03060          rtp->rtcp->reported_lost,
03061          rtp->rtcp->rtt
03062       );
03063    } else {
03064       snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality), "ssrc=%u;themssrc=%u;rxjitter=%f;rxcount=%u;txcount=%u;",
03065          rtp->ssrc,
03066          rtp->themssrc,
03067          rtp->rxjitter,
03068          rtp->rxcount,
03069          rtp->txcount
03070       );
03071    }
03072 
03073    return rtp->rtcp->quality;
03074 }
03075 
03076 char *ast_rtp_get_quality(struct ast_rtp *rtp, struct ast_rtp_quality *qual, enum ast_rtp_quality_type qtype) 
03077 {
03078    if (qual && rtp) {
03079       qual->local_ssrc   = rtp->ssrc;
03080       qual->local_jitter = rtp->rxjitter;
03081       qual->local_count  = rtp->rxcount;
03082       qual->remote_ssrc  = rtp->themssrc;
03083       qual->remote_count = rtp->txcount;
03084 
03085       if (rtp->rtcp) {
03086          qual->local_lostpackets  = rtp->rtcp->expected_prior - rtp->rtcp->received_prior;
03087          qual->remote_lostpackets = rtp->rtcp->reported_lost;
03088          qual->remote_jitter      = rtp->rtcp->reported_jitter / 65536.0;
03089          qual->rtt                = rtp->rtcp->rtt;
03090       }
03091    }
03092 
03093    switch (qtype) {
03094    case RTPQOS_SUMMARY:
03095       return __ast_rtp_get_quality(rtp);
03096    case RTPQOS_JITTER:
03097       return __ast_rtp_get_quality_jitter(rtp);
03098    case RTPQOS_LOSS:
03099       return __ast_rtp_get_quality_loss(rtp);
03100    case RTPQOS_RTT:
03101       return __ast_rtp_get_quality_rtt(rtp);
03102    }
03103 
03104    return NULL;
03105 }
03106 
03107 void ast_rtp_destroy(struct ast_rtp *rtp)
03108 {
03109    if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
03110       /*Print some info on the call here */
03111       ast_verbose("  RTP-stats\n");
03112       ast_verbose("* Our Receiver:\n");
03113       ast_verbose("  SSRC:     %u\n", rtp->themssrc);
03114       ast_verbose("  Received packets: %u\n", rtp->rxcount);
03115       ast_verbose("  Lost packets:   %u\n", rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0);
03116       ast_verbose("  Jitter:      %.4f\n", rtp->rxjitter);
03117       ast_verbose("  Transit:     %.4f\n", rtp->rxtransit);
03118       ast_verbose("  RR-count:    %u\n", rtp->rtcp ? rtp->rtcp->rr_count : 0);
03119       ast_verbose("* Our Sender:\n");
03120       ast_verbose("  SSRC:     %u\n", rtp->ssrc);
03121       ast_verbose("  Sent packets:   %u\n", rtp->txcount);
03122       ast_verbose("  Lost packets:   %u\n", rtp->rtcp ? rtp->rtcp->reported_lost : 0);
03123       ast_verbose("  Jitter:      %u\n", rtp->rtcp ? (rtp->rtcp->reported_jitter / (unsigned int)65536.0) : 0);
03124       ast_verbose("  SR-count:    %u\n", rtp->rtcp ? rtp->rtcp->sr_count : 0);
03125       ast_verbose("  RTT:      %f\n", rtp->rtcp ? rtp->rtcp->rtt : 0);
03126    }
03127 
03128    manager_event(EVENT_FLAG_REPORTING, "RTPReceiverStat", "SSRC: %u\r\n"
03129                    "ReceivedPackets: %u\r\n"
03130                    "LostPackets: %u\r\n"
03131                    "Jitter: %.4f\r\n"
03132                    "Transit: %.4f\r\n"
03133                    "RRCount: %u\r\n",
03134                    rtp->themssrc,
03135                    rtp->rxcount,
03136                    rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0,
03137                    rtp->rxjitter,
03138                    rtp->rxtransit,
03139                    rtp->rtcp ? rtp->rtcp->rr_count : 0);
03140    manager_event(EVENT_FLAG_REPORTING, "RTPSenderStat", "SSRC: %u\r\n"
03141                    "SentPackets: %u\r\n"
03142                    "LostPackets: %u\r\n"
03143                    "Jitter: %u\r\n"
03144                    "SRCount: %u\r\n"
03145                    "RTT: %f\r\n",
03146                    rtp->ssrc,
03147                    rtp->txcount,
03148                    rtp->rtcp ? rtp->rtcp->reported_lost : 0,
03149                    rtp->rtcp ? rtp->rtcp->reported_jitter : 0,
03150                    rtp->rtcp ? rtp->rtcp->sr_count : 0,
03151                    rtp->rtcp ? rtp->rtcp->rtt : 0);
03152    if (rtp->smoother)
03153       ast_smoother_free(rtp->smoother);
03154    if (rtp->ioid)
03155       ast_io_remove(rtp->io, rtp->ioid);
03156    if (rtp->s > -1)
03157       close(rtp->s);
03158    if (rtp->rtcp) {
03159       AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
03160       close(rtp->rtcp->s);
03161       ast_free(rtp->rtcp);
03162       rtp->rtcp=NULL;
03163    }
03164 #ifdef P2P_INTENSE
03165    ast_mutex_destroy(&rtp->bridge_lock);
03166 #endif
03167    ast_free(rtp);
03168 }
03169 
03170 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
03171 {
03172    struct timeval t;
03173    long ms;
03174    if (ast_tvzero(rtp->txcore)) {
03175       rtp->txcore = ast_tvnow();
03176       /* Round to 20ms for nice, pretty timestamps */
03177       rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
03178    }
03179    /* Use previous txcore if available */
03180    t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
03181    ms = ast_tvdiff_ms(t, rtp->txcore);
03182    if (ms < 0)
03183       ms = 0;
03184    /* Use what we just got for next time */
03185    rtp->txcore = t;
03186    return (unsigned int) ms;
03187 }
03188 
03189 /*! \brief Send begin frames for DTMF */
03190 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
03191 {
03192    unsigned int *rtpheader;
03193    int hdrlen = 12, res = 0, i = 0, payload = 0;
03194    char data[256];
03195 
03196    if ((digit <= '9') && (digit >= '0'))
03197       digit -= '0';
03198    else if (digit == '*')
03199       digit = 10;
03200    else if (digit == '#')
03201       digit = 11;
03202    else if ((digit >= 'A') && (digit <= 'D'))
03203       digit = digit - 'A' + 12;
03204    else if ((digit >= 'a') && (digit <= 'd'))
03205       digit = digit - 'a' + 12;
03206    else {
03207       ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
03208       return 0;
03209    }
03210 
03211    /* If we have no peer, return immediately */ 
03212    if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
03213       return 0;
03214 
03215    payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
03216 
03217    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
03218    rtp->send_duration = 160;
03219    rtp->lastdigitts = rtp->lastts + rtp->send_duration;
03220    
03221    /* Get a pointer to the header */
03222    rtpheader = (unsigned int *)data;
03223    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
03224    rtpheader[1] = htonl(rtp->lastdigitts);
03225    rtpheader[2] = htonl(rtp->ssrc); 
03226 
03227    for (i = 0; i < 2; i++) {
03228       rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
03229       res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
03230       if (res < 0) 
03231          ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
03232             ast_inet_ntoa(rtp->them.sin_addr),
03233             ntohs(rtp->them.sin_port), strerror(errno));
03234       if (rtp_debug_test_addr(&rtp->them))
03235          ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
03236                 ast_inet_ntoa(rtp->them.sin_addr),
03237                 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
03238       /* Increment sequence number */
03239       rtp->seqno++;
03240       /* Increment duration */
03241       rtp->send_duration += 160;
03242       /* Clear marker bit and set seqno */
03243       rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
03244    }
03245 
03246    /* Since we received a begin, we can safely store the digit and disable any compensation */
03247    rtp->sending_digit = 1;
03248    rtp->send_digit = digit;
03249    rtp->send_payload = payload;
03250 
03251    return 0;
03252 }
03253 
03254 /*! \brief Send continuation frame for DTMF */
03255 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
03256 {
03257    unsigned int *rtpheader;
03258    int hdrlen = 12, res = 0;
03259    char data[256];
03260 
03261    if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
03262       return 0;
03263 
03264    /* Setup packet to send */
03265    rtpheader = (unsigned int *)data;
03266    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
03267    rtpheader[1] = htonl(rtp->lastdigitts);
03268    rtpheader[2] = htonl(rtp->ssrc);
03269    rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
03270    rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
03271    
03272    /* Transmit */
03273    res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
03274    if (res < 0)
03275       ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
03276          ast_inet_ntoa(rtp->them.sin_addr),
03277          ntohs(rtp->them.sin_port), strerror(errno));
03278    if (rtp_debug_test_addr(&rtp->them))
03279       ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
03280              ast_inet_ntoa(rtp->them.sin_addr),
03281              ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
03282 
03283    /* Increment sequence number */
03284    rtp->seqno++;
03285    /* Increment duration */
03286    rtp->send_duration += 160;
03287 
03288    return 0;
03289 }
03290 
03291 /*! \brief Send end packets for DTMF */
03292 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
03293 {
03294    unsigned int *rtpheader;
03295    int hdrlen = 12, res = 0, i = 0;
03296    char data[256];
03297    
03298    /* If no address, then bail out */
03299    if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
03300       return 0;
03301    
03302    if ((digit <= '9') && (digit >= '0'))
03303       digit -= '0';
03304    else if (digit == '*')
03305       digit = 10;
03306    else if (digit == '#')
03307       digit = 11;
03308    else if ((digit >= 'A') && (digit <= 'D'))
03309       digit = digit - 'A' + 12;
03310    else if ((digit >= 'a') && (digit <= 'd'))
03311       digit = digit - 'a' + 12;
03312    else {
03313       ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
03314       return 0;
03315    }
03316 
03317    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
03318 
03319    rtpheader = (unsigned int *)data;
03320    rtpheader[1] = htonl(rtp->lastdigitts);
03321    rtpheader[2] = htonl(rtp->ssrc);
03322    rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
03323    /* Set end bit */
03324    rtpheader[3] |= htonl((1 << 23));
03325 
03326    /* Send 3 termination packets */
03327    for (i = 0; i < 3; i++) {
03328       rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
03329       res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
03330       rtp->seqno++;
03331       if (res < 0)
03332          ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
03333             ast_inet_ntoa(rtp->them.sin_addr),
03334             ntohs(rtp->them.sin_port), strerror(errno));
03335       if (rtp_debug_test_addr(&rtp->them))
03336          ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
03337                 ast_inet_ntoa(rtp->them.sin_addr),
03338                 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
03339    }
03340    rtp->lastts += rtp->send_duration;
03341    rtp->sending_digit = 0;
03342    rtp->send_digit = 0;
03343 
03344    return res;
03345 }
03346 
03347 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
03348 int ast_rtcp_send_h261fur(void *data)
03349 {
03350    struct ast_rtp *rtp = data;
03351    int res;
03352 
03353    rtp->rtcp->sendfur = 1;
03354    res = ast_rtcp_write(data);
03355    
03356    return res;
03357 }
03358 
03359 /*! \brief Send RTCP sender's report */
03360 static int ast_rtcp_write_sr(const void *data)
03361 {
03362    struct ast_rtp *rtp = (struct ast_rtp *)data;
03363    int res;
03364    int len = 0;
03365    struct timeval now;
03366    unsigned int now_lsw;
03367    unsigned int now_msw;
03368    unsigned int *rtcpheader;
03369    unsigned int lost;
03370    unsigned int extended;
03371    unsigned int expected;
03372    unsigned int expected_interval;
03373    unsigned int received_interval;
03374    int lost_interval;
03375    int fraction;
03376    struct timeval dlsr;
03377    char bdata[512];
03378 
03379    /* Commented condition is always not NULL if rtp->rtcp is not NULL */
03380    if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
03381       return 0;
03382    
03383    if (!rtp->rtcp->them.sin_addr.s_addr) {  /* This'll stop rtcp for this rtp session */
03384       ast_verbose("RTCP SR transmission error, rtcp halted\n");
03385       AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
03386       return 0;
03387    }
03388 
03389    gettimeofday(&now, NULL);
03390    timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
03391    rtcpheader = (unsigned int *)bdata;
03392    rtcpheader[1] = htonl(rtp->ssrc);               /* Our SSRC */
03393    rtcpheader[2] = htonl(now_msw);                 /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
03394    rtcpheader[3] = htonl(now_lsw);                 /* now, LSW */
03395    rtcpheader[4] = htonl(rtp->lastts);             /* FIXME shouldn't be that, it should be now */
03396    rtcpheader[5] = htonl(rtp->txcount);            /* No. packets sent */
03397    rtcpheader[6] = htonl(rtp->txoctetcount);       /* No. bytes sent */
03398    len += 28;
03399    
03400    extended = rtp->cycles + rtp->lastrxseqno;
03401    expected = extended - rtp->seedrxseqno + 1;
03402    if (rtp->rxcount > expected) 
03403       expected += rtp->rxcount - expected;
03404    lost = expected - rtp->rxcount;
03405    expected_interval = expected - rtp->rtcp->expected_prior;
03406    rtp->rtcp->expected_prior = expected;
03407    received_interval = rtp->rxcount - rtp->rtcp->received_prior;
03408    rtp->rtcp->received_prior = rtp->rxcount;
03409    lost_interval = expected_interval - received_interval;
03410    if (expected_interval == 0 || lost_interval <= 0)
03411       fraction = 0;
03412    else
03413       fraction = (lost_interval << 8) / expected_interval;
03414    timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
03415    rtcpheader[7] = htonl(rtp->themssrc);
03416    rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
03417    rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
03418    rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
03419    rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
03420    rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
03421    len += 24;
03422    
03423    rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
03424 
03425    if (rtp->rtcp->sendfur) {
03426       rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
03427       rtcpheader[14] = htonl(rtp->ssrc);               /* Our SSRC */
03428       len += 8;
03429       rtp->rtcp->sendfur = 0;
03430    }
03431    
03432    /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */ 
03433    /* it can change mid call, and SDES can't) */
03434    rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
03435    rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
03436    rtcpheader[(len/4)+2] = htonl(0x01 << 24);                    /* Empty for the moment */
03437    len += 12;
03438    
03439    res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
03440    if (res < 0) {
03441       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));
03442       AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
03443       return 0;
03444    }
03445    
03446    /* FIXME Don't need to get a new one */
03447    gettimeofday(&rtp->rtcp->txlsr, NULL);
03448    rtp->rtcp->sr_count++;
03449 
03450    rtp->rtcp->lastsrtxcount = rtp->txcount;  
03451    
03452    if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
03453       ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
03454       ast_verbose("  Our SSRC: %u\n", rtp->ssrc);
03455       ast_verbose("  Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
03456       ast_verbose("  Sent(RTP): %u\n", rtp->lastts);
03457       ast_verbose("  Sent packets: %u\n", rtp->txcount);
03458       ast_verbose("  Sent octets: %u\n", rtp->txoctetcount);
03459       ast_verbose("  Report block:\n");
03460       ast_verbose("  Fraction lost: %u\n", fraction);
03461       ast_verbose("  Cumulative loss: %u\n", lost);
03462       ast_verbose("  IA jitter: %.4f\n", rtp->rxjitter);
03463       ast_verbose("  Their last SR: %u\n", rtp->rtcp->themrxlsr);
03464       ast_verbose("  DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
03465    }
03466    manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To: %s:%d\r\n"
03467                    "OurSSRC: %u\r\n"
03468                    "SentNTP: %u.%010u\r\n"
03469                    "SentRTP: %u\r\n"
03470                    "SentPackets: %u\r\n"
03471                    "SentOctets: %u\r\n"
03472                    "ReportBlock:\r\n"
03473                    "FractionLost: %u\r\n"
03474                    "CumulativeLoss: %u\r\n"
03475                    "IAJitter: %.4f\r\n"
03476                    "TheirLastSR: %u\r\n"
03477                    "DLSR: %4.4f (sec)\r\n",
03478                    ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port),
03479                    rtp->ssrc,
03480                    (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
03481                    rtp->lastts,
03482                    rtp->txcount,
03483                    rtp->txoctetcount,
03484                    fraction,
03485                    lost,
03486                    rtp->rxjitter,
03487                    rtp->rtcp->themrxlsr,
03488                    (double)(ntohl(rtcpheader[12])/65536.0));
03489    return res;
03490 }
03491 
03492 /*! \brief Send RTCP recipient's report */
03493 static int ast_rtcp_write_rr(const void *data)
03494 {
03495    struct ast_rtp *rtp = (struct ast_rtp *)data;
03496    int res;
03497    int len = 32;
03498    unsigned int lost;
03499    unsigned int extended;
03500    unsigned int expected;
03501    unsigned int expected_interval;
03502    unsigned int received_interval;
03503    int lost_interval;
03504    struct timeval now;
03505    unsigned int *rtcpheader;
03506    char bdata[1024];
03507    struct timeval dlsr;
03508    int fraction;
03509 
03510    double rxlost_current;
03511    
03512    if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
03513       return 0;
03514      
03515    if (!rtp->rtcp->them.sin_addr.s_addr) {
03516       ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
03517       AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
03518       return 0;
03519    }
03520 
03521    extended = rtp->cycles + rtp->lastrxseqno;
03522    expected = extended - rtp->seedrxseqno + 1;
03523    lost = expected - rtp->rxcount;
03524    expected_interval = expected - rtp->rtcp->expected_prior;
03525    rtp->rtcp->expected_prior = expected;
03526    received_interval = rtp->rxcount - rtp->rtcp->received_prior;
03527    rtp->rtcp->received_prior = rtp->rxcount;
03528    lost_interval = expected_interval - received_interval;
03529 
03530    if (lost_interval <= 0)
03531       rtp->rtcp->rxlost = 0;
03532    else rtp->rtcp->rxlost = rtp->rtcp->rxlost;
03533    if (rtp->rtcp->rxlost_count == 0)
03534       rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
03535    if (lost_interval < rtp->rtcp->minrxlost) 
03536       rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
03537    if (lost_interval > rtp->rtcp->maxrxlost) 
03538       rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
03539 
03540    rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->rxlost_count);
03541    rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->normdev_rxlost, rxlost_current, rtp->rtcp->rxlost_count);
03542    rtp->rtcp->normdev_rxlost = rxlost_current;
03543    rtp->rtcp->rxlost_count++;
03544 
03545    if (expected_interval == 0 || lost_interval <= 0)
03546       fraction = 0;
03547    else
03548       fraction = (lost_interval << 8) / expected_interval;
03549    gettimeofday(&now, NULL);
03550    timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
03551    rtcpheader = (unsigned int *)bdata;
03552    rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
03553    rtcpheader[1] = htonl(rtp->ssrc);
03554    rtcpheader[2] = htonl(rtp->themssrc);
03555    rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
03556    rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
03557    rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
03558    rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
03559    rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
03560 
03561    if (rtp->rtcp->sendfur) {
03562       rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
03563       rtcpheader[9] = htonl(rtp->ssrc);               /* Our SSRC */
03564       len += 8;
03565       rtp->rtcp->sendfur = 0;
03566    }
03567 
03568    /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos 
03569    it can change mid call, and SDES can't) */
03570    rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
03571    rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
03572    rtcpheader[(len/4)+2] = htonl(0x01 << 24);              /* Empty for the moment */
03573    len += 12;
03574    
03575    res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
03576 
03577    if (res < 0) {
03578       ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
03579       /* Remove the scheduler */
03580       AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
03581       return 0;
03582    }
03583 
03584    rtp->rtcp->rr_count++;
03585 
03586    if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
03587       ast_verbose("\n* Sending RTCP RR to %s:%d\n"
03588          "  Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n" 
03589          "  IA jitter: %.4f\n" 
03590          "  Their last SR: %u\n" 
03591          "  DLSR: %4.4f (sec)\n\n",
03592          ast_inet_ntoa(rtp->rtcp->them.sin_addr),
03593          ntohs(rtp->rtcp->them.sin_port),
03594          rtp->ssrc, rtp->themssrc, fraction, lost,
03595          rtp->rxjitter,
03596          rtp->rtcp->themrxlsr,
03597          (double)(ntohl(rtcpheader[7])/65536.0));
03598    }
03599 
03600    return res;
03601 }
03602 
03603 /*! \brief Write and RTCP packet to the far end
03604  * \note Decide if we are going to send an SR (with Reception Block) or RR 
03605  * RR is sent if we have not sent any rtp packets in the previous interval */
03606 static int ast_rtcp_write(const void *data)
03607 {
03608    struct ast_rtp *rtp = (struct ast_rtp *)data;
03609    int res;
03610    
03611    if (!rtp || !rtp->rtcp)
03612       return 0;
03613 
03614    if (rtp->txcount > rtp->rtcp->lastsrtxcount)
03615       res = ast_rtcp_write_sr(data);
03616    else
03617       res = ast_rtcp_write_rr(data);
03618    
03619    return res;
03620 }
03621 
03622 /*! \brief generate comfort noice (CNG) */
03623 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
03624 {
03625    unsigned int *rtpheader;
03626    int hdrlen = 12;
03627    int res;
03628    int payload;
03629    char data[256];
03630    level = 127 - (level & 0x7f);
03631    payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
03632 
03633    /* If we have no peer, return immediately */ 
03634    if (!rtp->them.sin_addr.s_addr)
03635       return 0;
03636 
03637    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
03638 
03639    /* Get a pointer to the header */
03640    rtpheader = (unsigned int *)data;
03641    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
03642    rtpheader[1] = htonl(rtp->lastts);
03643    rtpheader[2] = htonl(rtp->ssrc); 
03644    data[12] = level;
03645    if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
03646       res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
03647       if (res <0) 
03648          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));
03649       if (rtp_debug_test_addr(&rtp->them))
03650          ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
03651                , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);         
03652          
03653    }
03654    return 0;
03655 }
03656 
03657 /*! \brief Write RTP packet with audio or video media frames into UDP packet */
03658 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
03659 {
03660    unsigned char *rtpheader;
03661    int hdrlen = 12;
03662    int res;
03663    unsigned int ms;
03664    int pred;
03665    int mark = 0;
03666    int rate = rtp_get_rate(f->subclass) / 1000;
03667 
03668    if (f->subclass == AST_FORMAT_G722) {
03669       f->samples /= 2;
03670    }
03671 
03672    if (rtp->sending_digit) {
03673       return 0;
03674    }
03675 
03676    ms = calc_txstamp(rtp, &f->delivery);
03677    /* Default prediction */
03678    if (f->frametype == AST_FRAME_VOICE) {
03679       pred = rtp->lastts + f->samples;
03680 
03681       /* Re-calculate last TS */
03682       rtp->lastts = rtp->lastts + ms * rate;
03683       if (ast_tvzero(f->delivery)) {
03684          /* If this isn't an absolute delivery time, Check if it is close to our prediction, 
03685             and if so, go with our prediction */
03686          if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
03687             rtp->lastts = pred;
03688          else {
03689             ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
03690             mark = 1;
03691          }
03692       }
03693    } else if (f->frametype == AST_FRAME_VIDEO) {
03694       mark = f->subclass & 0x1;
03695       pred = rtp->lastovidtimestamp + f->samples;
03696       /* Re-calculate last TS */
03697       rtp->lastts = rtp->lastts + ms * 90;
03698       /* If it's close to our prediction, go for it */
03699       if (ast_tvzero(f->delivery)) {
03700          if (abs(rtp->lastts - pred) < 7200) {
03701             rtp->lastts = pred;
03702             rtp->lastovidtimestamp += f->samples;
03703          } else {
03704             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);
03705             rtp->lastovidtimestamp = rtp->lastts;
03706          }
03707       }
03708    } else {
03709       pred = rtp->lastotexttimestamp + f->samples;
03710       /* Re-calculate last TS */
03711       rtp->lastts = rtp->lastts + ms;
03712       /* If it's close to our prediction, go for it */
03713       if (ast_tvzero(f->delivery)) {
03714          if (abs(rtp->lastts - pred) < 7200) {
03715             rtp->lastts = pred;
03716             rtp->lastotexttimestamp += f->samples;
03717          } else {
03718             ast_debug(3, "Difference is %d, ms is %d, pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, rtp->lastts, pred, f->samples);
03719             rtp->lastotexttimestamp = rtp->lastts;
03720          }
03721       }
03722    }
03723 
03724    /* If we have been explicitly told to set the marker bit do so */
03725    if (rtp->set_marker_bit) {
03726       mark = 1;
03727       rtp->set_marker_bit = 0;
03728    }
03729 
03730    /* If the timestamp for non-digit packets has moved beyond the timestamp
03731       for digits, update the digit timestamp.
03732    */
03733    if (rtp->lastts > rtp->lastdigitts)
03734       rtp->lastdigitts = rtp->lastts;
03735 
03736    if (ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO))
03737       rtp->lastts = f->ts * rate;
03738 
03739    /* Get a pointer to the header */
03740    rtpheader = (unsigned char *)(f->data.ptr - hdrlen);
03741 
03742    put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
03743    put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
03744    put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc)); 
03745 
03746    if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
03747       res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
03748       if (res < 0) {
03749          if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
03750             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));
03751          } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
03752             /* Only give this error message once if we are not RTP debugging */
03753             if (option_debug || rtpdebug)
03754                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));
03755             ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
03756          }
03757       } else {
03758          rtp->txcount++;
03759          rtp->txoctetcount +=(res - hdrlen);
03760          
03761          /* Do not schedule RR if RTCP isn't run */
03762          if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
03763             rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
03764          }
03765       }
03766             
03767       if (rtp_debug_test_addr(&rtp->them))
03768          ast_verbose("Sent RTP packet to      %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
03769                ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
03770    }
03771 
03772    rtp->seqno++;
03773 
03774    return 0;
03775 }
03776 
03777 void ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
03778 {
03779    struct ast_format_list current_format_old, current_format_new;
03780 
03781    /* if no packets have been sent through this session yet, then
03782     *  changing preferences does not require any extra work
03783     */
03784    if (rtp->lasttxformat == 0) {
03785       rtp->pref = *prefs;
03786       return;
03787    }
03788 
03789    current_format_old = ast_codec_pref_getsize(&rtp->pref, rtp->lasttxformat);
03790 
03791    rtp->pref = *prefs;
03792 
03793    current_format_new = ast_codec_pref_getsize(&rtp->pref, rtp->lasttxformat);
03794 
03795    /* if the framing desired for the current format has changed, we may have to create
03796     * or adjust the smoother for this session
03797     */
03798    if ((current_format_new.inc_ms != 0) &&
03799        (current_format_new.cur_ms != current_format_old.cur_ms)) {
03800       int new_size = (current_format_new.cur_ms * current_format_new.fr_len) / current_format_new.inc_ms;
03801 
03802       if (rtp->smoother) {
03803          ast_smoother_reconfigure(rtp->smoother, new_size);
03804          if (option_debug) {
03805             ast_log(LOG_DEBUG, "Adjusted smoother to %d ms and %d bytes\n", current_format_new.cur_ms, new_size);
03806          }
03807       } else {
03808          if (!(rtp->smoother = ast_smoother_new(new_size))) {
03809             ast_log(LOG_WARNING, "Unable to create smoother: format: %d ms: %d len: %d\n", rtp->lasttxformat, current_format_new.cur_ms, new_size);
03810             return;
03811          }
03812          if (current_format_new.flags) {
03813             ast_smoother_set_flags(rtp->smoother, current_format_new.flags);
03814          }
03815          if (option_debug) {
03816             ast_log(LOG_DEBUG, "Created smoother: format: %d ms: %d len: %d\n", rtp->lasttxformat, current_format_new.cur_ms, new_size);
03817          }
03818       }
03819    }
03820 
03821 }
03822 
03823 struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
03824 {
03825    return &rtp->pref;
03826 }
03827 
03828 int ast_rtp_codec_getformat(int pt)
03829 {
03830    if (pt < 0 || pt >= MAX_RTP_PT)
03831       return 0; /* bogus payload type */
03832 
03833    if (static_RTP_PT[pt].isAstFormat)
03834       return static_RTP_PT[pt].code;
03835    else
03836       return 0;
03837 }
03838 
03839 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
03840 {
03841    struct ast_frame *f;
03842    int codec;
03843    int hdrlen = 12;
03844    int subclass;
03845    
03846 
03847    /* If we have no peer, return immediately */ 
03848    if (!rtp->them.sin_addr.s_addr)
03849       return 0;
03850 
03851    /* If there is no data length, return immediately */
03852    if (!_f->datalen && !rtp->red)
03853       return 0;
03854    
03855    /* Make sure we have enough space for RTP header */
03856    if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO) && (_f->frametype != AST_FRAME_TEXT)) {
03857       ast_log(LOG_WARNING, "RTP can only send voice, video and text\n");
03858       return -1;
03859    }
03860 
03861    if (rtp->red) {
03862       /* return 0; */
03863       /* no primary data or generations to send */
03864       if ((_f = red_t140_to_red(rtp->red)) == NULL) 
03865          return 0;
03866    }
03867 
03868    /* The bottom bit of a video subclass contains the marker bit */
03869    subclass = _f->subclass;
03870    if (_f->frametype == AST_FRAME_VIDEO)
03871       subclass &= ~0x1;
03872 
03873    codec = ast_rtp_lookup_code(rtp, 1, subclass);
03874    if (codec < 0) {
03875       ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
03876       return -1;
03877    }
03878 
03879    if (rtp->lasttxformat != subclass) {
03880       /* New format, reset the smoother */
03881       ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
03882       rtp->lasttxformat = subclass;
03883       if (rtp->smoother)
03884          ast_smoother_free(rtp->smoother);
03885       rtp->smoother = NULL;
03886    }
03887 
03888    if (!rtp->smoother) {
03889       struct ast_format_list fmt = ast_codec_pref_getsize(&rtp->pref, subclass);
03890 
03891       switch (subclass) {
03892       case AST_FORMAT_SPEEX:
03893       case AST_FORMAT_G723_1:
03894       case AST_FORMAT_SIREN7:
03895       case AST_FORMAT_SIREN14:
03896          /* these are all frame-based codecs and cannot be safely run through
03897             a smoother */
03898          break;
03899       default:
03900          if (fmt.inc_ms) { /* if codec parameters is set / avoid division by zero */
03901             if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
03902                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));
03903                return -1;
03904             }
03905             if (fmt.flags)
03906                ast_smoother_set_flags(rtp->smoother, fmt.flags);
03907             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));
03908          }
03909       }
03910    }
03911    if (rtp->smoother) {
03912       if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
03913          ast_smoother_feed_be(rtp->smoother, _f);
03914       } else {
03915          ast_smoother_feed(rtp->smoother, _f);
03916       }
03917 
03918       while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
03919          ast_rtp_raw_write(rtp, f, codec);
03920       }
03921    } else {
03922       /* Don't buffer outgoing frames; send them one-per-packet: */
03923       if (_f->offset < hdrlen) 
03924          f = ast_frdup(_f);   /*! \bug XXX this might never be free'd. Why do we do this? */
03925       else
03926          f = _f;
03927       if (f->data.ptr)
03928          ast_rtp_raw_write(rtp, f, codec);
03929       if (f != _f)
03930          ast_frfree(f);
03931    }
03932       
03933    return 0;
03934 }
03935 
03936 /*! \brief Unregister interface to channel driver */
03937 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
03938 {
03939    AST_RWLIST_WRLOCK(&protos);
03940    AST_RWLIST_REMOVE(&protos, proto, list);
03941    AST_RWLIST_UNLOCK(&protos);
03942 }
03943 
03944 /*! \brief Register interface to channel driver */
03945 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
03946 {
03947    struct ast_rtp_protocol *cur;
03948 
03949    AST_RWLIST_WRLOCK(&protos);
03950    AST_RWLIST_TRAVERSE(&protos, cur, list) { 
03951       if (!strcmp(cur->type, proto->type)) {
03952          ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
03953          AST_RWLIST_UNLOCK(&protos);
03954          return -1;
03955       }
03956    }
03957    AST_RWLIST_INSERT_HEAD(&protos, proto, list);
03958    AST_RWLIST_UNLOCK(&protos);
03959    
03960    return 0;
03961 }
03962 
03963 /*! \brief Bridge loop for true native bridge (reinvite) */
03964 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)
03965 {
03966    struct ast_frame *fr = NULL;
03967    struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
03968    int oldcodec0 = codec0, oldcodec1 = codec1;
03969    struct sockaddr_in ac1 = {0,}, vac1 = {0,}, tac1 = {0,}, ac0 = {0,}, vac0 = {0,}, tac0 = {0,};
03970    struct sockaddr_in t1 = {0,}, vt1 = {0,}, tt1 = {0,}, t0 = {0,}, vt0 = {0,}, tt0 = {0,};
03971    
03972    /* Set it up so audio goes directly between the two endpoints */
03973 
03974    /* Test the first channel */
03975    if (!(pr0->set_rtp_peer(c0, p1, vp1, tp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))) {
03976       ast_rtp_get_peer(p1, &ac1);
03977       if (vp1)
03978          ast_rtp_get_peer(vp1, &vac1);
03979       if (tp1)
03980          ast_rtp_get_peer(tp1, &tac1);
03981    } else
03982       ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
03983    
03984    /* Test the second channel */
03985    if (!(pr1->set_rtp_peer(c1, p0, vp0, tp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))) {
03986       ast_rtp_get_peer(p0, &ac0);
03987       if (vp0)
03988          ast_rtp_get_peer(vp0, &vac0);
03989       if (tp0)
03990          ast_rtp_get_peer(tp0, &tac0);
03991    } else
03992       ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c1->name, c0->name);
03993 
03994    /* Now we can unlock and move into our loop */
03995    ast_channel_unlock(c0);
03996    ast_channel_unlock(c1);
03997 
03998    ast_poll_channel_add(c0, c1);
03999 
04000    /* Throw our channels into the structure and enter the loop */
04001    cs[0] = c0;
04002    cs[1] = c1;
04003    cs[2] = NULL;
04004    for (;;) {
04005       /* Check if anything changed */
04006       if ((c0->tech_pvt != pvt0) ||
04007           (c1->tech_pvt != pvt1) ||
04008           (c0->masq || c0->masqr || c1->masq || c1->masqr) ||
04009           (c0->monitor || c0->audiohooks || c1->monitor || c1->audiohooks)) {
04010          ast_debug(1, "Oooh, something is weird, backing out\n");
04011          if (c0->tech_pvt == pvt0)
04012             if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
04013                ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
04014          if (c1->tech_pvt == pvt1)
04015             if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
04016                ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
04017          ast_poll_channel_del(c0, c1);
04018          return AST_BRIDGE_RETRY;
04019       }
04020 
04021       /* Check if they have changed their address */
04022       ast_rtp_get_peer(p1, &t1);
04023       if (vp1)
04024          ast_rtp_get_peer(vp1, &vt1);
04025       if (tp1)
04026          ast_rtp_get_peer(tp1, &tt1);
04027       if (pr1->get_codec)
04028          codec1 = pr1->get_codec(c1);
04029       ast_rtp_get_peer(p0, &t0);
04030       if (vp0)
04031          ast_rtp_get_peer(vp0, &vt0);
04032       if (tp0)
04033          ast_rtp_get_peer(tp0, &tt0);
04034       if (pr0->get_codec)
04035          codec0 = pr0->get_codec(c0);
04036       if ((inaddrcmp(&t1, &ac1)) ||
04037           (vp1 && inaddrcmp(&vt1, &vac1)) ||
04038           (tp1 && inaddrcmp(&tt1, &tac1)) ||
04039           (codec1 != oldcodec1)) {
04040          ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
04041             c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
04042          ast_debug(2, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
04043             c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
04044          ast_debug(2, "Oooh, '%s' changed end taddress to %s:%d (format %d)\n",
04045             c1->name, ast_inet_ntoa(tt1.sin_addr), ntohs(tt1.sin_port), codec1);
04046          ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
04047             c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
04048          ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
04049             c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
04050          ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
04051             c1->name, ast_inet_ntoa(tac1.sin_addr), ntohs(tac1.sin_port), oldcodec1);
04052          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)))
04053             ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
04054          memcpy(&ac1, &t1, sizeof(ac1));
04055          memcpy(&vac1, &vt1, sizeof(vac1));
04056          memcpy(&tac1, &tt1, sizeof(tac1));
04057          oldcodec1 = codec1;
04058       }
04059       if ((inaddrcmp(&t0, &ac0)) ||
04060           (vp0 && inaddrcmp(&vt0, &vac0)) ||
04061           (tp0 && inaddrcmp(&tt0, &tac0)) ||
04062           (codec0 != oldcodec0)) {
04063          ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
04064             c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
04065          ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
04066             c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
04067          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)))
04068             ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
04069          memcpy(&ac0, &t0, sizeof(ac0));
04070          memcpy(&vac0, &vt0, sizeof(vac0));
04071          memcpy(&tac0, &tt0, sizeof(tac0));
04072          oldcodec0 = codec0;
04073       }
04074 
04075       /* Wait for frame to come in on the channels */
04076       if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
04077          if (!timeoutms) {
04078             if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
04079                ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
04080             if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
04081                ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
04082             return AST_BRIDGE_RETRY;
04083          }
04084          ast_debug(1, "Ooh, empty read...\n");
04085          if (ast_check_hangup(c0) || ast_check_hangup(c1))
04086             break;
04087          continue;
04088       }
04089       fr = ast_read(who);
04090       other = (who == c0) ? c1 : c0;
04091       if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
04092              (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
04093               ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
04094          /* Break out of bridge */
04095          *fo = fr;
04096          *rc = who;
04097          ast_debug(1, "Oooh, got a %s\n", fr ? "digit" : "hangup");
04098          if (c0->tech_pvt == pvt0)
04099             if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
04100                ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
04101          if (c1->tech_pvt == pvt1)
04102             if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
04103                ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
04104          ast_poll_channel_del(c0, c1);
04105          return AST_BRIDGE_COMPLETE;
04106       } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
04107          if ((fr->subclass == AST_CONTROL_HOLD) ||
04108              (fr->subclass == AST_CONTROL_UNHOLD) ||
04109              (fr->subclass == AST_CONTROL_VIDUPDATE) ||
04110              (fr->subclass == AST_CONTROL_SRCUPDATE) ||
04111              (fr->subclass == AST_CONTROL_T38_PARAMETERS)) {
04112             if (fr->subclass == AST_CONTROL_HOLD) {
04113                /* If we someone went on hold we want the other side to reinvite back to us */
04114                if (who == c0)
04115                   pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0);
04116                else
04117                   pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0);
04118             } else if (fr->subclass == AST_CONTROL_UNHOLD) {
04119                /* If they went off hold they should go back to being direct */
04120                if (who == c0)
04121                   pr1->set_rtp_peer(c1, p0, vp0, tp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE));
04122                else
04123                   pr0->set_rtp_peer(c0, p1, vp1, tp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE));
04124             }
04125             /* Update local address information */
04126             ast_rtp_get_peer(p0, &t0);
04127             memcpy(&ac0, &t0, sizeof(ac0));
04128             ast_rtp_get_peer(p1, &t1);
04129             memcpy(&ac1, &t1, sizeof(ac1));
04130             /* Update codec information */
04131             if (pr0->get_codec && c0->tech_pvt)
04132                oldcodec0 = codec0 = pr0->get_codec(c0);
04133             if (pr1->get_codec && c1->tech_pvt)
04134                oldcodec1 = codec1 = pr1->get_codec(c1);
04135             ast_indicate_data(other, fr->subclass, fr->data.ptr, fr->datalen);
04136             ast_frfree(fr);
04137          } else {
04138             *fo = fr;
04139             *rc = who;
04140             ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
04141             return AST_BRIDGE_COMPLETE;
04142          }
04143       } else {
04144          if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
04145              (fr->frametype == AST_FRAME_DTMF_END) ||
04146              (fr->frametype == AST_FRAME_VOICE) ||
04147              (fr->frametype == AST_FRAME_VIDEO) ||
04148              (fr->frametype == AST_FRAME_IMAGE) ||
04149              (fr->frametype == AST_FRAME_HTML) ||
04150              (fr->frametype == AST_FRAME_MODEM) ||
04151              (fr->frametype == AST_FRAME_TEXT)) {
04152             ast_write(other, fr);
04153          }
04154          ast_frfree(fr);
04155       }
04156       /* Swap priority */
04157 #ifndef HAVE_EPOLL
04158       cs[2] = cs[0];
04159       cs[0] = cs[1];
04160       cs[1] = cs[2];
04161 #endif
04162    }
04163 
04164    ast_poll_channel_del(c0, c1);
04165 
04166    if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
04167       ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
04168    if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
04169       ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
04170 
04171    return AST_BRIDGE_FAILED;
04172 }
04173 
04174 /*! \brief P2P RTP Callback */
04175 #ifdef P2P_INTENSE
04176 static int p2p_rtp_callback(int *id, int fd, short events, void *cbdata)
04177 {
04178    int res = 0, hdrlen = 12;
04179    struct sockaddr_in sin;
04180    socklen_t len;
04181    unsigned int *header;
04182    struct ast_rtp *rtp = cbdata, *bridged = NULL;
04183 
04184    if (!rtp)
04185       return 1;
04186 
04187    len = sizeof(sin);
04188    if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
04189       return 1;
04190 
04191    header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
04192    
04193    /* If NAT support is turned on, then see if we need to change their address */
04194    if ((rtp->nat) && 
04195        ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
04196         (rtp->them.sin_port != sin.sin_port))) {
04197       rtp->them = sin;
04198       rtp->rxseqno = 0;
04199       ast_set_flag(rtp, FLAG_NAT_ACTIVE);
04200       if (option_debug || rtpdebug)
04201          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));
04202    }
04203 
04204    /* Write directly out to other RTP stream if bridged */
04205    if ((bridged = ast_rtp_get_bridged(rtp)))
04206       bridge_p2p_rtp_write(rtp, bridged, header, res, hdrlen);
04207    
04208    return 1;
04209 }
04210 
04211 /*! \brief Helper function to switch a channel and RTP stream into callback mode */
04212 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
04213 {
04214    /* If we need DTMF, are looking for STUN, or we have no IO structure then we can't do direct callback */
04215    if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) || ast_test_flag(rtp, FLAG_HAS_STUN) || !rtp->io)
04216       return 0;
04217 
04218    /* If the RTP structure is already in callback mode, remove it temporarily */
04219    if (rtp->ioid) {
04220       ast_io_remove(rtp->io, rtp->ioid);
04221       rtp->ioid = NULL;
04222    }
04223 
04224    /* Steal the file descriptors from the channel */
04225    chan->fds[0] = -1;
04226 
04227    /* Now, fire up callback mode */
04228    iod[0] = ast_io_add(rtp->io, ast_rtp_fd(rtp), p2p_rtp_callback, AST_IO_IN, rtp);
04229 
04230    return 1;
04231 }
04232 #else
04233 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
04234 {
04235    return 0;
04236 }
04237 #endif
04238 
04239 /*! \brief Helper function to switch a channel and RTP stream out of callback mode */
04240 static int p2p_callback_disable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
04241 {
04242    ast_channel_lock(chan);
04243 
04244    /* Remove the callback from the IO context */
04245    ast_io_remove(rtp->io, iod[0]);
04246 
04247    /* Restore file descriptors */
04248    chan->fds[0] = ast_rtp_fd(rtp);
04249    ast_channel_unlock(chan);
04250 
04251    /* Restore callback mode if previously used */
04252    if (ast_test_flag(rtp, FLAG_CALLBACK_MODE))
04253       rtp->ioid = ast_io_add(rtp->io, ast_rtp_fd(rtp), rtpread, AST_IO_IN, rtp);
04254 
04255    return 0;
04256 }
04257 
04258 /*! \brief Helper function that sets what an RTP structure is bridged to */
04259 static void p2p_set_bridge(struct ast_rtp *rtp0, struct ast_rtp *rtp1)
04260 {
04261    rtp_bridge_lock(rtp0);
04262    rtp0->bridged = rtp1;
04263    rtp_bridge_unlock(rtp0);
04264 }
04265 
04266 /*! \brief Bridge loop for partial native bridge (packet2packet) 
04267 
04268    In p2p mode, Asterisk is a very basic RTP proxy, just forwarding whatever
04269    rtp/rtcp we get in to the channel. 
04270    \note this currently only works for Audio
04271 */
04272 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)
04273 {
04274    struct ast_frame *fr = NULL;
04275    struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
04276    int *p0_iod[2] = {NULL, NULL}, *p1_iod[2] = {NULL, NULL};
04277    int p0_callback = 0, p1_callback = 0;
04278    enum ast_bridge_result res = AST_BRIDGE_FAILED;
04279 
04280    /* Okay, setup each RTP structure to do P2P forwarding */
04281    ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
04282    p2p_set_bridge(p0, p1);
04283    ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
04284    p2p_set_bridge(p1, p0);
04285 
04286    /* Activate callback modes if possible */
04287    p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
04288    p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
04289 
04290    /* Now let go of the channel locks and be on our way */
04291    ast_channel_unlock(c0);
04292    ast_channel_unlock(c1);
04293 
04294    ast_poll_channel_add(c0, c1);
04295 
04296    /* Go into a loop forwarding frames until we don't need to anymore */
04297    cs[0] = c0;
04298    cs[1] = c1;
04299    cs[2] = NULL;
04300    for (;;) {
04301       /* If the underlying formats have changed force this bridge to break */
04302       if ((c0->rawreadformat != c1->rawwriteformat) || (c1->rawreadformat != c0->rawwriteformat)) {
04303          ast_debug(3, "p2p-rtp-bridge: Oooh, formats changed, backing out\n");
04304          res = AST_BRIDGE_FAILED_NOWARN;
04305          break;
04306       }
04307       /* Check if anything changed */
04308       if ((c0->tech_pvt != pvt0) ||
04309           (c1->tech_pvt != pvt1) ||
04310           (c0->masq || c0->masqr || c1->masq || c1->masqr) ||
04311           (c0->monitor || c0->audiohooks || c1->monitor || c1->audiohooks)) {
04312          ast_debug(3, "p2p-rtp-bridge: Oooh, something is weird, backing out\n");
04313          /* 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 */
04314          if ((c0->masq || c0->masqr) && (fr = ast_read(c0)))
04315             ast_frfree(fr);
04316          if ((c1->masq || c1->masqr) && (fr = ast_read(c1)))
04317             ast_frfree(fr);
04318          res = AST_BRIDGE_RETRY;
04319          break;
04320       }
04321       /* Wait on a channel to feed us a frame */
04322       if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
04323          if (!timeoutms) {
04324             res = AST_BRIDGE_RETRY;
04325             break;
04326          }
04327          if (option_debug > 2)
04328             ast_log(LOG_NOTICE, "p2p-rtp-bridge: Ooh, empty read...\n");
04329          if (ast_check_hangup(c0) || ast_check_hangup(c1))
04330             break;
04331          continue;
04332       }
04333       /* Read in frame from channel */
04334       fr = ast_read(who);
04335       other = (who == c0) ? c1 : c0;
04336       /* Depending on the frame we may need to break out of our bridge */
04337       if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
04338              ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
04339              ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
04340          /* Record received frame and who */
04341          *fo = fr;
04342          *rc = who;
04343          ast_debug(3, "p2p-rtp-bridge: Ooh, got a %s\n", fr ? "digit" : "hangup");
04344          res = AST_BRIDGE_COMPLETE;
04345          break;
04346       } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
04347          if ((fr->subclass == AST_CONTROL_HOLD) ||
04348              (fr->subclass == AST_CONTROL_UNHOLD) ||
04349              (fr->subclass == AST_CONTROL_VIDUPDATE) ||
04350              (fr->subclass == AST_CONTROL_SRCUPDATE) ||
04351              (fr->subclass == AST_CONTROL_T38_PARAMETERS)) {
04352             /* If we are going on hold, then break callback mode and P2P bridging */
04353             if (fr->subclass == AST_CONTROL_HOLD) {
04354                if (p0_callback)
04355                   p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
04356                if (p1_callback)
04357                   p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
04358                p2p_set_bridge(p0, NULL);
04359                p2p_set_bridge(p1, NULL);
04360             } else if (fr->subclass == AST_CONTROL_UNHOLD) {
04361                /* If we are off hold, then go back to callback mode and P2P bridging */
04362                ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
04363                p2p_set_bridge(p0, p1);
04364                ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
04365                p2p_set_bridge(p1, p0);
04366                p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
04367                p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
04368             }
04369             ast_indicate_data(other, fr->subclass, fr->data.ptr, fr->datalen);
04370             ast_frfree(fr);
04371          } else {
04372             *fo = fr;
04373             *rc = who;
04374             ast_debug(3, "p2p-rtp-bridge: Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
04375             res = AST_BRIDGE_COMPLETE;
04376             break;
04377          }
04378       } else {
04379          if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
04380              (fr->frametype == AST_FRAME_DTMF_END) ||
04381              (fr->frametype == AST_FRAME_VOICE) ||
04382              (fr->frametype == AST_FRAME_VIDEO) ||
04383              (fr->frametype == AST_FRAME_IMAGE) ||
04384              (fr->frametype == AST_FRAME_HTML) ||
04385              (fr->frametype == AST_FRAME_MODEM) ||
04386              (fr->frametype == AST_FRAME_TEXT)) {
04387             ast_write(other, fr);
04388          }
04389 
04390          ast_frfree(fr);
04391       }
04392       /* Swap priority */
04393 #ifndef HAVE_EPOLL
04394       cs[2] = cs[0];
04395       cs[0] = cs[1];
04396       cs[1] = cs[2];
04397 #endif
04398    }
04399 
04400    /* If we are totally avoiding the core, then restore our link to it */
04401    if (p0_callback)
04402       p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
04403    if (p1_callback)
04404       p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
04405 
04406    /* Break out of the direct bridge */
04407    p2p_set_bridge(p0, NULL);
04408    p2p_set_bridge(p1, NULL);
04409 
04410    ast_poll_channel_del(c0, c1);
04411 
04412    return res;
04413 }
04414 
04415 /*! \page AstRTPbridge The Asterisk RTP bridge 
04416    The RTP bridge is called from the channel drivers that are using the RTP
04417    subsystem in Asterisk - like SIP, H.323 and Jingle/Google Talk.
04418 
04419    This bridge aims to offload the Asterisk server by setting up
04420    the media stream directly between the endpoints, keeping the
04421    signalling in Asterisk.
04422 
04423    It checks with the channel driver, using a callback function, if
04424    there are possibilities for a remote bridge.
04425 
04426    If this fails, the bridge hands off to the core bridge. Reasons
04427    can be NAT support needed, DTMF features in audio needed by
04428    the PBX for transfers or spying/monitoring on channels.
04429 
04430    If transcoding is needed - we can't do a remote bridge.
04431    If only NAT support is needed, we're using Asterisk in
04432    RTP proxy mode with the p2p RTP bridge, basically
04433    forwarding incoming audio packets to the outbound
04434    stream on a network level.
04435 
04436    References:
04437    - ast_rtp_bridge()
04438    - ast_channel_early_bridge()
04439    - ast_channel_bridge()
04440    - rtp.c
04441    - rtp.h
04442 */
04443 /*! \brief Bridge calls. If possible and allowed, initiate
04444    re-invite so the peers exchange media directly outside 
04445    of Asterisk. 
04446 */
04447 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)
04448 {
04449    struct ast_rtp *p0 = NULL, *p1 = NULL;    /* Audio RTP Channels */
04450    struct ast_rtp *vp0 = NULL, *vp1 = NULL;  /* Video RTP channels */
04451    struct ast_rtp *tp0 = NULL, *tp1 = NULL;  /* Text RTP channels */
04452    struct ast_rtp_protocol *pr0 = NULL, *pr1 = NULL;
04453    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;
04454    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;
04455    enum ast_bridge_result res = AST_BRIDGE_FAILED;
04456    int codec0 = 0, codec1 = 0;
04457    void *pvt0 = NULL, *pvt1 = NULL;
04458 
04459    /* Lock channels */
04460    ast_channel_lock(c0);
04461    while (ast_channel_trylock(c1)) {
04462       ast_channel_unlock(c0);
04463       usleep(1);
04464       ast_channel_lock(c0);
04465    }
04466 
04467    /* Ensure neither channel got hungup during lock avoidance */
04468    if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
04469       ast_log(LOG_WARNING, "Got hangup while attempting to bridge '%s' and '%s'\n", c0->name, c1->name);
04470       ast_channel_unlock(c0);
04471       ast_channel_unlock(c1);
04472       return AST_BRIDGE_FAILED;
04473    }
04474       
04475    /* Find channel driver interfaces */
04476    if (!(pr0 = get_proto(c0))) {
04477       ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
04478       ast_channel_unlock(c0);
04479       ast_channel_unlock(c1);
04480       return AST_BRIDGE_FAILED;
04481    }
04482    if (!(pr1 = get_proto(c1))) {
04483       ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
04484       ast_channel_unlock(c0);
04485       ast_channel_unlock(c1);
04486       return AST_BRIDGE_FAILED;
04487    }
04488 
04489    /* Get channel specific interface structures */
04490    pvt0 = c0->tech_pvt;
04491    pvt1 = c1->tech_pvt;
04492 
04493    /* Get audio and video interface (if native bridge is possible) */
04494    audio_p0_res = pr0->get_rtp_info(c0, &p0);
04495    video_p0_res = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
04496    text_p0_res = pr0->get_trtp_info ? pr0->get_trtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
04497    audio_p1_res = pr1->get_rtp_info(c1, &p1);
04498    video_p1_res = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
04499    text_p1_res = pr1->get_trtp_info ? pr1->get_trtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
04500 
04501    /* If we are carrying video, and both sides are not reinviting... then fail the native bridge */
04502    if (video_p0_res != AST_RTP_GET_FAILED && (audio_p0_res != AST_RTP_TRY_NATIVE || video_p0_res != AST_RTP_TRY_NATIVE))
04503       audio_p0_res = AST_RTP_GET_FAILED;
04504    if (video_p1_res != AST_RTP_GET_FAILED && (audio_p1_res != AST_RTP_TRY_NATIVE || video_p1_res != AST_RTP_TRY_NATIVE))
04505       audio_p1_res = AST_RTP_GET_FAILED;
04506 
04507    /* Check if a bridge is possible (partial/native) */
04508    if (audio_p0_res == AST_RTP_GET_FAILED || audio_p1_res == AST_RTP_GET_FAILED) {
04509       /* Somebody doesn't want to play... */
04510       ast_channel_unlock(c0);
04511       ast_channel_unlock(c1);
04512       return AST_BRIDGE_FAILED_NOWARN;
04513    }
04514 
04515    /* If we need to feed DTMF frames into the core then only do a partial native bridge */
04516    if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
04517       ast_set_flag(p0, FLAG_P2P_NEED_DTMF);
04518       audio_p0_res = AST_RTP_TRY_PARTIAL;
04519    }
04520 
04521    if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
04522       ast_set_flag(p1, FLAG_P2P_NEED_DTMF);
04523       audio_p1_res = AST_RTP_TRY_PARTIAL;
04524    }
04525 
04526    /* If both sides are not using the same method of DTMF transmission 
04527     * (ie: one is RFC2833, other is INFO... then we can not do direct media. 
04528     * --------------------------------------------------
04529     * | DTMF Mode |  HAS_DTMF  |  Accepts Begin Frames |
04530     * |-----------|------------|-----------------------|
04531     * | Inband    | False      | True                  |
04532     * | RFC2833   | True       | True                  |
04533     * | SIP INFO  | False      | False                 |
04534     * --------------------------------------------------
04535     * However, if DTMF from both channels is being monitored by the core, then
04536     * we can still do packet-to-packet bridging, because passing through the 
04537     * core will handle DTMF mode translation.
04538     */
04539    if ((ast_test_flag(p0, FLAG_HAS_DTMF) != ast_test_flag(p1, FLAG_HAS_DTMF)) ||
04540       (!c0->tech->send_digit_begin != !c1->tech->send_digit_begin)) {
04541       if (!ast_test_flag(p0, FLAG_P2P_NEED_DTMF) || !ast_test_flag(p1, FLAG_P2P_NEED_DTMF)) {
04542          ast_channel_unlock(c0);
04543          ast_channel_unlock(c1);
04544          return AST_BRIDGE_FAILED_NOWARN;
04545       }
04546       audio_p0_res = AST_RTP_TRY_PARTIAL;
04547       audio_p1_res = AST_RTP_TRY_PARTIAL;
04548    }
04549 
04550    /* If we need to feed frames into the core don't do a P2P bridge */
04551    if ((audio_p0_res == AST_RTP_TRY_PARTIAL && ast_test_flag(p0, FLAG_P2P_NEED_DTMF)) ||
04552        (audio_p1_res == AST_RTP_TRY_PARTIAL && ast_test_flag(p1, FLAG_P2P_NEED_DTMF))) {
04553       ast_channel_unlock(c0);
04554       ast_channel_unlock(c1);
04555       return AST_BRIDGE_FAILED_NOWARN;
04556    }
04557 
04558    /* Get codecs from both sides */
04559    codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
04560    codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
04561    if (codec0 && codec1 && !(codec0 & codec1)) {
04562       /* Hey, we can't do native bridging if both parties speak different codecs */
04563       ast_debug(3, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
04564       ast_channel_unlock(c0);
04565       ast_channel_unlock(c1);
04566       return AST_BRIDGE_FAILED_NOWARN;
04567    }
04568 
04569    /* If either side can only do a partial bridge, then don't try for a true native bridge */
04570    if (audio_p0_res == AST_RTP_TRY_PARTIAL || audio_p1_res == AST_RTP_TRY_PARTIAL) {
04571       struct ast_format_list fmt0, fmt1;
04572 
04573       /* In order to do Packet2Packet bridging both sides must be in the same rawread/rawwrite */
04574       if (c0->rawreadformat != c1->rawwriteformat || c1->rawreadformat != c0->rawwriteformat) {
04575          ast_debug(1, "Cannot packet2packet bridge - raw formats are incompatible\n");
04576          ast_channel_unlock(c0);
04577          ast_channel_unlock(c1);
04578          return AST_BRIDGE_FAILED_NOWARN;
04579       }
04580       /* They must also be using the same packetization */
04581       fmt0 = ast_codec_pref_getsize(&p0->pref, c0->rawreadformat);
04582       fmt1 = ast_codec_pref_getsize(&p1->pref, c1->rawreadformat);
04583       if (fmt0.cur_ms != fmt1.cur_ms) {
04584          ast_debug(1, "Cannot packet2packet bridge - packetization settings prevent it\n");
04585          ast_channel_unlock(c0);
04586          ast_channel_unlock(c1);
04587          return AST_BRIDGE_FAILED_NOWARN;
04588       }
04589 
04590       ast_verb(3, "Packet2Packet bridging %s and %s\n", c0->name, c1->name);
04591       res = bridge_p2p_loop(c0, c1, p0, p1, timeoutms, flags, fo, rc, pvt0, pvt1);
04592    } else {
04593       ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
04594       res = bridge_native_loop(c0, c1, p0, p1, vp0, vp1, tp0, tp1, pr0, pr1, codec0, codec1, timeoutms, flags, fo, rc, pvt0, pvt1);
04595    }
04596 
04597    return res;
04598 }
04599 
04600 static char *rtp_do_debug_ip(struct ast_cli_args *a)
04601 {
04602    struct hostent *hp;
04603    struct ast_hostent ahp;
04604    int port = 0;
04605    char *p, *arg;
04606 
04607    arg = a->argv[4];
04608    p = strstr(arg, ":");
04609    if (p) {
04610       *p = '\0';
04611       p++;
04612       port = atoi(p);
04613    }
04614    hp = ast_gethostbyname(arg, &ahp);
04615    if (hp == NULL) {
04616       ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
04617       return CLI_FAILURE;
04618    }
04619    rtpdebugaddr.sin_family = AF_INET;
04620    memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
04621    rtpdebugaddr.sin_port = htons(port);
04622    if (port == 0) {
04623       ast_cli(a->fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr.sin_addr));
04624     } else {
04625       ast_cli(a->fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr.sin_addr), port);
04626    }
04627    rtpdebug = 1;
04628    return CLI_SUCCESS;
04629 }
04630 
04631 static char *rtcp_do_debug_ip(struct ast_cli_args *a)
04632 {
04633    struct hostent *hp;
04634    struct ast_hostent ahp;
04635    int port = 0;
04636    char *p, *arg;
04637 
04638    arg = a->argv[4];
04639    p = strstr(arg, ":");
04640    if (p) {
04641       *p = '\0';
04642       p++;
04643       port = atoi(p);
04644    }
04645    hp = ast_gethostbyname(arg, &ahp);
04646    if (hp == NULL) {
04647       ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
04648       return CLI_FAILURE;
04649    }
04650    rtcpdebugaddr.sin_family = AF_INET;
04651    memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
04652    rtcpdebugaddr.sin_port = htons(port);
04653    if (port == 0) {
04654       ast_cli(a->fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
04655     } else {
04656       ast_cli(a->fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
04657    }
04658    rtcpdebug = 1;
04659    return CLI_SUCCESS;
04660 }
04661 
04662 static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04663 {
04664    switch (cmd) {
04665    case CLI_INIT:
04666       e->command = "rtp set debug {on|off|ip}";
04667       e->usage =
04668          "Usage: rtp set debug {on|off|ip host[:port]}\n"
04669          "       Enable/Disable dumping of all RTP packets. If 'ip' is\n"
04670          "       specified, limit the dumped packets to those to and from\n"
04671          "       the specified 'host' with optional port.\n";
04672       return NULL;
04673    case CLI_GENERATE:
04674       return NULL;
04675    }
04676 
04677    if (a->argc == e->args) { /* set on or off */
04678       if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
04679          rtpdebug = 1;
04680          memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
04681          ast_cli(a->fd, "RTP Debugging Enabled\n");
04682          return CLI_SUCCESS;
04683       } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
04684          rtpdebug = 0;
04685          ast_cli(a->fd, "RTP Debugging Disabled\n");
04686          return CLI_SUCCESS;
04687       }
04688    } else if (a->argc == e->args +1) { /* ip */
04689       return rtp_do_debug_ip(a);
04690    }
04691 
04692    return CLI_SHOWUSAGE;   /* default, failure */
04693 }
04694 
04695 static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04696 {
04697    switch (cmd) {
04698    case CLI_INIT:
04699       e->command = "rtcp set debug {on|off|ip}";
04700       e->usage =
04701          "Usage: rtcp set debug {on|off|ip host[:port]}\n"
04702          "       Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
04703          "       specified, limit the dumped packets to those to and from\n"
04704          "       the specified 'host' with optional port.\n";
04705       return NULL;
04706    case CLI_GENERATE:
04707       return NULL;
04708    }
04709 
04710    if (a->argc == e->args) { /* set on or off */
04711       if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
04712          rtcpdebug = 1;
04713          memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
04714          ast_cli(a->fd, "RTCP Debugging Enabled\n");
04715          return CLI_SUCCESS;
04716       } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
04717          rtcpdebug = 0;
04718          ast_cli(a->fd, "RTCP Debugging Disabled\n");
04719          return CLI_SUCCESS;
04720       }
04721    } else if (a->argc == e->args +1) { /* ip */
04722       return rtcp_do_debug_ip(a);
04723    }
04724 
04725    return CLI_SHOWUSAGE;   /* default, failure */
04726 }
04727 
04728 static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04729 {
04730    switch (cmd) {
04731    case CLI_INIT:
04732       e->command = "rtcp set stats {on|off}";
04733       e->usage =
04734          "Usage: rtcp set stats {on|off}\n"
04735          "       Enable/Disable dumping of RTCP stats.\n";
04736       return NULL;
04737    case CLI_GENERATE:
04738       return NULL;
04739    }
04740 
04741    if (a->argc != e->args)
04742       return CLI_SHOWUSAGE;
04743 
04744    if (!strncasecmp(a->argv[e->args-1], "on", 2))
04745       rtcpstats = 1;
04746    else if (!strncasecmp(a->argv[e->args-1], "off", 3))
04747       rtcpstats = 0;
04748    else
04749       return CLI_SHOWUSAGE;
04750 
04751    ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
04752    return CLI_SUCCESS;
04753 }
04754 
04755 static char *handle_cli_stun_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
04756 {
04757    switch (cmd) {
04758    case CLI_INIT:
04759       e->command = "stun set debug {on|off}";
04760       e->usage =
04761          "Usage: stun set debug {on|off}\n"
04762          "       Enable/Disable STUN (Simple Traversal of UDP through NATs)\n"
04763          "       debugging\n";
04764       return NULL;
04765    case CLI_GENERATE:
04766       return NULL;
04767    }
04768 
04769    if (a->argc != e->args)
04770       return CLI_SHOWUSAGE;
04771 
04772    if (!strncasecmp(a->argv[e->args-1], "on", 2))
04773       stundebug = 1;
04774    else if (!strncasecmp(a->argv[e->args-1], "off", 3))
04775       stundebug = 0;
04776    else
04777       return CLI_SHOWUSAGE;
04778 
04779    ast_cli(a->fd, "STUN Debugging %s\n", stundebug ? "Enabled" : "Disabled");
04780    return CLI_SUCCESS;
04781 }
04782 
04783 static struct ast_cli_entry cli_rtp[] = {
04784    AST_CLI_DEFINE(handle_cli_rtp_set_debug,  "Enable/Disable RTP debugging"),
04785    AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging"),
04786    AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats"),
04787    AST_CLI_DEFINE(handle_cli_stun_set_debug, "Enable/Disable STUN debugging"),
04788 };
04789 
04790 static int __ast_rtp_reload(int reload)
04791 {
04792    struct ast_config *cfg;
04793    const char *s;
04794    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
04795 
04796    cfg = ast_config_load2("rtp.conf", "rtp", config_flags);
04797    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
04798       return 0;
04799    }
04800 
04801    rtpstart = 5000;
04802    rtpend = 31000;
04803    dtmftimeout = DEFAULT_DTMF_TIMEOUT;
04804    strictrtp = STRICT_RTP_OPEN;
04805    if (cfg) {
04806       if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
04807          rtpstart = atoi(s);
04808          if (rtpstart < 1024)
04809             rtpstart = 1024;
04810          if (rtpstart > 65535)
04811             rtpstart = 65535;
04812       }
04813       if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
04814          rtpend = atoi(s);
04815          if (rtpend < 1024)
04816             rtpend = 1024;
04817          if (rtpend > 65535)
04818             rtpend = 65535;
04819       }
04820       if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
04821          rtcpinterval = atoi(s);
04822          if (rtcpinterval == 0)
04823             rtcpinterval = 0; /* Just so we're clear... it's zero */
04824          if (rtcpinterval < RTCP_MIN_INTERVALMS)
04825             rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
04826          if (rtcpinterval > RTCP_MAX_INTERVALMS)
04827             rtcpinterval = RTCP_MAX_INTERVALMS;
04828       }
04829       if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
04830 #ifdef SO_NO_CHECK
04831          if (ast_false(s))
04832             nochecksums = 1;
04833          else
04834             nochecksums = 0;
04835 #else
04836          if (ast_false(s))
04837             ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
04838 #endif
04839       }
04840       if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
04841          dtmftimeout = atoi(s);
04842          if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
04843             ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
04844                dtmftimeout, DEFAULT_DTMF_TIMEOUT);
04845             dtmftimeout = DEFAULT_DTMF_TIMEOUT;
04846          };
04847       }
04848       if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
04849          strictrtp = ast_true(s);
04850       }
04851       ast_config_destroy(cfg);
04852    }
04853    if (rtpstart >= rtpend) {
04854       ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
04855       rtpstart = 5000;
04856       rtpend = 31000;
04857    }
04858    ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
04859    return 0;
04860 }
04861 
04862 int ast_rtp_reload(void)
04863 {
04864    return __ast_rtp_reload(1);
04865 }
04866 
04867 /*! \brief Initialize the RTP system in Asterisk */
04868 void ast_rtp_init(void)
04869 {
04870    ast_cli_register_multiple(cli_rtp, sizeof(cli_rtp) / sizeof(struct ast_cli_entry));
04871    __ast_rtp_reload(0);
04872 }
04873 
04874 /*! \brief Write t140 redundacy frame 
04875  * \param data primary data to be buffered
04876  */
04877 static int red_write(const void *data)
04878 {
04879    struct ast_rtp *rtp = (struct ast_rtp*) data;
04880    
04881    ast_rtp_write(rtp, &rtp->red->t140); 
04882 
04883    return 1;   
04884 }
04885 
04886 /*! \brief Construct a redundant frame 
04887  * \param red redundant data structure
04888  */
04889 static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
04890    unsigned char *data = red->t140red.data.ptr;
04891    int len = 0;
04892    int i;
04893 
04894    /* replace most aged generation */
04895    if (red->len[0]) {
04896       for (i = 1; i < red->num_gen+1; i++)
04897          len += red->len[i];
04898 
04899       memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len); 
04900    }
04901    
04902    /* Store length of each generation and primary data length*/
04903    for (i = 0; i < red->num_gen; i++)
04904       red->len[i] = red->len[i+1];
04905    red->len[i] = red->t140.datalen;
04906    
04907    /* write each generation length in red header */
04908    len = red->hdrlen;
04909    for (i = 0; i < red->num_gen; i++)
04910       len += data[i*4+3] = red->len[i];
04911    
04912    /* add primary data to buffer */
04913    memcpy(&data[len], red->t140.data.ptr, red->t140.datalen); 
04914    red->t140red.datalen = len + red->t140.datalen;
04915    
04916    /* no primary data and no generations to send */
04917    if (len == red->hdrlen && !red->t140.datalen)
04918       return NULL;
04919 
04920    /* reset t.140 buffer */
04921    red->t140.datalen = 0; 
04922    
04923    return &red->t140red;
04924 }
04925 
04926 /*! \brief Initialize t140 redundancy 
04927  * \param rtp
04928  * \param ti buffer t140 for ti (msecs) before sending redundant frame
04929  * \param red_data_pt Payloadtypes for primary- and generation-data
04930  * \param num_gen numbers of generations (primary generation not encounted)
04931  *
04932 */
04933 int rtp_red_init(struct ast_rtp *rtp, int ti, int *red_data_pt, int num_gen)
04934 {
04935    struct rtp_red *r;
04936    int x;
04937    
04938    if (!(r = ast_calloc(1, sizeof(struct rtp_red))))
04939       return -1;
04940 
04941    r->t140.frametype = AST_FRAME_TEXT;
04942    r->t140.subclass = AST_FORMAT_T140RED;
04943    r->t140.data.ptr = &r->buf_data; 
04944 
04945    r->t140.ts = 0;
04946    r->t140red = r->t140;
04947    r->t140red.data.ptr = &r->t140red_data;
04948    r->t140red.datalen = 0;
04949    r->ti = ti;
04950    r->num_gen = num_gen;
04951    r->hdrlen = num_gen * 4 + 1;
04952    r->prev_ts = 0;
04953 
04954    for (x = 0; x < num_gen; x++) {
04955       r->pt[x] = red_data_pt[x];
04956       r->pt[x] |= 1 << 7; /* mark redundant generations pt */ 
04957       r->t140red_data[x*4] = r->pt[x];
04958    }
04959    r->t140red_data[x*4] = r->pt[x] = red_data_pt[x]; /* primary pt */
04960    r->schedid = ast_sched_add(rtp->sched, ti, red_write, rtp);
04961    rtp->red = r;
04962 
04963    r->t140.datalen = 0;
04964    
04965    return 0;
04966 }
04967 
04968 /*! \brief Buffer t140 from chan_sip
04969  * \param rtp
04970  * \param f frame
04971  */
04972 void red_buffer_t140(struct ast_rtp *rtp, struct ast_frame *f)
04973 {
04974    if (f->datalen > -1) {
04975       struct rtp_red *red = rtp->red;
04976       memcpy(&red->buf_data[red->t140.datalen], f->data.ptr, f->datalen);
04977       red->t140.datalen += f->datalen;
04978       red->t140.ts = f->ts;
04979    }
04980 }