Thu Apr 28 2011 16:56:49

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