Codename Pineapple

Home page | Mailing list | Docs

Last updated: Sat Feb 3 05:00:54 2007

Asterisk developer's documentation :: Codename Pineapple


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: 53128 $")
00032 
00033 #include <stdio.h>
00034 #include <stdlib.h>
00035 #include <string.h>
00036 #include <sys/time.h>
00037 #include <signal.h>
00038 #include <errno.h>
00039 #include <unistd.h>
00040 #include <netinet/in.h>
00041 #include <sys/time.h>
00042 #include <sys/socket.h>
00043 #include <arpa/inet.h>
00044 #include <fcntl.h>
00045 
00046 #include "asterisk/rtp.h"
00047 #include "asterisk/frame.h"
00048 #include "asterisk/logger.h"
00049 #include "asterisk/options.h"
00050 #include "asterisk/channel.h"
00051 #include "asterisk/acl.h"
00052 #include "asterisk/channel.h"
00053 #include "asterisk/config.h"
00054 #include "asterisk/lock.h"
00055 #include "asterisk/utils.h"
00056 #include "asterisk/cli.h"
00057 #include "asterisk/unaligned.h"
00058 #include "asterisk/utils.h"
00059 
00060 #define MAX_TIMESTAMP_SKEW 640
00061 
00062 #define RTP_SEQ_MOD     (1<<16)  /*!< A sequence number can't be more than 16 bits */
00063 #define RTCP_DEFAULT_INTERVALMS   5000 /*!< Default milli-seconds between RTCP reports we send */
00064 #define RTCP_MIN_INTERVALMS       500  /*!< Min milli-seconds between RTCP reports we send */
00065 #define RTCP_MAX_INTERVALMS       60000   /*!< Max milli-seconds between RTCP reports we send */
00066 
00067 #define RTCP_PT_FUR     192
00068 #define RTCP_PT_SR      200
00069 #define RTCP_PT_RR      201
00070 #define RTCP_PT_SDES    202
00071 #define RTCP_PT_BYE     203
00072 #define RTCP_PT_APP     204
00073 
00074 #define RTP_MTU      1200
00075 
00076 #define DEFAULT_DTMF_TIMEOUT 3000   /*!< samples */
00077 
00078 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
00079 
00080 static int rtpstart;       /*!< First port for RTP sessions (set in rtp.conf) */
00081 static int rtpend;         /*!< Last port for RTP sessions (set in rtp.conf) */
00082 static int rtpdebug;       /*!< Are we debugging? */
00083 static int rtcpdebug;         /*!< Are we debugging RTCP? */
00084 static int rtcpstats;         /*!< Are we debugging RTCP? */
00085 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
00086 static int stundebug;         /*!< Are we debugging stun? */
00087 static struct sockaddr_in rtpdebugaddr;   /*!< Debug packets to/from this host */
00088 static struct sockaddr_in rtcpdebugaddr;  /*!< Debug RTCP packets to/from this host */
00089 #ifdef SO_NO_CHECK
00090 static int nochecksums;
00091 #endif
00092 
00093 /* Uncomment this to enable more intense native bridging, but note: this is currently buggy */
00094 /* #define P2P_INTENSE */
00095 
00096 /*!
00097  * \brief Structure representing a RTP session.
00098  *
00099  * 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 [...]"
00100  *
00101  */
00102 /*! \brief The value of each payload format mapping: */
00103 struct rtpPayloadType {
00104    int isAstFormat;  /*!< whether the following code is an AST_FORMAT */
00105    int code;
00106 };
00107 
00108 
00109 /*! \brief RTP session description */
00110 struct ast_rtp {
00111    int s;
00112    struct ast_frame f;
00113    unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
00114    unsigned int ssrc;      /*!< Synchronization source, RFC 3550, page 10. */
00115    unsigned int themssrc;     /*!< Their SSRC */
00116    unsigned int rxssrc;
00117    unsigned int lastts;
00118    unsigned int lastrxts;
00119    unsigned int lastividtimestamp;
00120    unsigned int lastovidtimestamp;
00121    unsigned int lasteventseqn;
00122    int lastrxseqno;                /*!< Last received sequence number */
00123    unsigned short seedrxseqno;     /*!< What sequence number did they start with?*/
00124    unsigned int seedrxts;          /*!< What RTP timestamp did they start with? */
00125    unsigned int rxcount;           /*!< How many packets have we received? */
00126    unsigned int rxoctetcount;      /*!< How many octets have we received? should be rxcount *160*/
00127    unsigned int txcount;           /*!< How many packets have we sent? */
00128    unsigned int txoctetcount;      /*!< How many octets have we sent? (txcount*160)*/
00129    unsigned int cycles;            /*!< Shifted count of sequence number cycles */
00130    double rxjitter;                /*!< Interarrival jitter at the moment */
00131    double rxtransit;               /*!< Relative transit time for previous packet */
00132    int lasttxformat;
00133    int lastrxformat;
00134 
00135    int rtptimeout;         /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
00136    int rtpholdtimeout;     /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
00137    int rtpkeepalive;    /*!< Send RTP comfort noice packets for keepalive */
00138 
00139    /* DTMF Reception Variables */
00140    char resp;
00141    unsigned int lasteventendseqn;
00142    int dtmfcount;
00143    unsigned int dtmfsamples;
00144    /* DTMF Transmission Variables */
00145    unsigned int lastdigitts;
00146    char sending_digit;  /* boolean - are we sending digits */
00147    char send_digit;  /* digit we are sending */
00148    int send_payload;
00149    int send_duration;
00150    int nat;
00151    unsigned int flags;
00152    struct sockaddr_in us;     /*!< Socket representation of the local endpoint. */
00153    struct sockaddr_in them;   /*!< Socket representation of the remote endpoint. */
00154    struct timeval rxcore;
00155    struct timeval txcore;
00156    double drxcore;                 /*!< The double representation of the first received packet */
00157    struct timeval lastrx;          /*!< timeval when we last received a packet */
00158    struct timeval dtmfmute;
00159    struct ast_smoother *smoother;
00160    int *ioid;
00161    unsigned short seqno;      /*!< Sequence number, RFC 3550, page 13. */
00162    unsigned short rxseqno;
00163    struct sched_context *sched;
00164    struct io_context *io;
00165    void *data;
00166    ast_rtp_callback callback;
00167 #ifdef P2P_INTENSE
00168    ast_mutex_t bridge_lock;
00169 #endif
00170    struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
00171    int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
00172    int rtp_lookup_code_cache_code;
00173    int rtp_lookup_code_cache_result;
00174    struct ast_rtcp *rtcp;
00175    struct ast_codec_pref pref;
00176    struct ast_rtp *bridged;        /*!< Who we are Packet bridged to */
00177 };
00178 
00179 /* Forward declarations */
00180 static int ast_rtcp_write(void *data);
00181 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
00182 static int ast_rtcp_write_sr(void *data);
00183 static int ast_rtcp_write_rr(void *data);
00184 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
00185 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
00186 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
00187 
00188 #define FLAG_3389_WARNING     (1 << 0)
00189 #define FLAG_NAT_ACTIVE       (3 << 1)
00190 #define FLAG_NAT_INACTIVE     (0 << 1)
00191 #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
00192 #define FLAG_HAS_DTMF         (1 << 3)
00193 #define FLAG_P2P_SENT_MARK              (1 << 4)
00194 #define FLAG_P2P_NEED_DTMF              (1 << 5)
00195 #define FLAG_CALLBACK_MODE              (1 << 6)
00196 #define FLAG_DTMF_COMPENSATE            (1 << 7)
00197 #define FLAG_HAS_STUN                   (1 << 8)
00198 
00199 /*!
00200  * \brief Structure defining an RTCP session.
00201  * 
00202  * The concept "RTCP session" is not defined in RFC 3550, but since 
00203  * this structure is analogous to ast_rtp, which tracks a RTP session, 
00204  * it is logical to think of this as a RTCP session.
00205  *
00206  * RTCP packet is defined on page 9 of RFC 3550.
00207  * 
00208  */
00209 struct ast_rtcp {
00210    int s;            /*!< Socket */
00211    struct sockaddr_in us;     /*!< Socket representation of the local endpoint. */
00212    struct sockaddr_in them;   /*!< Socket representation of the remote endpoint. */
00213    unsigned int soc;    /*!< What they told us */
00214    unsigned int spc;    /*!< What they told us */
00215    unsigned int themrxlsr;    /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
00216    struct timeval rxlsr;      /*!< Time when we got their last SR */
00217    struct timeval txlsr;      /*!< Time when we sent or last SR*/
00218    unsigned int expected_prior;  /*!< no. packets in previous interval */
00219    unsigned int received_prior;  /*!< no. packets received in previous interval */
00220    int schedid;         /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
00221    unsigned int rr_count;     /*!< number of RRs we've sent, not including report blocks in SR's */
00222    unsigned int sr_count;     /*!< number of SRs we've sent */
00223    unsigned int lastsrtxcount;     /*!< Transmit packet count when last SR sent */
00224    double accumulated_transit;   /*!< accumulated a-dlsr-lsr */
00225    double rtt;       /*!< Last reported rtt */
00226    unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
00227    unsigned int reported_lost;   /*!< Reported lost packets in their RR */
00228    char quality[AST_MAX_USER_FIELD];
00229    double maxrxjitter;
00230    double minrxjitter;
00231    double maxrtt;
00232    double minrtt;
00233    int sendfur;
00234 };
00235 
00236 
00237 typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
00238 
00239 /* XXX Maybe stun belongs in another file if it ever has use outside of RTP */
00240 struct stun_header {
00241    unsigned short msgtype;
00242    unsigned short msglen;
00243    stun_trans_id  id;
00244    unsigned char ies[0];
00245 } __attribute__((packed));
00246 
00247 struct stun_attr {
00248    unsigned short attr;
00249    unsigned short len;
00250    unsigned char value[0];
00251 } __attribute__((packed));
00252 
00253 struct stun_addr {
00254    unsigned char unused;
00255    unsigned char family;
00256    unsigned short port;
00257    unsigned int addr;
00258 } __attribute__((packed));
00259 
00260 #define STUN_IGNORE     (0)
00261 #define STUN_ACCEPT     (1)
00262 
00263 #define STUN_BINDREQ 0x0001
00264 #define STUN_BINDRESP   0x0101
00265 #define STUN_BINDERR 0x0111
00266 #define STUN_SECREQ  0x0002
00267 #define STUN_SECRESP 0x0102
00268 #define STUN_SECERR  0x0112
00269 
00270 #define STUN_MAPPED_ADDRESS   0x0001
00271 #define STUN_RESPONSE_ADDRESS 0x0002
00272 #define STUN_CHANGE_REQUEST   0x0003
00273 #define STUN_SOURCE_ADDRESS   0x0004
00274 #define STUN_CHANGED_ADDRESS  0x0005
00275 #define STUN_USERNAME      0x0006
00276 #define STUN_PASSWORD      0x0007
00277 #define STUN_MESSAGE_INTEGRITY   0x0008
00278 #define STUN_ERROR_CODE    0x0009
00279 #define STUN_UNKNOWN_ATTRIBUTES  0x000a
00280 #define STUN_REFLECTED_FROM   0x000b
00281 
00282 static const char *stun_msg2str(int msg)
00283 {
00284    switch (msg) {
00285    case STUN_BINDREQ:
00286       return "Binding Request";
00287    case STUN_BINDRESP:
00288       return "Binding Response";
00289    case STUN_BINDERR:
00290       return "Binding Error Response";
00291    case STUN_SECREQ:
00292       return "Shared Secret Request";
00293    case STUN_SECRESP:
00294       return "Shared Secret Response";
00295    case STUN_SECERR:
00296       return "Shared Secret Error Response";
00297    }
00298    return "Non-RFC3489 Message";
00299 }
00300 
00301 static const char *stun_attr2str(int msg)
00302 {
00303    switch (msg) {
00304    case STUN_MAPPED_ADDRESS:
00305       return "Mapped Address";
00306    case STUN_RESPONSE_ADDRESS:
00307       return "Response Address";
00308    case STUN_CHANGE_REQUEST:
00309       return "Change Request";
00310    case STUN_SOURCE_ADDRESS:
00311       return "Source Address";
00312    case STUN_CHANGED_ADDRESS:
00313       return "Changed Address";
00314    case STUN_USERNAME:
00315       return "Username";
00316    case STUN_PASSWORD:
00317       return "Password";
00318    case STUN_MESSAGE_INTEGRITY:
00319       return "Message Integrity";
00320    case STUN_ERROR_CODE:
00321       return "Error Code";
00322    case STUN_UNKNOWN_ATTRIBUTES:
00323       return "Unknown Attributes";
00324    case STUN_REFLECTED_FROM:
00325       return "Reflected From";
00326    }
00327    return "Non-RFC3489 Attribute";
00328 }
00329 
00330 struct stun_state {
00331    const char *username;
00332    const char *password;
00333 };
00334 
00335 static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
00336 {
00337    if (stundebug)
00338       ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
00339              stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
00340    switch (ntohs(attr->attr)) {
00341    case STUN_USERNAME:
00342       state->username = (const char *) (attr->value);
00343       break;
00344    case STUN_PASSWORD:
00345       state->password = (const char *) (attr->value);
00346       break;
00347    default:
00348       if (stundebug)
00349          ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n", 
00350                 stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
00351    }
00352    return 0;
00353 }
00354 
00355 static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
00356 {
00357    int size = sizeof(**attr) + strlen(s);
00358    if (*left > size) {
00359       (*attr)->attr = htons(attrval);
00360       (*attr)->len = htons(strlen(s));
00361       memcpy((*attr)->value, s, strlen(s));
00362       (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
00363       *len += size;
00364       *left -= size;
00365    }
00366 }
00367 
00368 static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
00369 {
00370    int size = sizeof(**attr) + 8;
00371    struct stun_addr *addr;
00372    if (*left > size) {
00373       (*attr)->attr = htons(attrval);
00374       (*attr)->len = htons(8);
00375       addr = (struct stun_addr *)((*attr)->value);
00376       addr->unused = 0;
00377       addr->family = 0x01;
00378       addr->port = sin->sin_port;
00379       addr->addr = sin->sin_addr.s_addr;
00380       (*attr) = (struct stun_attr *)((*attr)->value + 8);
00381       *len += size;
00382       *left -= size;
00383    }
00384 }
00385 
00386 static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
00387 {
00388    return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
00389             (struct sockaddr *)dst, sizeof(*dst));
00390 }
00391 
00392 static void stun_req_id(struct stun_header *req)
00393 {
00394    int x;
00395    for (x = 0; x < 4; x++)
00396       req->id.id[x] = ast_random();
00397 }
00398 
00399 size_t ast_rtp_alloc_size(void)
00400 {
00401    return sizeof(struct ast_rtp);
00402 }
00403 
00404 void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
00405 {
00406    struct stun_header *req;
00407    unsigned char reqdata[1024];
00408    int reqlen, reqleft;
00409    struct stun_attr *attr;
00410    
00411    req = (struct stun_header *)reqdata;
00412    stun_req_id(req);
00413    reqlen = 0;
00414    reqleft = sizeof(reqdata) - sizeof(struct stun_header);
00415    req->msgtype = 0;
00416    req->msglen = 0;
00417    attr = (struct stun_attr *)req->ies;
00418    if (username)
00419       append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
00420    req->msglen = htons(reqlen);
00421    req->msgtype = htons(STUN_BINDREQ);
00422    stun_send(rtp->s, suggestion, req);
00423 }
00424 
00425 static int stun_handle_packet(int s, struct sockaddr_in *src, unsigned char *data, size_t len)
00426 {
00427    struct stun_header *resp, *hdr = (struct stun_header *)data;
00428    struct stun_attr *attr;
00429    struct stun_state st;
00430    int ret = STUN_IGNORE;  
00431    unsigned char respdata[1024];
00432    int resplen, respleft;
00433    
00434    if (len < sizeof(struct stun_header)) {
00435       if (option_debug)
00436          ast_log(LOG_DEBUG, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
00437       return -1;
00438    }
00439    if (stundebug)
00440       ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), ntohs(hdr->msglen));
00441    if (ntohs(hdr->msglen) > len - sizeof(struct stun_header)) {
00442       if (option_debug)
00443          ast_log(LOG_DEBUG, "Scrambled STUN packet length (got %d, expecting %d)\n", ntohs(hdr->msglen), (int)(len - sizeof(struct stun_header)));
00444    } else
00445       len = ntohs(hdr->msglen);
00446    data += sizeof(struct stun_header);
00447    memset(&st, 0, sizeof(st));
00448    while (len) {
00449       if (len < sizeof(struct stun_attr)) {
00450          if (option_debug)
00451             ast_log(LOG_DEBUG, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
00452          break;
00453       }
00454       attr = (struct stun_attr *)data;
00455       if (ntohs(attr->len) > len) {
00456          if (option_debug)
00457             ast_log(LOG_DEBUG, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", ntohs(attr->len), (int)len);
00458          break;
00459       }
00460       if (stun_process_attr(&st, attr)) {
00461          if (option_debug)
00462             ast_log(LOG_DEBUG, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
00463          break;
00464       }
00465       /* Clear attribute in case previous entry was a string */
00466       attr->attr = 0;
00467       data += ntohs(attr->len) + sizeof(struct stun_attr);
00468       len -= ntohs(attr->len) + sizeof(struct stun_attr);
00469    }
00470    /* Null terminate any string */
00471    *data = '\0';
00472    resp = (struct stun_header *)respdata;
00473    resplen = 0;
00474    respleft = sizeof(respdata) - sizeof(struct stun_header);
00475    resp->id = hdr->id;
00476    resp->msgtype = 0;
00477    resp->msglen = 0;
00478    attr = (struct stun_attr *)resp->ies;
00479    if (!len) {
00480       switch (ntohs(hdr->msgtype)) {
00481       case STUN_BINDREQ:
00482          if (stundebug)
00483             ast_verbose("STUN Bind Request, username: %s\n", 
00484                    st.username ? st.username : "<none>");
00485          if (st.username)
00486             append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
00487          append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
00488          resp->msglen = htons(resplen);
00489          resp->msgtype = htons(STUN_BINDRESP);
00490          stun_send(s, src, resp);
00491          ret = STUN_ACCEPT;
00492          break;
00493       default:
00494          if (stundebug)
00495             ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
00496       }
00497    }
00498    return ret;
00499 }
00500 
00501 /*! \brief List of current sessions */
00502 static AST_RWLIST_HEAD_STATIC(protos, ast_rtp_protocol);
00503 
00504 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
00505 {
00506    unsigned int sec, usec, frac;
00507    sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
00508    usec = tv.tv_usec;
00509    frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
00510    *msw = sec;
00511    *lsw = frac;
00512 }
00513 
00514 int ast_rtp_fd(struct ast_rtp *rtp)
00515 {
00516    return rtp->s;
00517 }
00518 
00519 int ast_rtcp_fd(struct ast_rtp *rtp)
00520 {
00521    if (rtp->rtcp)
00522       return rtp->rtcp->s;
00523    return -1;
00524 }
00525 
00526 unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
00527 {
00528    unsigned int interval;
00529    /*! \todo XXX Do a more reasonable calculation on this one
00530     * Look in RFC 3550 Section A.7 for an example*/
00531    interval = rtcpinterval;
00532    return interval;
00533 }
00534 
00535 /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
00536 void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
00537 {
00538    rtp->rtptimeout = (-1) * rtp->rtptimeout;
00539    rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
00540 }
00541 
00542 /*! \brief Set rtp timeout */
00543 void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
00544 {
00545    rtp->rtptimeout = timeout;
00546 }
00547 
00548 /*! \brief Set rtp hold timeout */
00549 void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
00550 {
00551    rtp->rtpholdtimeout = timeout;
00552 }
00553 
00554 /*! \brief set RTP keepalive interval */
00555 void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
00556 {
00557    rtp->rtpkeepalive = period;
00558 }
00559 
00560 /*! \brief Get rtp timeout */
00561 int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
00562 {
00563    if (rtp->rtptimeout < 0)   /* We're not checking, but remembering the setting (during T.38 transmission) */
00564       return 0;
00565    return rtp->rtptimeout;
00566 }
00567 
00568 /*! \brief Get rtp hold timeout */
00569 int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
00570 {
00571    if (rtp->rtptimeout < 0)   /* We're not checking, but remembering the setting (during T.38 transmission) */
00572       return 0;
00573    return rtp->rtpholdtimeout;
00574 }
00575 
00576 /*! \brief Get RTP keepalive interval */
00577 int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
00578 {
00579    return rtp->rtpkeepalive;
00580 }
00581 
00582 void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
00583 {
00584    rtp->data = data;
00585 }
00586 
00587 void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
00588 {
00589    rtp->callback = callback;
00590 }
00591 
00592 void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
00593 {
00594    rtp->nat = nat;
00595 }
00596 
00597 int ast_rtp_getnat(struct ast_rtp *rtp)
00598 {
00599    return ast_test_flag(rtp, FLAG_NAT_ACTIVE);
00600 }
00601 
00602 void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
00603 {
00604    ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
00605 }
00606 
00607 void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
00608 {
00609    ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
00610 }
00611 
00612 void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
00613 {
00614    ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
00615 }
00616 
00617 static void rtp_bridge_lock(struct ast_rtp *rtp)
00618 {
00619 #ifdef P2P_INTENSE
00620    ast_mutex_lock(&rtp->bridge_lock);
00621 #endif
00622    return;
00623 }
00624 
00625 static void rtp_bridge_unlock(struct ast_rtp *rtp)
00626 {
00627 #ifdef P2P_INTENSE
00628    ast_mutex_unlock(&rtp->bridge_lock);
00629 #endif
00630    return;
00631 }
00632 
00633 static struct ast_frame *send_dtmf(struct ast_rtp *rtp, enum ast_frame_type type)
00634 {
00635    if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
00636         (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
00637       if (option_debug)
00638          ast_log(LOG_DEBUG, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
00639       rtp->resp = 0;
00640       rtp->dtmfsamples = 0;
00641       return &ast_null_frame;
00642    }
00643    if (option_debug)
00644       ast_log(LOG_DEBUG, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
00645    if (rtp->resp == 'X') {
00646       rtp->f.frametype = AST_FRAME_CONTROL;
00647       rtp->f.subclass = AST_CONTROL_FLASH;
00648    } else {
00649       rtp->f.frametype = type;
00650       rtp->f.subclass = rtp->resp;
00651    }
00652    rtp->f.datalen = 0;
00653    rtp->f.samples = 0;
00654    rtp->f.mallocd = 0;
00655    rtp->f.src = "RTP";
00656    return &rtp->f;
00657    
00658 }
00659 
00660 static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
00661 {
00662    if (rtpdebug == 0)
00663       return 0;
00664    if (rtpdebugaddr.sin_addr.s_addr) {
00665       if (((ntohs(rtpdebugaddr.sin_port) != 0)
00666            && (rtpdebugaddr.sin_port != addr->sin_port))
00667           || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
00668          return 0;
00669    }
00670    return 1;
00671 }
00672 
00673 static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
00674 {
00675    if (rtcpdebug == 0)
00676       return 0;
00677    if (rtcpdebugaddr.sin_addr.s_addr) {
00678       if (((ntohs(rtcpdebugaddr.sin_port) != 0)
00679            && (rtcpdebugaddr.sin_port != addr->sin_port))
00680           || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
00681          return 0;
00682    }
00683    return 1;
00684 }
00685 
00686 
00687 static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
00688 {
00689    unsigned int event;
00690    char resp = 0;
00691    struct ast_frame *f = NULL;
00692    unsigned char seq;
00693    unsigned int flags;
00694    unsigned int power;
00695 
00696    /* We should have at least 4 bytes in RTP data */
00697    if (len < 4)
00698       return f;
00699 
00700    /* The format of Cisco RTP DTMF packet looks like next:
00701       +0          - sequence number of DTMF RTP packet (begins from 1,
00702                     wrapped to 0)
00703       +1          - set of flags
00704       +1 (bit 0)     - flaps by different DTMF digits delimited by audio
00705                     or repeated digit without audio???
00706       +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
00707                     then falls to 0 at its end)
00708       +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
00709       Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
00710       by each new packet and thus provides some redudancy.
00711       
00712       Sample of Cisco RTP DTMF packet is (all data in hex):
00713          19 07 00 02 12 02 20 02
00714       showing end of DTMF digit '2'.
00715 
00716       The packets
00717          27 07 00 02 0A 02 20 02
00718          28 06 20 02 00 02 0A 02
00719       shows begin of new digit '2' with very short pause (20 ms) after
00720       previous digit '2'. Bit +1.0 flips at begin of new digit.
00721       
00722       Cisco RTP DTMF packets comes as replacement of audio RTP packets
00723       so its uses the same sequencing and timestamping rules as replaced
00724       audio packets. Repeat interval of DTMF packets is 20 ms and not rely
00725       on audio framing parameters. Marker bit isn't used within stream of
00726       DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
00727       are not sequential at borders between DTMF and audio streams,
00728    */
00729 
00730    seq = data[0];
00731    flags = data[1];
00732    power = data[2];
00733    event = data[3] & 0x1f;
00734 
00735    if (option_debug > 2 || rtpdebug)
00736       ast_log(LOG_DEBUG, "Cisco DTMF Digit: %02x (len=%d, seq=%d, flags=%02x, power=%d, history count=%d)\n", event, len, seq, flags, power, (len - 4) / 2);
00737    if (event < 10) {
00738       resp = '0' + event;
00739    } else if (event < 11) {
00740       resp = '*';
00741    } else if (event < 12) {
00742       resp = '#';
00743    } else if (event < 16) {
00744       resp = 'A' + (event - 12);
00745    } else if (event < 17) {
00746       resp = 'X';
00747    }
00748    if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
00749       rtp->resp = resp;
00750       /* Why we should care on DTMF compensation at reception? */
00751       if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
00752          f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
00753          rtp->dtmfsamples = 0;
00754       }
00755    } else if ((rtp->resp == resp) && !power) {
00756       f = send_dtmf(rtp, AST_FRAME_DTMF_END);
00757       f->samples = rtp->dtmfsamples * 8;
00758       rtp->resp = 0;
00759    } else if (rtp->resp == resp)
00760       rtp->dtmfsamples += 20 * 8;
00761    rtp->dtmfcount = dtmftimeout;
00762    return f;
00763 }
00764 
00765 /*! 
00766  * \brief Process RTP DTMF and events according to RFC 2833.
00767  * 
00768  * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
00769  * 
00770  * \param rtp
00771  * \param data
00772  * \param len
00773  * \param seqno
00774  * \returns
00775  */
00776 static struct ast_frame *process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno)
00777 {
00778    unsigned int event;
00779    unsigned int event_end;
00780    unsigned int samples;
00781    char resp = 0;
00782    struct ast_frame *f = NULL;
00783 
00784    /* Figure out event, event end, and samples */
00785    event = ntohl(*((unsigned int *)(data)));
00786    event >>= 24;
00787    event_end = ntohl(*((unsigned int *)(data)));
00788    event_end <<= 8;
00789    event_end >>= 24;
00790    samples = ntohl(*((unsigned int *)(data)));
00791    samples &= 0xFFFF;
00792 
00793    /* Print out debug if turned on */
00794    if (rtpdebug || option_debug > 2)
00795       ast_log(LOG_DEBUG, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
00796 
00797    /* Figure out what digit was pressed */
00798    if (event < 10) {
00799       resp = '0' + event;
00800    } else if (event < 11) {
00801       resp = '*';
00802    } else if (event < 12) {
00803       resp = '#';
00804    } else if (event < 16) {
00805       resp = 'A' + (event - 12);
00806    } else if (event < 17) {   /* Event 16: Hook flash */
00807       resp = 'X'; 
00808    }
00809    
00810    if ((!(rtp->resp) && (!(event_end & 0x80))) || (rtp->resp && rtp->resp != resp)) {
00811       rtp->resp = resp;
00812       if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE))
00813          f = send_dtmf(rtp, AST_FRAME_DTMF_BEGIN);
00814    } else if (event_end & 0x80 && rtp->lasteventendseqn != seqno && rtp->resp) {
00815       f = send_dtmf(rtp, AST_FRAME_DTMF_END);
00816       f->len = ast_tvdiff_ms(ast_samp2tv(samples, 8000), ast_tv(0, 0)); /* XXX hard coded 8kHz */
00817       rtp->resp = 0;
00818       rtp->lasteventendseqn = seqno;
00819    } else if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && event_end & 0x80 && rtp->lasteventendseqn != seqno) {
00820       rtp->resp = resp;
00821       f = send_dtmf(rtp, AST_FRAME_DTMF_END);
00822       f->len = ast_tvdiff_ms(ast_samp2tv(samples, 8000), ast_tv(0, 0)); /* XXX hard coded 8kHz */
00823       rtp->resp = 0;
00824       rtp->lasteventendseqn = seqno;
00825    }
00826 
00827    rtp->dtmfcount = dtmftimeout;
00828    rtp->dtmfsamples = samples;
00829 
00830    return f;
00831 }
00832 
00833 /*!
00834  * \brief Process Comfort Noise RTP.
00835  * 
00836  * This is incomplete at the moment.
00837  * 
00838 */
00839 static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
00840 {
00841    struct ast_frame *f = NULL;
00842    /* Convert comfort noise into audio with various codecs.  Unfortunately this doesn't
00843       totally help us out becuase we don't have an engine to keep it going and we are not
00844       guaranteed to have it every 20ms or anything */
00845    if (rtpdebug)
00846       ast_log(LOG_DEBUG, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
00847 
00848    if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
00849       ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
00850          ast_inet_ntoa(rtp->them.sin_addr));
00851       ast_set_flag(rtp, FLAG_3389_WARNING);
00852    }
00853    
00854    /* Must have at least one byte */
00855    if (!len)
00856       return NULL;
00857    if (len < 24) {
00858       rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
00859       rtp->f.datalen = len - 1;
00860       rtp->f.offset = AST_FRIENDLY_OFFSET;
00861       memcpy(rtp->f.data, data + 1, len - 1);
00862    } else {
00863       rtp->f.data = NULL;
00864       rtp->f.offset = 0;
00865       rtp->f.datalen = 0;
00866    }
00867    rtp->f.frametype = AST_FRAME_CNG;
00868    rtp->f.subclass = data[0] & 0x7f;
00869    rtp->f.datalen = len - 1;
00870    rtp->f.samples = 0;
00871    rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
00872    f = &rtp->f;
00873    return f;
00874 }
00875 
00876 static int rtpread(int *id, int fd, short events, void *cbdata)
00877 {
00878    struct ast_rtp *rtp = cbdata;
00879    struct ast_frame *f;
00880    f = ast_rtp_read(rtp);
00881    if (f) {
00882       if (rtp->callback)
00883          rtp->callback(rtp, f, rtp->data);
00884    }
00885    return 1;
00886 }
00887 
00888 struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
00889 {
00890    socklen_t len;
00891    int position, i, packetwords;
00892    int res;
00893    struct sockaddr_in sin;
00894    unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
00895    unsigned int *rtcpheader;
00896    int pt;
00897    struct timeval now;
00898    unsigned int length;
00899    int rc;
00900    double rtt = 0;
00901    double a;
00902    double dlsr;
00903    double lsr;
00904    unsigned int msw;
00905    unsigned int lsw;
00906    unsigned int comp;
00907    struct ast_frame *f = &ast_null_frame;
00908    
00909    if (!rtp || !rtp->rtcp)
00910       return &ast_null_frame;
00911 
00912    len = sizeof(sin);
00913    
00914    res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
00915                0, (struct sockaddr *)&sin, &len);
00916    rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
00917    
00918    if (res < 0) {
00919       if (errno != EAGAIN)
00920          ast_log(LOG_WARNING, "RTCP Read error: %s\n", strerror(errno));
00921       if (errno == EBADF)
00922          CRASH;
00923       return &ast_null_frame;
00924    }
00925 
00926    packetwords = res / 4;
00927    
00928    if (rtp->nat) {
00929       /* Send to whoever sent to us */
00930       if ((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
00931           (rtp->rtcp->them.sin_port != sin.sin_port)) {
00932          memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
00933          if (option_debug || rtpdebug)
00934             ast_log(LOG_DEBUG, "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));
00935       }
00936    }
00937 
00938    if (option_debug)
00939       ast_log(LOG_DEBUG, "Got RTCP report of %d bytes\n", res);
00940 
00941    /* Process a compound packet */
00942    position = 0;
00943    while (position < packetwords) {
00944       i = position;
00945       length = ntohl(rtcpheader[i]);
00946       pt = (length & 0xff0000) >> 16;
00947       rc = (length & 0x1f000000) >> 24;
00948       length &= 0xffff;
00949     
00950       if ((i + length) > packetwords) {
00951          ast_log(LOG_WARNING, "RTCP Read too short\n");
00952          return &ast_null_frame;
00953       }
00954       
00955       if (rtcp_debug_test_addr(&sin)) {
00956          ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
00957          ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
00958          ast_verbose("Reception reports: %d\n", rc);
00959          ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
00960       }
00961     
00962       i += 2; /* Advance past header and ssrc */
00963       
00964       switch (pt) {
00965       case RTCP_PT_SR:
00966          gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
00967          rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
00968          rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
00969          rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff) >> 16); /* Going to LSR in RR*/
00970     
00971          if (rtcp_debug_test_addr(&sin)) {
00972             ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
00973             ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
00974             ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
00975          }
00976          i += 5;
00977          if (rc < 1)
00978             break;
00979          /* Intentional fall through */
00980       case RTCP_PT_RR:
00981          /* This is the place to calculate RTT */
00982          /* Don't handle multiple reception reports (rc > 1) yet */
00983          gettimeofday(&now, NULL);
00984          timeval2ntp(now, &msw, &lsw);
00985          /* Use the one we sent them in our SR instead, rtcp->txlsr could have been rewritten if the dlsr is large */
00986          if (ntohl(rtcpheader[i + 4])) { /* We must have the LSR */
00987             comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
00988             a = (double)((comp & 0xffff0000) >> 16) + (double)((double)(comp & 0xffff)/1000000.);
00989             lsr = (double)((ntohl(rtcpheader[i + 4]) & 0xffff0000) >> 16) + (double)((double)(ntohl(rtcpheader[i + 4]) & 0xffff) / 1000000.);
00990             dlsr = (double)(ntohl(rtcpheader[i + 5])/65536.);
00991             rtt = a - dlsr - lsr;
00992             rtp->rtcp->accumulated_transit += rtt;
00993             rtp->rtcp->rtt = rtt;
00994             if (rtp->rtcp->maxrtt<rtt)
00995                rtp->rtcp->maxrtt = rtt;
00996             if (rtp->rtcp->minrtt>rtt)
00997             rtp->rtcp->minrtt = rtt;
00998          }
00999          rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
01000          rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
01001          if (rtcp_debug_test_addr(&sin)) {
01002             ast_verbose("Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
01003             ast_verbose("Packets lost so far: %d\n", rtp->rtcp->reported_lost);
01004             ast_verbose("Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
01005             ast_verbose("Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
01006             ast_verbose("Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
01007             ast_verbose("Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
01008             ast_verbose("DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
01009             if (rtt)
01010                ast_verbose("RTT: %f(sec)\n", rtt);
01011          }
01012          break;
01013       case RTCP_PT_FUR:
01014          if (rtcp_debug_test_addr(&sin))
01015             ast_verbose("Received an RTCP Fast Update Request\n");
01016          rtp->f.frametype = AST_FRAME_CONTROL;
01017          rtp->f.subclass = AST_CONTROL_VIDUPDATE;
01018          rtp->f.datalen = 0;
01019          rtp->f.samples = 0;
01020          rtp->f.mallocd = 0;
01021          rtp->f.src = "RTP";
01022          f = &rtp->f;
01023          break;
01024       case RTCP_PT_SDES:
01025          if (rtcp_debug_test_addr(&sin))
01026             ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
01027          break;
01028       case RTCP_PT_BYE:
01029          if (rtcp_debug_test_addr(&sin))
01030             ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
01031          break;
01032       default:
01033          if (option_debug)
01034             ast_log(LOG_DEBUG, "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));
01035          break;
01036       }
01037       position += (length + 1);
01038    }
01039          
01040    return f;
01041 }
01042 
01043 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
01044 {
01045    struct timeval now;
01046    double transit;
01047    double current_time;
01048    double d;
01049    double dtv;
01050    double prog;
01051    
01052    if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
01053       gettimeofday(&rtp->rxcore, NULL);
01054       rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
01055       /* map timestamp to a real time */
01056       rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
01057       rtp->rxcore.tv_sec -= timestamp / 8000;
01058       rtp->rxcore.tv_usec -= (timestamp % 8000) * 125;
01059       /* Round to 0.1ms for nice, pretty timestamps */
01060       rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
01061       if (rtp->rxcore.tv_usec < 0) {
01062          /* Adjust appropriately if necessary */
01063          rtp->rxcore.tv_usec += 1000000;
01064          rtp->rxcore.tv_sec -= 1;
01065       }
01066    }
01067 
01068    gettimeofday(&now,NULL);
01069    /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
01070    tv->tv_sec = rtp->rxcore.tv_sec + timestamp / 8000;
01071    tv->tv_usec = rtp->rxcore.tv_usec + (timestamp % 8000) * 125;
01072    if (tv->tv_usec >= 1000000) {
01073       tv->tv_usec -= 1000000;
01074       tv->tv_sec += 1;
01075    }
01076    prog = (double)((timestamp-rtp->seedrxts)/8000.);
01077    dtv = (double)rtp->drxcore + (double)(prog);
01078    current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
01079    transit = current_time - dtv;
01080    d = transit - rtp->rxtransit;
01081    rtp->rxtransit = transit;
01082    if (d<0)
01083       d=-d;
01084    rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
01085    if (rtp->rtcp && rtp->rxjitter > rtp->rtcp->maxrxjitter)
01086       rtp->rtcp->maxrxjitter = rtp->rxjitter;
01087    if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
01088       rtp->rtcp->minrxjitter = rtp->rxjitter;
01089 }
01090 
01091 /*! \brief Perform a Packet2Packet RTP write */
01092 static int bridge_p2p_rtp_write(struct ast_rtp *rtp, struct ast_rtp *bridged, unsigned int *rtpheader, int len, int hdrlen)
01093 {
01094    int res = 0, payload = 0, bridged_payload = 0, version, padding, mark, ext;
01095    struct rtpPayloadType rtpPT;
01096    unsigned int seqno;
01097    
01098    /* Get fields from packet */
01099    seqno = ntohl(rtpheader[0]);
01100    version = (seqno & 0xC0000000) >> 30;
01101    payload = (seqno & 0x7f0000) >> 16;
01102    padding = seqno & (1 << 29);
01103    mark = seqno & (1 << 23);
01104    ext = seqno & (1 << 28);
01105    seqno &= 0xffff;
01106 
01107    /* Check what the payload value should be */
01108    rtpPT = ast_rtp_lookup_pt(rtp, payload);
01109 
01110    /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
01111    if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
01112       return -1;
01113 
01114    /* Otherwise adjust bridged payload to match */
01115    bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
01116 
01117    /* If the mark bit has not been sent yet... do it now */
01118    if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
01119       mark = 1;
01120       ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
01121    }
01122 
01123    /* Reconstruct part of the packet */
01124    rtpheader[0] = htonl((version << 30) | (mark << 23) | (bridged_payload << 16) | (seqno));
01125 
01126    /* Send the packet back out */
01127    res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
01128    if (res < 0) {
01129       if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
01130          if (option_debug)
01131             ast_log(LOG_DEBUG, "RTP Transmission error of packet to %s:%d: %s\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), strerror(errno));
01132       } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
01133          if (option_debug || rtpdebug)
01134             ast_log(LOG_DEBUG, "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));
01135          ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
01136       }
01137       return 0;
01138    } else if (rtp_debug_test_addr(&bridged->them))
01139          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);
01140 
01141    return 0;
01142 }
01143 
01144 struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
01145 {
01146    int res;
01147    struct sockaddr_in sin;
01148    socklen_t len;
01149    unsigned int seqno;
01150    int version;
01151    int payloadtype;
01152    int tseqno;
01153    int hdrlen = 12;
01154    int padding;
01155    int mark;
01156    int ext;
01157    unsigned int ssrc;
01158    unsigned int timestamp;
01159    unsigned int *rtpheader;
01160    struct rtpPayloadType rtpPT;
01161    struct ast_rtp *bridged = NULL;
01162    
01163    /* If time is up, kill it */
01164    if (rtp->sending_digit)
01165       ast_rtp_senddigit_continuation(rtp);
01166 
01167    len = sizeof(sin);
01168    
01169    /* Cache where the header will go */
01170    res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
01171                0, (struct sockaddr *)&sin, &len);
01172 
01173    rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
01174    if (res < 0) {
01175       if (errno != EAGAIN)
01176          ast_log(LOG_WARNING, "RTP Read error: %s\n", strerror(errno));
01177       if (errno == EBADF)
01178          CRASH;
01179       return &ast_null_frame;
01180    }
01181    
01182    if (res < hdrlen) {
01183       ast_log(LOG_WARNING, "RTP Read too short\n");
01184       return &ast_null_frame;
01185    }
01186 
01187    /* Get fields */
01188    seqno = ntohl(rtpheader[0]);
01189 
01190    /* Check RTP version */
01191    version = (seqno & 0xC0000000) >> 30;
01192    if (!version) {
01193       if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res) == STUN_ACCEPT) &&
01194          (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
01195          memcpy(&rtp->them, &sin, sizeof(rtp->them));
01196       }
01197       return &ast_null_frame;
01198    }
01199 
01200 #if 0 /* Allow to receive RTP stream with closed transmission path */
01201    /* If we don't have the other side's address, then ignore this */
01202    if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
01203       return &ast_null_frame;
01204 #endif
01205 
01206    /* Send to whoever send to us if NAT is turned on */
01207    if (rtp->nat) {
01208       if ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
01209           (rtp->them.sin_port != sin.sin_port)) {
01210          rtp->them = sin;
01211          if (rtp->rtcp) {
01212             memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
01213             rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
01214          }
01215          rtp->rxseqno = 0;
01216          ast_set_flag(rtp, FLAG_NAT_ACTIVE);
01217          if (option_debug || rtpdebug)
01218             ast_log(LOG_DEBUG, "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));
01219       }
01220    }
01221 
01222    /* If we are bridged to another RTP stream, send direct */
01223    if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
01224       return &ast_null_frame;
01225 
01226    if (version != 2)
01227       return &ast_null_frame;
01228 
01229    payloadtype = (seqno & 0x7f0000) >> 16;
01230    padding = seqno & (1 << 29);
01231    mark = seqno & (1 << 23);
01232    ext = seqno & (1 << 28);
01233    seqno &= 0xffff;
01234    timestamp = ntohl(rtpheader[1]);
01235    ssrc = ntohl(rtpheader[2]);
01236    
01237    if (!mark && rtp->rxssrc && rtp->rxssrc != ssrc) {
01238       if (option_debug || rtpdebug)
01239          ast_log(LOG_DEBUG, "Forcing Marker bit, because SSRC has changed\n");
01240       mark = 1;
01241    }
01242 
01243    rtp->rxssrc = ssrc;
01244    
01245    if (padding) {
01246       /* Remove padding bytes */
01247       res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
01248    }
01249    
01250    if (ext) {
01251       /* RTP Extension present */
01252       hdrlen += 4;
01253       hdrlen += (ntohl(rtpheader[3]) & 0xffff) << 2;
01254       if (option_debug) {
01255          int profile;
01256          profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
01257          if (profile == 0x505a)
01258             ast_log(LOG_DEBUG, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
01259          else
01260             ast_log(LOG_DEBUG, "Found unknown RTP Extensions %x\n", profile);
01261       }
01262    }
01263 
01264    if (res < hdrlen) {
01265       ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
01266       return &ast_null_frame;
01267    }
01268 
01269    rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
01270 
01271    tseqno = rtp->lastrxseqno +1;
01272 
01273    if (rtp->rxcount==1) {
01274       /* This is the first RTP packet successfully received from source */
01275       rtp->seedrxseqno = seqno;
01276    }
01277 
01278    /* Do not schedule RR if RTCP isn't run */
01279    if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
01280       /* Schedule transmission of Receiver Report */
01281       rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
01282    }
01283 
01284    if (tseqno > RTP_SEQ_MOD) { /* if tseqno is greater than RTP_SEQ_MOD it would indicate that the sender cycled */
01285       rtp->cycles += RTP_SEQ_MOD;
01286       ast_verbose("SEQNO cycled: %u\t%d\n", rtp->cycles, seqno);
01287    }
01288 
01289    rtp->lastrxseqno = seqno;
01290    
01291    if (rtp->themssrc==0)
01292       rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
01293    
01294    if (rtp_debug_test_addr(&sin))
01295       ast_verbose("Got  RTP packet from    %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
01296          ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
01297 
01298    rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
01299    if (!rtpPT.isAstFormat) {
01300       struct ast_frame *f = NULL;
01301 
01302       /* This is special in-band data that's not one of our codecs */
01303       if (rtpPT.code == AST_RTP_DTMF) {
01304          /* It's special -- rfc2833 process it */
01305          if (rtp_debug_test_addr(&sin)) {
01306             unsigned char *data;
01307             unsigned int event;
01308             unsigned int event_end;
01309             unsigned int duration;
01310             data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
01311             event = ntohl(*((unsigned int *)(data)));
01312             event >>= 24;
01313             event_end = ntohl(*((unsigned int *)(data)));
01314             event_end <<= 8;
01315             event_end >>= 24;
01316             duration = ntohl(*((unsigned int *)(data)));
01317             duration &= 0xFFFF;
01318             ast_verbose("Got  RTP RFC2833 from   %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
01319          }
01320          f = process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno);
01321       } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
01322          /* It's really special -- process it the Cisco way */
01323          if (rtp->lasteventseqn <= seqno || (rtp->lasteventseqn >= 65530 && seqno <= 6)) {
01324             f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
01325             rtp->lasteventseqn = seqno;
01326          }
01327       } else if (rtpPT.code == AST_RTP_CN) {
01328          /* Comfort Noise */
01329          f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
01330       } else {
01331          ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
01332       }
01333       return f ? f : &ast_null_frame;
01334    }
01335    rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
01336    rtp->f.frametype = (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) ? AST_FRAME_VOICE : AST_FRAME_VIDEO;
01337 
01338    if (!rtp->lastrxts)
01339       rtp->lastrxts = timestamp;
01340 
01341    rtp->rxseqno = seqno;
01342 
01343    /* Record received timestamp as last received now */
01344    rtp->lastrxts = timestamp;
01345 
01346    rtp->f.mallocd = 0;
01347    rtp->f.datalen = res - hdrlen;
01348    rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
01349    rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
01350    if (rtp->f.subclass < AST_FORMAT_MAX_AUDIO) {
01351       rtp->f.samples = ast_codec_get_samples(&rtp->f);
01352       if (rtp->f.subclass == AST_FORMAT_SLINEAR) 
01353          ast_frame_byteswap_be(&rtp->f);
01354       calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
01355       /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
01356       rtp->f.has_timing_info = 1;
01357       rtp->f.ts = timestamp / 8;
01358       rtp->f.len = rtp->f.samples / 8;
01359       rtp->f.seqno = seqno;
01360    } else {
01361       /* Video -- samples is # of samples vs. 90000 */
01362       if (!rtp->lastividtimestamp)
01363          rtp->lastividtimestamp = timestamp;
01364       rtp->f.samples = timestamp - rtp->lastividtimestamp;
01365       rtp->lastividtimestamp = timestamp;
01366       rtp->f.delivery.tv_sec = 0;
01367       rtp->f.delivery.tv_usec = 0;
01368       if (mark)
01369          rtp->f.subclass |= 0x1;
01370       
01371    }
01372    rtp->f.src = "RTP";
01373    return &rtp->f;
01374 }
01375 
01376 /* The following array defines the MIME Media type (and subtype) for each
01377    of our codecs, or RTP-specific data type. */
01378 static struct {
01379    struct rtpPayloadType payloadType;
01380    char* type;
01381    char* subtype;
01382 } mimeTypes[] = {
01383    {{1, AST_FORMAT_G723_1}, "audio", "G723"},
01384    {{1, AST_FORMAT_GSM}, "audio", "GSM"},
01385    {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
01386    {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
01387    {{1, AST_FORMAT_G726}, "audio", "G726-32"},
01388    {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
01389    {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
01390    {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
01391    {{1, AST_FORMAT_G729A}, "audio", "G729"},
01392    {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
01393    {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
01394    {{1, AST_FORMAT_G722}, "audio", "G722"},
01395    {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
01396    {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
01397    {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
01398    {{0, AST_RTP_CN}, "audio", "CN"},
01399    {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
01400    {{1, AST_FORMAT_PNG}, "video", "PNG"},
01401    {{1, AST_FORMAT_H261}, "video", "H261"},
01402    {{1, AST_FORMAT_H263}, "video", "H263"},
01403    {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
01404    {{1, AST_FORMAT_H264}, "video", "H264"},
01405    {{1, AST_FORMAT_MP4_VIDEO}, "video", "MP4V-ES"},
01406    {{1, AST_FORMAT_T140}, "text", "T140"},
01407 };
01408 
01409 /* Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
01410    also, our own choices for dynamic payload types.  This is our master
01411    table for transmission */
01412 static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
01413    [0] = {1, AST_FORMAT_ULAW},
01414 #ifdef USE_DEPRECATED_G726
01415    [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
01416 #endif
01417    [3] = {1, AST_FORMAT_GSM},
01418    [4] = {1, AST_FORMAT_G723_1},
01419    [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
01420    [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
01421    [7] = {1, AST_FORMAT_LPC10},
01422    [8] = {1, AST_FORMAT_ALAW},
01423    [9] = {1, AST_FORMAT_G722},
01424    [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
01425    [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
01426    [13] = {0, AST_RTP_CN},
01427    [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
01428    [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
01429    [18] = {1, AST_FORMAT_G729A},
01430    [19] = {0, AST_RTP_CN},    /* Also used for CN */
01431    [26] = {1, AST_FORMAT_JPEG},
01432    [31] = {1, AST_FORMAT_H261},
01433    [34] = {1, AST_FORMAT_H263},
01434    [97] = {1, AST_FORMAT_ILBC},
01435    [99] = {1, AST_FORMAT_H264},
01436    [101] = {0, AST_RTP_DTMF},
01437    [102] = {1, AST_FORMAT_T140}, /* Real time text chat */
01438    [103] = {1, AST_FORMAT_H263_PLUS},
01439    [104] = {1, AST_FORMAT_MP4_VIDEO},
01440    [110] = {1, AST_FORMAT_SPEEX},
01441    [111] = {1, AST_FORMAT_G726},
01442    [112] = {1, AST_FORMAT_G726_AAL2},
01443    [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
01444 };
01445 
01446 void ast_rtp_pt_clear(struct ast_rtp* rtp) 
01447 {
01448    int i;
01449 
01450    if (!rtp)
01451       return;
01452 
01453    rtp_bridge_lock(rtp);
01454 
01455    for (i = 0; i < MAX_RTP_PT; ++i) {
01456       rtp->current_RTP_PT[i].isAstFormat = 0;
01457       rtp->current_RTP_PT[i].code = 0;
01458    }
01459 
01460    rtp->rtp_lookup_code_cache_isAstFormat = 0;
01461    rtp->rtp_lookup_code_cache_code = 0;
01462    rtp->rtp_lookup_code_cache_result = 0;
01463 
01464    rtp_bridge_unlock(rtp);
01465 }
01466 
01467 void ast_rtp_pt_default(struct ast_rtp* rtp) 
01468 {
01469    int i;
01470 
01471    rtp_bridge_lock(rtp);
01472 
01473    /* Initialize to default payload types */
01474    for (i = 0; i < MAX_RTP_PT; ++i) {
01475       rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
01476       rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
01477    }
01478 
01479    rtp->rtp_lookup_code_cache_isAstFormat = 0;
01480    rtp->rtp_lookup_code_cache_code = 0;
01481    rtp->rtp_lookup_code_cache_result = 0;
01482 
01483    rtp_bridge_unlock(rtp);
01484 }
01485 
01486 void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
01487 {
01488    unsigned int i;
01489 
01490    rtp_bridge_lock(dest);
01491    rtp_bridge_lock(src);
01492 
01493    for (i=0; i < MAX_RTP_PT; ++i) {
01494       dest->current_RTP_PT[i].isAstFormat = 
01495          src->current_RTP_PT[i].isAstFormat;
01496       dest->current_RTP_PT[i].code = 
01497          src->current_RTP_PT[i].code; 
01498    }
01499    dest->rtp_lookup_code_cache_isAstFormat = 0;
01500    dest->rtp_lookup_code_cache_code = 0;
01501    dest->rtp_lookup_code_cache_result = 0;
01502 
01503    rtp_bridge_unlock(src);
01504    rtp_bridge_unlock(dest);
01505 }
01506 
01507 /*! \brief Get channel driver interface structure */
01508 static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
01509 {
01510    struct ast_rtp_protocol *cur = NULL;
01511 
01512    AST_RWLIST_RDLOCK(&protos);
01513    AST_RWLIST_TRAVERSE(&protos, cur, list) {
01514       if (cur->type == chan->tech->type)
01515          break;
01516    }
01517    AST_RWLIST_UNLOCK(&protos);
01518 
01519    return cur;
01520 }
01521 
01522 int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
01523 {
01524    // dest = c0, src = c1
01525    struct ast_rtp *destp = NULL, *srcp = NULL;     /* Audio RTP Channels */
01526    struct ast_rtp *vdestp = NULL, *vsrcp = NULL;      /* Video RTP channels */
01527    struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
01528    enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED;
01529    enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED;
01530    int srccodec, nat_active = 0;
01531 
01532    /* Lock channels */
01533    ast_channel_lock(c0);
01534    if (c1) {
01535       while (ast_channel_trylock(c1)) {
01536          ast_channel_unlock(c0);
01537          usleep(1);
01538          ast_channel_lock(c0);
01539       }
01540    }
01541 
01542    /* Find channel driver interfaces */
01543    destpr = get_proto(c0);
01544    if (c1)
01545       srcpr = get_proto(c1);
01546    if (!destpr) {
01547       if (option_debug)
01548          ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", c0->name);
01549       ast_channel_unlock(c0);
01550       if (c1)
01551          ast_channel_unlock(c1);
01552       return -1;
01553    }
01554    if (!srcpr) {
01555       if (option_debug)
01556          ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
01557       ast_channel_unlock(c0);
01558       if (c1)
01559          ast_channel_unlock(c1);
01560       return -1;
01561    }
01562 
01563    /* Get audio and video interface (if native bridge is possible) */
01564    audio_dest_res = destpr->get_rtp_info(c0, &destp);
01565    video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
01566    if (srcpr) {
01567       audio_src_res = srcpr->get_rtp_info(c1, &srcp);
01568       video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
01569    }
01570 
01571    /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
01572    if (audio_dest_res != AST_RTP_TRY_NATIVE) {
01573       /* Somebody doesn't want to play... */
01574       ast_channel_unlock(c0);
01575       if (c1)
01576          ast_channel_unlock(c1);
01577       return -1;
01578    }
01579    if (audio_src_res == AST_RTP_TRY_NATIVE && srcpr->get_codec)
01580       srccodec = srcpr->get_codec(c1);
01581    else
01582       srccodec = 0;
01583    /* Consider empty media as non-existant */
01584    if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
01585       srcp = NULL;
01586    if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
01587       nat_active = 1;
01588    /* Bridge media early */
01589    if (destpr->set_rtp_peer(c0, srcp, vsrcp, srccodec, nat_active))
01590       ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
01591    ast_channel_unlock(c0);
01592    if (c1)
01593       ast_channel_unlock(c1);
01594    if (option_debug)
01595       ast_log(LOG_DEBUG, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
01596    return 0;
01597 }
01598 
01599 int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
01600 {
01601    struct ast_rtp *destp = NULL, *srcp = NULL;     /* Audio RTP Channels */
01602    struct ast_rtp *vdestp = NULL, *vsrcp = NULL;      /* Video RTP channels */
01603    struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
01604    enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED;
01605    enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED; 
01606    int srccodec;
01607 
01608    /* Lock channels */
01609    ast_channel_lock(dest);
01610    while (ast_channel_trylock(src)) {
01611       ast_channel_unlock(dest);
01612       usleep(1);
01613       ast_channel_lock(dest);
01614    }
01615 
01616    /* Find channel driver interfaces */
01617    if (!(destpr = get_proto(dest))) {
01618       if (option_debug)
01619          ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", dest->name);
01620       ast_channel_unlock(dest);
01621       ast_channel_unlock(src);
01622       return 0;
01623    }
01624    if (!(srcpr = get_proto(src))) {
01625       if (option_debug)
01626          ast_log(LOG_DEBUG, "Channel '%s' has no RTP, not doing anything\n", src->name);
01627       ast_channel_unlock(dest);
01628       ast_channel_unlock(src);
01629       return 0;
01630    }
01631 
01632    /* Get audio and video interface (if native bridge is possible) */
01633    audio_dest_res = destpr->get_rtp_info(dest, &destp);
01634    video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
01635    audio_src_res = srcpr->get_rtp_info(src, &srcp);
01636    video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
01637 
01638    /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
01639    if (audio_dest_res != AST_RTP_TRY_NATIVE || audio_src_res != AST_RTP_TRY_NATIVE) {
01640       /* Somebody doesn't want to play... */
01641       ast_channel_unlock(dest);
01642       ast_channel_unlock(src);
01643       return 0;
01644    }
01645    ast_rtp_pt_copy(destp, srcp);
01646    if (vdestp && vsrcp)
01647       ast_rtp_pt_copy(vdestp, vsrcp);
01648    if (srcpr->get_codec)
01649       srccodec = srcpr->get_codec(src);
01650    else
01651       srccodec = 0;
01652    if (media) {
01653       /* Bridge early */
01654       if (destpr->set_rtp_peer(dest, srcp, vsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
01655          ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
01656    }
01657    ast_channel_unlock(dest);
01658    ast_channel_unlock(src);
01659    if (option_debug)
01660       ast_log(LOG_DEBUG, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
01661    return 1;
01662 }
01663 
01664 /*! \brief  Make a note of a RTP payload type that was seen in a SDP "m=" line.
01665  * By default, use the well-known value for this type (although it may 
01666  * still be set to a different value by a subsequent "a=rtpmap:" line)
01667  */
01668 void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt) 
01669 {
01670    if (pt < 0 || pt > MAX_RTP_PT || static_RTP_PT[pt].code == 0) 
01671       return; /* bogus payload type */
01672 
01673    rtp_bridge_lock(rtp);
01674    rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
01675    rtp_bridge_unlock(rtp);
01676 } 
01677 
01678 /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
01679  * an SDP "a=rtpmap:" line.
01680  */
01681 void ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
01682               char *mimeType, char *mimeSubtype,
01683               enum ast_rtp_options options)
01684 {
01685    unsigned int i;
01686 
01687    if (pt < 0 || pt > MAX_RTP_PT) 
01688       return; /* bogus payload type */
01689    
01690    rtp_bridge_lock(rtp);
01691 
01692    for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
01693       if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
01694           strcasecmp(mimeType, mimeTypes[i].type) == 0) {
01695          rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
01696          if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
01697              mimeTypes[i].payloadType.isAstFormat &&
01698              (options & AST_RTP_OPT_G726_NONSTANDARD))
01699             rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
01700          break;
01701       }
01702    }
01703 
01704    rtp_bridge_unlock(rtp);
01705 
01706    return;
01707 } 
01708 
01709 /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls 
01710  * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
01711 void ast_rtp_get_current_formats(struct ast_rtp* rtp,
01712              int* astFormats, int* nonAstFormats)
01713 {
01714    int pt;
01715    
01716    rtp_bridge_lock(rtp);
01717    
01718    *astFormats = *nonAstFormats = 0;
01719    for (pt = 0; pt < MAX_RTP_PT; ++pt) {
01720       if (rtp->current_RTP_PT[pt].isAstFormat) {
01721          *astFormats |= rtp->current_RTP_PT[pt].code;
01722       } else {
01723          *nonAstFormats |= rtp->current_RTP_PT[pt].code;
01724       }
01725    }
01726 
01727    rtp_bridge_unlock(rtp);
01728    
01729    return;
01730 }
01731 
01732 struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt) 
01733 {
01734    struct rtpPayloadType result;
01735 
01736    result.isAstFormat = result.code = 0;
01737 
01738    if (pt < 0 || pt > MAX_RTP_PT) 
01739       return result; /* bogus payload type */
01740 
01741    /* Start with negotiated codecs */
01742    rtp_bridge_lock(rtp);
01743    result = rtp->current_RTP_PT[pt];
01744    rtp_bridge_unlock(rtp);
01745 
01746    /* If it doesn't exist, check our static RTP type list, just in case */
01747    if (!result.code) 
01748       result = static_RTP_PT[pt];
01749 
01750    return result;
01751 }
01752 
01753 /*! \brief Looks up an RTP code out of our *static* outbound list */
01754 int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
01755 {
01756    int pt = 0;
01757 
01758    rtp_bridge_lock(rtp);
01759 
01760    if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
01761       code == rtp->rtp_lookup_code_cache_code) {
01762       /* Use our cached mapping, to avoid the overhead of the loop below */
01763       pt = rtp->rtp_lookup_code_cache_result;
01764       rtp_bridge_unlock(rtp);
01765       return pt;
01766    }
01767 
01768    /* Check the dynamic list first */
01769    for (pt = 0; pt < MAX_RTP_PT; ++pt) {
01770       if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
01771          rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
01772          rtp->rtp_lookup_code_cache_code = code;
01773          rtp->rtp_lookup_code_cache_result = pt;
01774          rtp_bridge_unlock(rtp);
01775          return pt;
01776       }
01777    }
01778 
01779    /* Then the static list */
01780    for (pt = 0; pt < MAX_RTP_PT; ++pt) {
01781       if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
01782          rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
01783          rtp->rtp_lookup_code_cache_code = code;
01784          rtp->rtp_lookup_code_cache_result = pt;
01785          rtp_bridge_unlock(rtp);
01786          return pt;
01787       }
01788    }
01789 
01790    rtp_bridge_unlock(rtp);
01791 
01792    return -1;
01793 }
01794 
01795 const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
01796               enum ast_rtp_options options)
01797 {
01798    unsigned int i;
01799 
01800    for (i = 0; i < sizeof(mimeTypes)/sizeof(mimeTypes[0]); ++i) {
01801       if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
01802          if (isAstFormat &&
01803              (code == AST_FORMAT_G726_AAL2) &&
01804              (options & AST_RTP_OPT_G726_NONSTANDARD))
01805             return "G726-32";
01806          else
01807             return mimeTypes[i].subtype;
01808       }
01809    }
01810 
01811    return "";
01812 }
01813 
01814 char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
01815                const int isAstFormat, enum ast_rtp_options options)
01816 {
01817    int format;
01818    unsigned len;
01819    char *end = buf;
01820    char *start = buf;
01821 
01822    if (!buf || !size)
01823       return NULL;
01824 
01825    snprintf(end, size, "0x%x (", capability);
01826 
01827    len = strlen(end);
01828    end += len;
01829    size -= len;
01830    start = end;
01831 
01832    for (format = 1; format < AST_RTP_MAX; format <<= 1) {
01833       if (capability & format) {
01834          const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
01835 
01836          snprintf(end, size, "%s|", name);
01837          len = strlen(end);
01838          end += len;
01839          size -= len;
01840       }
01841    }
01842 
01843    if (start == end)
01844       snprintf(start, size, "nothing)"); 
01845    else if (size > 1)
01846       *(end -1) = ')';
01847    
01848    return buf;
01849 }
01850 
01851 /*! \brief Open RTP or RTCP socket for a session */
01852 static int rtp_socket(void)
01853 {
01854    int s;
01855    long flags;
01856    s = socket(AF_INET, SOCK_DGRAM, 0);
01857    if (s > -1) {
01858       flags = fcntl(s, F_GETFL);
01859       fcntl(s, F_SETFL, flags | O_NONBLOCK);
01860 #ifdef SO_NO_CHECK
01861       if (nochecksums)
01862          setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
01863 #endif
01864    }
01865    return s;
01866 }
01867 
01868 /*!
01869  * \brief Initialize a new RTCP session.
01870  * 
01871  * \returns The newly initialized RTCP session.
01872  */
01873 static struct ast_rtcp *ast_rtcp_new(void)
01874 {
01875    struct ast_rtcp *rtcp;
01876 
01877    if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
01878       return NULL;
01879    rtcp->s = rtp_socket();
01880    rtcp->us.sin_family = AF_INET;
01881    rtcp->them.sin_family = AF_INET;
01882 
01883    if (rtcp->s < 0) {
01884       free(rtcp);
01885       ast_log(LOG_WARNING, "Unable to allocate RTCP socket: %s\n", strerror(errno));
01886       return NULL;
01887    }
01888 
01889    return rtcp;
01890 }
01891 
01892 /*!
01893  * \brief Initialize a new RTP structure.
01894  *
01895  */
01896 void ast_rtp_new_init(struct ast_rtp *rtp)
01897 {
01898 #ifdef P2P_INTENSE
01899    ast_mutex_init(&rtp->bridge_lock);
01900 #endif
01901 
01902    rtp->them.sin_family = AF_INET;
01903    rtp->us.sin_family = AF_INET;
01904    rtp->ssrc = ast_random();
01905    rtp->seqno = ast_random() & 0xffff;
01906    ast_set_flag(rtp, FLAG_HAS_DTMF);
01907 
01908    return;
01909 }
01910 
01911 struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
01912 {
01913    struct ast_rtp *rtp;
01914    int x;
01915    int first;
01916    int startplace;
01917    
01918    if (!(rtp = ast_calloc(1, sizeof(*rtp))))
01919       return NULL;
01920 
01921    ast_rtp_new_init(rtp);
01922 
01923    rtp->s = rtp_socket();
01924    if (rtp->s < 0) {
01925       free(rtp);
01926       ast_log(LOG_ERROR, "Unable to allocate socket: %s\n", strerror(errno));
01927       return NULL;
01928    }
01929    if (sched && rtcpenable) {
01930       rtp->sched = sched;
01931       rtp->rtcp = ast_rtcp_new();
01932    }
01933    
01934    /* Select a random port number in the range of possible RTP */
01935    x = (ast_random() % (rtpend-rtpstart)) + rtpstart;
01936    x = x & ~1;
01937    /* Save it for future references. */
01938    startplace = x;
01939    /* Iterate tring to bind that port and incrementing it otherwise untill a port was found or no ports are available. */
01940    for (;;) {
01941       /* Must be an even port number by RTP spec */
01942       rtp->us.sin_port = htons(x);
01943       rtp->us.sin_addr = addr;
01944 
01945       /* If there's rtcp, initialize it as well. */
01946       if (rtp->rtcp) {
01947          rtp->rtcp->us.sin_port = htons(x + 1);
01948          rtp->rtcp->us.sin_addr = addr;
01949       }
01950       /* Try to bind it/them. */
01951       if (!(first = bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) &&
01952          (!rtp->rtcp || !bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us))))
01953          break;
01954       if (!first) {
01955          /* Primary bind succeeded! Gotta recreate it */
01956          close(rtp->s);
01957          rtp->s = rtp_socket();
01958       }
01959       if (errno != EADDRINUSE) {
01960          /* We got an error that wasn't expected, abort! */
01961          ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
01962          close(rtp->s);
01963          if (rtp->rtcp) {
01964             close(rtp->rtcp->s);
01965             free(rtp->rtcp);
01966          }
01967          free(rtp);
01968          return NULL;
01969       }
01970       /* The port was used, increment it (by two). */
01971       x += 2;
01972       /* Did we go over the limit ? */
01973       if (x > rtpend)
01974          /* then, start from the begingig. */
01975          x = (rtpstart + 1) & ~1;
01976       /* Check if we reached the place were we started. */
01977       if (x == startplace) {
01978          /* If so, there's no ports available. */
01979          ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
01980          close(rtp->s);
01981          if (rtp->rtcp) {
01982             close(rtp->rtcp->s);
01983             free(rtp->rtcp);
01984          }
01985          free(rtp);
01986          return NULL;
01987       }
01988    }
01989    rtp->sched = sched;
01990    rtp->io = io;
01991    if (callbackmode) {
01992       rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
01993       ast_set_flag(rtp, FLAG_CALLBACK_MODE);
01994    }
01995    ast_rtp_pt_default(rtp);
01996    return rtp;
01997 }
01998 
01999 struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
02000 {
02001    struct in_addr ia;
02002 
02003    memset(&ia, 0, sizeof(ia));
02004    return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
02005 }
02006 
02007 int ast_rtp_settos(struct ast_rtp *rtp, int tos)
02008 {
02009    int res;
02010 
02011    if ((res = setsockopt(rtp->s, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)))) 
02012       ast_log(LOG_WARNING, "Unable to set TOS to %d\n", tos);
02013    return res;
02014 }
02015 
02016 void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
02017 {
02018    rtp->them.sin_port = them->sin_port;
02019    rtp->them.sin_addr = them->sin_addr;
02020    if (rtp->rtcp) {
02021       rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
02022       rtp->rtcp->them.sin_addr = them->sin_addr;
02023    }
02024    rtp->rxseqno = 0;
02025 }
02026 
02027 int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
02028 {
02029    if ((them->sin_family != AF_INET) ||
02030       (them->sin_port != rtp->them.sin_port) ||
02031       (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
02032       them->sin_family = AF_INET;
02033       them->sin_port = rtp->them.sin_port;
02034       them->sin_addr = rtp->them.sin_addr;
02035       return 1;
02036    }
02037    return 0;
02038 }
02039 
02040 void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
02041 {
02042    *us = rtp->us;
02043 }
02044 
02045 struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
02046 {
02047    struct ast_rtp *bridged = NULL;
02048 
02049    rtp_bridge_lock(rtp);
02050    bridged = rtp->bridged;
02051    rtp_bridge_unlock(rtp);
02052 
02053    return bridged;
02054 }
02055 
02056 void ast_rtp_stop(struct ast_rtp *rtp)
02057 {
02058    if (rtp->rtcp && rtp->rtcp->schedid > 0) {
02059       ast_sched_del(rtp->sched, rtp->rtcp->schedid);
02060       rtp->rtcp->schedid = -1;
02061    }
02062 
02063    memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
02064    memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
02065    if (rtp->rtcp) {
02066       memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
02067       memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
02068    }
02069    
02070    ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
02071 }
02072 
02073 void ast_rtp_reset(struct ast_rtp *rtp)
02074 {
02075    memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
02076    memset(&rtp->txcore, 0, sizeof(rtp->txcore));
02077    memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
02078    rtp->lastts = 0;
02079    rtp->lastdigitts = 0;
02080    rtp->lastrxts = 0;
02081    rtp->lastividtimestamp = 0;
02082    rtp->lastovidtimestamp = 0;
02083    rtp->lasteventseqn = 0;
02084    rtp->lasteventendseqn = 0;
02085    rtp->lasttxformat = 0;
02086    rtp->lastrxformat = 0;
02087    rtp->dtmfcount = 0;
02088    rtp->dtmfsamples = 0;
02089    rtp->seqno = 0;
02090    rtp->rxseqno = 0;
02091 }
02092 
02093 char *ast_rtp_get_quality(struct ast_rtp *rtp)
02094 {
02095    /*
02096    *ssrc          our ssrc
02097    *themssrc      their ssrc
02098    *lp            lost packets
02099    *rxjitter      our calculated jitter(rx)
02100    *rxcount       no. received packets
02101    *txjitter      reported jitter of the other end
02102    *txcount       transmitted packets
02103    *rlp           remote lost packets
02104    */
02105    
02106    snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality), "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f", rtp->ssrc, rtp->themssrc, rtp->rtcp->expected_prior - rtp->rtcp->received_prior, rtp->rxjitter, rtp->rxcount, (double)rtp->rtcp->reported_jitter/65536., rtp->txcount, rtp->rtcp->reported_lost, rtp->rtcp->rtt);
02107    
02108    return rtp->rtcp->quality;
02109 }
02110 
02111 void ast_rtp_destroy(struct ast_rtp *rtp)
02112 {
02113    if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
02114       /*Print some info on the call here */
02115       ast_verbose("  RTP-stats\n");
02116       ast_verbose("* Our Receiver:\n");
02117       ast_verbose("  SSRC:     %u\n", rtp->themssrc);
02118       ast_verbose("  Received packets: %u\n", rtp->rxcount);
02119       ast_verbose("  Lost packets:   %u\n", rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
02120       ast_verbose("  Jitter:      %.4f\n", rtp->rxjitter);
02121       ast_verbose("  Transit:     %.4f\n", rtp->rxtransit);
02122       ast_verbose("  RR-count:    %u\n", rtp->rtcp->rr_count);
02123       ast_verbose("* Our Sender:\n");
02124       ast_verbose("  SSRC:     %u\n", rtp->ssrc);
02125       ast_verbose("  Sent packets:   %u\n", rtp->txcount);
02126       ast_verbose("  Lost packets:   %u\n", rtp->rtcp->reported_lost);
02127       ast_verbose("  Jitter:      %u\n", rtp->rtcp->reported_jitter);
02128       ast_verbose("  SR-count:    %u\n", rtp->rtcp->sr_count);
02129       ast_verbose("  RTT:      %f\n", rtp->rtcp->rtt);
02130    }
02131 
02132    if (rtp->smoother)
02133       ast_smoother_free(rtp->smoother);
02134    if (rtp->ioid)
02135       ast_io_remove(rtp->io, rtp->ioid);
02136    if (rtp->s > -1)
02137       close(rtp->s);
02138    if (rtp->rtcp) {
02139       if (rtp->rtcp->schedid > 0)
02140          ast_sched_del(rtp->sched, rtp->rtcp->schedid);
02141       close(rtp->rtcp->s);
02142       free(rtp->rtcp);
02143       rtp->rtcp=NULL;
02144    }
02145 #ifdef P2P_INTENSE
02146    ast_mutex_destroy(&rtp->bridge_lock);
02147 #endif
02148    free(rtp);
02149 }
02150 
02151 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
02152 {
02153    struct timeval t;
02154    long ms;
02155    if (ast_tvzero(rtp->txcore)) {
02156       rtp->txcore = ast_tvnow();
02157       /* Round to 20ms for nice, pretty timestamps */
02158       rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
02159    }
02160    /* Use previous txcore if available */
02161    t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
02162    ms = ast_tvdiff_ms(t, rtp->txcore);
02163    if (ms < 0)
02164       ms = 0;
02165    /* Use what we just got for next time */
02166    rtp->txcore = t;
02167    return (unsigned int) ms;
02168 }
02169 
02170 /*! \brief Send begin frames for DTMF */
02171 int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
02172 {
02173    unsigned int *rtpheader;
02174    int hdrlen = 12, res = 0, i = 0, payload = 0;
02175    char data[256];
02176 
02177    if ((digit <= '9') && (digit >= '0'))
02178       digit -= '0';
02179    else if (digit == '*')
02180       digit = 10;
02181    else if (digit == '#')
02182       digit = 11;
02183    else if ((digit >= 'A') && (digit <= 'D'))
02184       digit = digit - 'A' + 12;
02185    else if ((digit >= 'a') && (digit <= 'd'))
02186       digit = digit - 'a' + 12;
02187    else {
02188       ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
02189       return 0;
02190    }
02191 
02192    /* If we have no peer, return immediately */ 
02193    if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
02194       return 0;
02195 
02196    payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
02197 
02198    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
02199    rtp->send_duration = 160;
02200    
02201    /* Get a pointer to the header */
02202    rtpheader = (unsigned int *)data;
02203    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
02204    rtpheader[1] = htonl(rtp->lastdigitts);
02205    rtpheader[2] = htonl(rtp->ssrc); 
02206 
02207    for (i = 0; i < 2; i++) {
02208       rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
02209       res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
02210       if (res < 0) 
02211          ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
02212             ast_inet_ntoa(rtp->them.sin_addr),
02213             ntohs(rtp->them.sin_port), strerror(errno));
02214       if (rtp_debug_test_addr(&rtp->them))
02215          ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
02216                 ast_inet_ntoa(rtp->them.sin_addr),
02217                 ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
02218       /* Increment sequence number */
02219       rtp->seqno++;
02220       /* Increment duration */
02221       rtp->send_duration += 160;
02222       /* Clear marker bit and set seqno */
02223       rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
02224    }
02225 
02226    /* Since we received a begin, we can safely store the digit and disable any compensation */
02227    rtp->sending_digit = 1;
02228    rtp->send_digit = digit;
02229    rtp->send_payload = payload;
02230 
02231    return 0;
02232 }
02233 
02234 /*! \brief Send continuation frame for DTMF */
02235 static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
02236 {
02237    unsigned int *rtpheader;
02238    int hdrlen = 12, res = 0;
02239    char data[256];
02240 
02241    if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
02242       return 0;
02243 
02244    /* Setup packet to send */
02245    rtpheader = (unsigned int *)data;
02246         rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
02247         rtpheader[1] = htonl(rtp->lastdigitts);
02248         rtpheader[2] = htonl(rtp->ssrc);
02249         rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
02250    rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
02251    
02252    /* Transmit */
02253    res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
02254    if (res < 0)
02255       ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
02256          ast_inet_ntoa(rtp->them.sin_addr),
02257          ntohs(rtp->them.sin_port), strerror(errno));
02258    if (rtp_debug_test_addr(&rtp->them))
02259       ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
02260              ast_inet_ntoa(rtp->them.sin_addr),
02261              ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
02262 
02263    /* Increment sequence number */
02264    rtp->seqno++;
02265    /* Increment duration */
02266    rtp->send_duration += 160;
02267 
02268    return 0;
02269 }
02270 
02271 /*! \brief Send end packets for DTMF */
02272 int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
02273 {
02274    unsigned int *rtpheader;
02275    int hdrlen = 12, res = 0, i = 0;
02276    char data[256];
02277    
02278    /* If no address, then bail out */
02279    if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
02280       return 0;
02281    
02282    if ((digit <= '9') && (digit >= '0'))
02283       digit -= '0';
02284    else if (digit == '*')
02285       digit = 10;
02286    else if (digit == '#')
02287       digit = 11;
02288    else if ((digit >= 'A') && (digit <= 'D'))
02289       digit = digit - 'A' + 12;
02290    else if ((digit >= 'a') && (digit <= 'd'))
02291       digit = digit - 'a' + 12;
02292    else {
02293       ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
02294       return 0;
02295    }
02296 
02297    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
02298 
02299    rtpheader = (unsigned int *)data;
02300    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
02301    rtpheader[1] = htonl(rtp->lastdigitts);
02302    rtpheader[2] = htonl(rtp->ssrc);
02303    rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
02304    /* Set end bit */
02305    rtpheader[3] |= htonl((1 << 23));
02306    rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
02307    /* Send 3 termination packets */
02308    for (i = 0; i < 3; i++) {
02309       res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
02310       if (res < 0)
02311          ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
02312             ast_inet_ntoa(rtp->them.sin_addr),
02313             ntohs(rtp->them.sin_port), strerror(errno));
02314       if (rtp_debug_test_addr(&rtp->them))
02315          ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
02316                 ast_inet_ntoa(rtp->them.sin_addr),
02317                 ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
02318    }
02319    rtp->sending_digit = 0;
02320    rtp->send_digit = 0;
02321    /* Increment lastdigitts */
02322    rtp->lastdigitts += 960;
02323    rtp->seqno++;
02324 
02325    return res;
02326 }
02327 
02328 /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
02329 int ast_rtcp_send_h261fur(void *data)
02330 {
02331    struct ast_rtp *rtp = data;
02332    int res;
02333 
02334    rtp->rtcp->sendfur = 1;
02335    res = ast_rtcp_write(data);
02336    
02337    return res;
02338 }
02339 
02340 /*! \brief Send RTCP sender's report */
02341 static int ast_rtcp_write_sr(void *data)
02342 {
02343    struct ast_rtp *rtp = data;
02344    int res;
02345    int len = 0;
02346    struct timeval now;
02347    unsigned int now_lsw;
02348    unsigned int now_msw;
02349    unsigned int *rtcpheader;
02350    unsigned int lost;
02351    unsigned int extended;
02352    unsigned int expected;
02353    unsigned int expected_interval;
02354    unsigned int received_interval;
02355    int lost_interval;
02356    int fraction;
02357    struct timeval dlsr;
02358    char bdata[512];
02359 
02360    /* Commented condition is always not NULL if rtp->rtcp is not NULL */
02361    if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
02362       return 0;
02363    
02364    if (!rtp->rtcp->them.sin_addr.s_addr) {  /* This'll stop rtcp for this rtp session */
02365       ast_verbose("RTCP SR transmission error, rtcp halted\n");
02366       if (rtp->rtcp->schedid > 0)
02367          ast_sched_del(rtp->sched, rtp->rtcp->schedid);
02368       rtp->rtcp->schedid = -1;
02369       return 0;
02370    }
02371 
02372    gettimeofday(&now, NULL);
02373    timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
02374    rtcpheader = (unsigned int *)bdata;
02375    rtcpheader[1] = htonl(rtp->ssrc);               /* Our SSRC */
02376    rtcpheader[2] = htonl(now_msw);                 /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
02377    rtcpheader[3] = htonl(now_lsw);                 /* now, LSW */
02378    rtcpheader[4] = htonl(rtp->lastts);             /* FIXME shouldn't be that, it should be now */
02379    rtcpheader[5] = htonl(rtp->txcount);            /* No. packets sent */
02380    rtcpheader[6] = htonl(rtp->txoctetcount);       /* No. bytes sent */
02381    len += 28;
02382    
02383    extended = rtp->cycles + rtp->lastrxseqno;
02384    expected = extended - rtp->seedrxseqno + 1;
02385    if (rtp->rxcount > expected) 
02386       expected += rtp->rxcount - expected;
02387    lost = expected - rtp->rxcount;
02388    expected_interval = expected - rtp->rtcp->expected_prior;
02389    rtp->rtcp->expected_prior = expected;
02390    received_interval = rtp->rxcount - rtp->rtcp->received_prior;
02391    rtp->rtcp->received_prior = rtp->rxcount;
02392    lost_interval = expected_interval - received_interval;
02393    if (expected_interval == 0 || lost_interval <= 0)
02394       fraction = 0;
02395    else
02396       fraction = (lost_interval << 8) / expected_interval;
02397    timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
02398    rtcpheader[7] = htonl(rtp->themssrc);
02399    rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
02400    rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
02401    rtcpheader[10] = htonl((unsigned int)rtp->rxjitter);
02402    rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
02403    rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
02404    len += 24;
02405    
02406    rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
02407 
02408    if (rtp->rtcp->sendfur) {
02409       rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
02410       rtcpheader[14] = htonl(rtp->ssrc);               /* Our SSRC */
02411       len += 8;
02412       rtp->rtcp->sendfur = 0;
02413    }
02414    
02415    /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */ 
02416    /* it can change mid call, and SDES can't) */
02417    rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
02418    rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
02419    rtcpheader[(len/4)+2] = htonl(0x01 << 24);                    /* Empty for the moment */
02420    len += 12;
02421    
02422    res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
02423    if (res < 0) {
02424       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));
02425       if (rtp->rtcp->schedid > 0)
02426          ast_sched_del(rtp->sched, rtp->rtcp->schedid);
02427       rtp->rtcp->schedid = -1;
02428       return 0;
02429    }
02430    
02431    /* FIXME Don't need to get a new one */
02432    gettimeofday(&rtp->rtcp->txlsr, NULL);
02433    rtp->rtcp->sr_count++;
02434 
02435    rtp->rtcp->lastsrtxcount = rtp->txcount;  
02436    
02437    if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
02438       ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
02439       ast_verbose("  Our SSRC: %u\n", rtp->ssrc);
02440       ast_verbose("  Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
02441       ast_verbose("  Sent(RTP): %u\n", rtp->lastts);
02442       ast_verbose("  Sent packets: %u\n", rtp->txcount);
02443       ast_verbose("  Sent octets: %u\n", rtp->txoctetcount);
02444       ast_verbose("  Report block:\n");
02445       ast_verbose("  Fraction lost: %u\n", fraction);
02446       ast_verbose("  Cumulative loss: %u\n", lost);
02447       ast_verbose("  IA jitter: %.4f\n", rtp->rxjitter);
02448       ast_verbose("  Their last SR: %u\n", rtp->rtcp->themrxlsr);
02449       ast_verbose("  DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
02450    }
02451    return res;
02452 }
02453 
02454 /*! \brief Send RTCP recipient's report */
02455 static int ast_rtcp_write_rr(void *data)
02456 {
02457    struct ast_rtp *rtp = data;
02458    int res;
02459    int len = 32;
02460    unsigned int lost;
02461    unsigned int extended;
02462    unsigned int expected;
02463    unsigned int expected_interval;
02464    unsigned int received_interval;
02465    int lost_interval;
02466    struct timeval now;
02467    unsigned int *rtcpheader;
02468    char bdata[1024];
02469    struct timeval dlsr;
02470    int fraction;
02471 
02472    if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
02473       return 0;
02474      
02475    if (!rtp->rtcp->them.sin_addr.s_addr) {
02476       ast_log(LOG_ERROR, "RTCP RR transmission error to, rtcp halted %s\n",strerror(errno));
02477       if (rtp->rtcp->schedid > 0)
02478          ast_sched_del(rtp->sched, rtp->rtcp->schedid);
02479       rtp->rtcp->schedid = -1;
02480       return 0;
02481    }
02482 
02483    extended = rtp->cycles + rtp->lastrxseqno;
02484    expected = extended - rtp->seedrxseqno + 1;
02485    lost = expected - rtp->rxcount;
02486    expected_interval = expected - rtp->rtcp->expected_prior;
02487    rtp->rtcp->expected_prior = expected;
02488    received_interval = rtp->rxcount - rtp->rtcp->received_prior;
02489    rtp->rtcp->received_prior = rtp->rxcount;
02490    lost_interval = expected_interval - received_interval;
02491    if (expected_interval == 0 || lost_interval <= 0)
02492       fraction = 0;
02493    else
02494       fraction = (lost_interval << 8) / expected_interval;
02495    gettimeofday(&now, NULL);
02496    timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
02497    rtcpheader = (unsigned int *)bdata;
02498    rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
02499    rtcpheader[1] = htonl(rtp->ssrc);
02500    rtcpheader[2] = htonl(rtp->themssrc);
02501    rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
02502    rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
02503    rtcpheader[5] = htonl((unsigned int)rtp->rxjitter);
02504    rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
02505    rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
02506 
02507    if (rtp->rtcp->sendfur) {
02508       rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
02509       rtcpheader[9] = htonl(rtp->ssrc);               /* Our SSRC */
02510       len += 8;
02511       rtp->rtcp->sendfur = 0;
02512    }
02513 
02514    /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos 
02515    it can change mid call, and SDES can't) */
02516    rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
02517    rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
02518    rtcpheader[(len/4)+2] = htonl(0x01 << 24);              /* Empty for the moment */
02519    len += 12;
02520    
02521    res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
02522 
02523    if (res < 0) {
02524       ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
02525       /* Remove the scheduler */
02526       if (rtp->rtcp->schedid > 0)
02527          ast_sched_del(rtp->sched, rtp->rtcp->schedid);
02528       rtp->rtcp->schedid = -1;
02529       return 0;
02530    }
02531 
02532    rtp->rtcp->rr_count++;
02533 
02534    if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
02535       ast_verbose("\n* Sending RTCP RR to %s:%d\n"
02536          "  Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n" 
02537          "  IA jitter: %.4f\n" 
02538          "  Their last SR: %u\n" 
02539          "  DLSR: %4.4f (sec)\n\n",
02540          ast_inet_ntoa(rtp->rtcp->them.sin_addr),
02541          ntohs(rtp->rtcp->them.sin_port),
02542          rtp->ssrc, rtp->themssrc, fraction, lost,
02543          rtp->rxjitter,
02544          rtp->rtcp->themrxlsr,
02545          (double)(ntohl(rtcpheader[7])/65536.0));
02546    }
02547 
02548    return res;
02549 }
02550 
02551 /*! \brief Write and RTCP packet to the far end
02552  * \note Decide if we are going to send an SR (with Reception Block) or RR 
02553  * RR is sent if we have not sent any rtp packets in the previous interval */
02554 static int ast_rtcp_write(void *data)
02555 {
02556    struct ast_rtp *rtp = data;
02557    int res;
02558    
02559    if (rtp->txcount > rtp->rtcp->lastsrtxcount)
02560       res = ast_rtcp_write_sr(data);
02561    else
02562       res = ast_rtcp_write_rr(data);
02563    
02564    return res;
02565 }
02566 
02567 /*! \brief generate comfort noice (CNG) */
02568 int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
02569 {
02570    unsigned int *rtpheader;
02571    int hdrlen = 12;
02572    int res;
02573    int payload;
02574    char data[256];
02575    level = 127 - (level & 0x7f);
02576    payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
02577 
02578    /* If we have no peer, return immediately */ 
02579    if (!rtp->them.sin_addr.s_addr)
02580       return 0;
02581 
02582    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
02583 
02584    /* Get a pointer to the header */
02585    rtpheader = (unsigned int *)data;
02586    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
02587    rtpheader[1] = htonl(rtp->lastts);
02588    rtpheader[2] = htonl(rtp->ssrc); 
02589    data[12] = level;
02590    if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
02591       res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
02592       if (res <0) 
02593          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));
02594       if (rtp_debug_test_addr(&rtp->them))
02595          ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
02596                , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);         
02597          
02598    }
02599    return 0;
02600 }
02601 
02602 /*! \brief Write RTP packet with audio or video media frames into UDP packet */
02603 static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
02604 {
02605    unsigned char *rtpheader;
02606    int hdrlen = 12;
02607    int res;
02608    unsigned int ms;
02609    int pred;
02610    int mark = 0;
02611 
02612    ms = calc_txstamp(rtp, &f->delivery);
02613    /* Default prediction */
02614    if (f->subclass < AST_FORMAT_MAX_AUDIO) {
02615       pred = rtp->lastts + f->samples;
02616 
02617       /* Re-calculate last TS */
02618       rtp->lastts = rtp->lastts + ms * 8;
02619       if (ast_tvzero(f->delivery)) {
02620          /* If this isn't an absolute delivery time, Check if it is close to our prediction, 
02621             and if so, go with our prediction */
02622          if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
02623             rtp->lastts = pred;
02624          else {
02625             if (option_debug > 2)
02626                ast_log(LOG_DEBUG, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
02627             mark = 1;
02628          }
02629       }
02630    } else {
02631       mark = f->subclass & 0x1;
02632       pred = rtp->lastovidtimestamp + f->samples;
02633       /* Re-calculate last TS */
02634       rtp->lastts = rtp->lastts + ms * 90;
02635       /* If it's close to our prediction, go for it */
02636       if (ast_tvzero(f->delivery)) {
02637          if (abs(rtp->lastts - pred) < 7200) {
02638             rtp->lastts = pred;
02639             rtp->lastovidtimestamp += f->samples;
02640          } else {
02641             if (option_debug > 2)
02642                ast_log(LOG_DEBUG, "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);
02643             rtp->lastovidtimestamp = rtp->lastts;
02644          }
02645       }
02646    }
02647    /* If the timestamp for non-digit packets has moved beyond the timestamp
02648       for digits, update the digit timestamp.
02649    */
02650    if (rtp->lastts > rtp->lastdigitts)
02651       rtp->lastdigitts = rtp->lastts;
02652 
02653    if (f->has_timing_info)
02654       rtp->lastts = f->ts * 8;
02655 
02656    /* Get a pointer to the header */
02657    rtpheader = (unsigned char *)(f->data - hdrlen);
02658 
02659    put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
02660    put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
02661    put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc)); 
02662 
02663    if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
02664       res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
02665       if (res <0) {
02666          if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
02667             if (option_debug)
02668                ast_log(LOG_DEBUG, "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));
02669          } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
02670             /* Only give this error message once if we are not RTP debugging */
02671             if (option_debug || rtpdebug)
02672                ast_log(LOG_DEBUG, "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));
02673             ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
02674          }
02675       } else {
02676          rtp->txcount++;
02677          rtp->txoctetcount +=(res - hdrlen);
02678          
02679          if (rtp->rtcp && rtp->rtcp->schedid < 1) 
02680              rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
02681       }
02682             
02683       if (rtp_debug_test_addr(&rtp->them))
02684          ast_verbose("Sent RTP packet to      %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
02685                ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
02686    }
02687 
02688    rtp->seqno++;
02689 
02690    return 0;
02691 }
02692 
02693 int ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
02694 {
02695    int x;
02696    for (x = 0; x < 32; x++) {  /* Ugly way */
02697       rtp->pref.order[x] = prefs->order[x];
02698       rtp->pref.framing[x] = prefs->framing[x];
02699    }
02700    if (rtp->smoother)
02701       ast_smoother_free(rtp->smoother);
02702    rtp->smoother = NULL;
02703    return 0;
02704 }
02705 
02706 struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
02707 {
02708    return &rtp->pref;
02709 }
02710 
02711 int ast_rtp_codec_getformat(int pt)
02712 {
02713    if (pt < 0 || pt > MAX_RTP_PT)
02714       return 0; /* bogus payload type */
02715 
02716    if (static_RTP_PT[pt].isAstFormat)
02717       return static_RTP_PT[pt].code;
02718    else
02719       return 0;
02720 }
02721 
02722 int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
02723 {
02724    struct ast_frame *f;
02725    int codec;
02726    int hdrlen = 12;
02727    int subclass;
02728    
02729 
02730    /* If we have no peer, return immediately */ 
02731    if (!rtp->them.sin_addr.s_addr)
02732       return 0;
02733 
02734    /* If there is no data length, return immediately */
02735    if (!_f->datalen) 
02736       return 0;
02737    
02738    /* Make sure we have enough space for RTP header */
02739    if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO)) {
02740       ast_log(LOG_WARNING, "RTP can only send voice and video\n");
02741       return -1;
02742    }
02743 
02744    subclass = _f->subclass;
02745    if (_f->frametype == AST_FRAME_VIDEO)
02746       subclass &= ~0x1;
02747 
02748    codec = ast_rtp_lookup_code(rtp, 1, subclass);
02749    if (codec < 0) {
02750       ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
02751       return -1;
02752    }
02753 
02754    if (rtp->lasttxformat != subclass) {
02755       /* New format, reset the smoother */
02756       if (option_debug)
02757          ast_log(LOG_DEBUG, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
02758       rtp->lasttxformat = subclass;
02759       if (rtp->smoother)
02760          ast_smoother_free(rtp->smoother);
02761       rtp->smoother = NULL;
02762    }
02763 
02764    if (!rtp->smoother) {
02765       struct ast_format_list fmt = ast_codec_pref_getsize(&rtp->pref, subclass);
02766       if (fmt.inc_ms) { /* if codec parameters is set / avoid division by zero */
02767          if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
02768             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));
02769             return -1;
02770          }
02771          if (fmt.flags)
02772             ast_smoother_set_flags(rtp->smoother, fmt.flags);
02773          if (option_debug)
02774             ast_log(LOG_DEBUG, "Created smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
02775       }
02776    }
02777    if (rtp->smoother) {
02778       if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
02779          ast_smoother_feed_be(rtp->smoother, _f);
02780       } else {
02781          ast_smoother_feed(rtp->smoother, _f);
02782       }
02783 
02784       while ((f = ast_smoother_read(rtp->smoother)))
02785          ast_rtp_raw_write(rtp, f, codec);
02786    } else {
02787            /* Don't buffer outgoing frames; send them one-per-packet: */
02788       if (_f->offset < hdrlen) 
02789          f = ast_frdup(_f);   /*! \bug XXX this might never be free'd. Why do we do this? */
02790       else
02791          f = _f;
02792       ast_rtp_raw_write(rtp, f, codec);
02793       if (f != _f)
02794          ast_frfree(f);
02795    }
02796       
02797    return 0;
02798 }
02799 
02800 /*! \brief Unregister interface to channel driver */
02801 void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
02802 {
02803    AST_RWLIST_WRLOCK(&protos);
02804    AST_RWLIST_REMOVE(&protos, proto, list);
02805    AST_RWLIST_UNLOCK(&protos);
02806 }
02807 
02808 /*! \brief Register interface to channel driver */
02809 int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
02810 {
02811    struct ast_rtp_protocol *cur;
02812 
02813    AST_RWLIST_WRLOCK(&protos);
02814    AST_RWLIST_TRAVERSE(&protos, cur, list) { 
02815       if (!strcmp(cur->type, proto->type)) {
02816          ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
02817          AST_RWLIST_UNLOCK(&protos);
02818          return -1;
02819       }
02820    }
02821    AST_RWLIST_INSERT_HEAD(&protos, proto, list);
02822    AST_RWLIST_UNLOCK(&protos);
02823    
02824    return 0;
02825 }
02826 
02827 /*! \brief Bridge loop for true native bridge (reinvite) */
02828 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_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)
02829 {
02830    struct ast_frame *fr = NULL;
02831    struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
02832    int oldcodec0 = codec0, oldcodec1 = codec1;
02833    struct sockaddr_in ac1 = {0,}, vac1 = {0,}, ac0 = {0,}, vac0 = {0,};
02834    struct sockaddr_in t1 = {0,}, vt1 = {0,}, t0 = {0,}, vt0 = {0,};
02835    
02836    /* Set it up so audio goes directly between the two endpoints */
02837 
02838    /* Test the first channel */
02839    if (!(pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))) {
02840       ast_rtp_get_peer(p1, &ac1);
02841       if (vp1)
02842          ast_rtp_get_peer(vp1, &vac1);
02843    } else
02844       ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
02845    
02846    /* Test the second channel */
02847    if (!(pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))) {
02848       ast_rtp_get_peer(p0, &ac0);
02849       if (vp0)
02850          ast_rtp_get_peer(vp0, &vac0);
02851    } else
02852       ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c1->name, c0->name);
02853 
02854    /* Now we can unlock and move into our loop */
02855    ast_channel_unlock(c0);
02856    ast_channel_unlock(c1);
02857 
02858    /* Throw our channels into the structure and enter the loop */
02859    cs[0] = c0;
02860    cs[1] = c1;
02861    cs[2] = NULL;
02862    for (;;) {
02863       /* Check if anything changed */
02864       if ((c0->tech_pvt != pvt0) ||
02865           (c1->tech_pvt != pvt1) ||
02866           (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
02867          if (option_debug)
02868             ast_log(LOG_DEBUG, "Oooh, something is weird, backing out\n");
02869          if (c0->tech_pvt == pvt0)
02870             if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
02871                ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
02872          if (c1->tech_pvt == pvt1)
02873             if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
02874                ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
02875          return AST_BRIDGE_RETRY;
02876       }
02877 
02878       /* Check if they have changed their address */
02879       ast_rtp_get_peer(p1, &t1);
02880       if (vp1)
02881          ast_rtp_get_peer(vp1, &vt1);
02882       if (pr1->get_codec)
02883          codec1 = pr1->get_codec(c1);
02884       ast_rtp_get_peer(p0, &t0);
02885       if (vp0)
02886          ast_rtp_get_peer(vp0, &vt0);
02887       if (pr0->get_codec)
02888          codec0 = pr0->get_codec(c0);
02889       if ((inaddrcmp(&t1, &ac1)) ||
02890           (vp1 && inaddrcmp(&vt1, &vac1)) ||
02891           (codec1 != oldcodec1)) {
02892          if (option_debug > 1) {
02893             ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
02894                c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
02895             ast_log(LOG_DEBUG, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
02896                c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
02897             ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
02898                c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
02899             ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
02900                c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
02901          }
02902          if (pr0->set_rtp_peer(c0, t1.sin_addr.s_addr ? p1 : NULL, vt1.sin_addr.s_addr ? vp1 : NULL, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
02903             ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
02904          memcpy(&ac1, &t1, sizeof(ac1));
02905          memcpy(&vac1, &vt1, sizeof(vac1));
02906          oldcodec1 = codec1;
02907       }
02908       if ((inaddrcmp(&t0, &ac0)) ||
02909           (vp0 && inaddrcmp(&vt0, &vac0))) {
02910          if (option_debug > 1) {
02911             ast_log(LOG_DEBUG, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
02912                c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
02913             ast_log(LOG_DEBUG, "Oooh, '%s' was %s:%d/(format %d)\n",
02914                c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
02915          }
02916          if (pr1->set_rtp_peer(c1, t0.sin_addr.s_addr ? p0 : NULL, vt0.sin_addr.s_addr ? vp0 : NULL, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
02917             ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
02918          memcpy(&ac0, &t0, sizeof(ac0));
02919          memcpy(&vac0, &vt0, sizeof(vac0));
02920          oldcodec0 = codec0;
02921       }
02922 
02923       /* Wait for frame to come in on the channels */
02924       if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
02925          if (!timeoutms)
02926             return AST_BRIDGE_RETRY;
02927          if (option_debug)
02928             ast_log(LOG_DEBUG, "Ooh, empty read...\n");
02929          if (ast_check_hangup(c0) || ast_check_hangup(c1))
02930             break;
02931          continue;
02932       }
02933       fr = ast_read(who);
02934       other = (who == c0) ? c1 : c0;
02935       if (!fr || ((fr->frametype == AST_FRAME_DTMF) &&
02936              (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
02937               ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
02938          /* Break out of bridge */
02939          *fo = fr;
02940          *rc = who;
02941          if (option_debug)
02942             ast_log(LOG_DEBUG, "Oooh, got a %s\n", fr ? "digit" : "hangup");
02943          if (c0->tech_pvt == pvt0)
02944             if (pr0->set_rtp_peer(c0, NULL, NULL, 0, 0))
02945                ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
02946          if (c1->tech_pvt == pvt1)
02947             if (pr1->set_rtp_peer(c1, NULL, NULL, 0, 0))
02948                ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
02949          return AST_BRIDGE_COMPLETE;
02950       } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
02951          if ((fr->subclass == AST_CONTROL_HOLD) ||
02952              (fr->subclass == AST_CONTROL_UNHOLD) ||
02953              (fr->subclass == AST_CONTROL_VIDUPDATE)) {
02954             if (fr->subclass == AST_CONTROL_HOLD) {
02955                /* If we someone went on hold we want the other side to reinvite back to us */
02956                if (who == c0)
02957                   pr1->set_rtp_peer(c1, NULL, NULL, 0, 0);
02958                else
02959                   pr0->set_rtp_peer(c0, NULL, NULL, 0, 0);
02960             } else if (fr->subclass == AST_CONTROL_UNHOLD) {
02961                /* If they went off hold they should go back to being direct */
02962                if (who == c0)
02963                   pr1->set_rtp_peer(c1, p0, vp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE));
02964                else
02965                   pr0->set_rtp_peer(c0, p1, vp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE));
02966             }
02967             ast_indicate_data(other, fr->subclass, fr->data, fr->datalen);
02968             ast_frfree(fr);
02969          } else {
02970             *fo = fr;
02971             *rc = who;
02972             if (option_debug)
02973                ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
02974             return AST_BRIDGE_COMPLETE;
02975          }
02976       } else {
02977          if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
02978              (fr->frametype == AST_FRAME_DTMF) ||
02979              (fr->frametype == AST_FRAME_VOICE) ||
02980              (fr->frametype == AST_FRAME_VIDEO) ||
02981              (fr->frametype == AST_FRAME_IMAGE) ||
02982              (fr->frametype == AST_FRAME_HTML) ||
02983              (fr->frametype == AST_FRAME_MODEM) ||
02984              (fr->frametype == AST_FRAME_TEXT)) {
02985             ast_write(other, fr);
02986          }
02987          ast_frfree(fr);
02988       }
02989       /* Swap priority */
02990       cs[2] = cs[0];
02991       cs[0] = cs[1];
02992       cs[1] = cs[2];
02993    }
02994 
02995    return AST_BRIDGE_FAILED;
02996 }
02997 
02998 /*! \brief P2P RTP Callback */
02999 #ifdef P2P_INTENSE
03000 static int p2p_rtp_callback(int *id, int fd, short events, void *cbdata)
03001 {
03002    int res = 0, hdrlen = 12;
03003    struct sockaddr_in sin;
03004    socklen_t len;
03005    unsigned int *header;
03006    struct ast_rtp *rtp = cbdata, *bridged = NULL;
03007 
03008    if (!rtp)
03009       return 1;
03010 
03011    len = sizeof(sin);
03012    if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
03013       return 1;
03014 
03015    header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
03016    
03017    /* If NAT support is turned on, then see if we need to change their address */
03018    if ((rtp->nat) && 
03019        ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
03020         (rtp->them.sin_port != sin.sin_port))) {
03021       rtp->them = sin;
03022       rtp->rxseqno = 0;
03023       ast_set_flag(rtp, FLAG_NAT_ACTIVE);
03024       if (option_debug || rtpdebug)
03025          ast_log(LOG_DEBUG, "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));
03026    }
03027 
03028    /* Write directly out to other RTP stream if bridged */
03029    if ((bridged = ast_rtp_get_bridged(rtp)))
03030       bridge_p2p_rtp_write(rtp, bridged, header, res, hdrlen);
03031    
03032    return 1;
03033 }
03034 
03035 /*! \brief Helper function to switch a channel and RTP stream into callback mode */
03036 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
03037 {
03038    /* If we need DTMF, are looking for STUN, or we have no IO structure then we can't do direct callback */
03039    if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) || ast_test_flag(rtp, FLAG_HAS_STUN) || !rtp->io)
03040       return 0;
03041 
03042    /* If the RTP structure is already in callback mode, remove it temporarily */
03043    if (rtp->ioid) {
03044       ast_io_remove(rtp->io, rtp->ioid);
03045       rtp->ioid = NULL;
03046    }
03047 
03048    /* Steal the file descriptors from the channel */
03049    chan->fds[0] = -1;
03050 
03051    /* Now, fire up callback mode */
03052    iod[0] = ast_io_add(rtp->io, ast_rtp_fd(rtp), p2p_rtp_callback, AST_IO_IN, rtp);
03053 
03054    return 1;
03055 }
03056 #else
03057 static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
03058 {
03059    return 0;
03060 }
03061 #endif
03062 
03063 /*! \brief Helper function to switch a channel and RTP stream out of callback mode */
03064 static int p2p_callback_disable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
03065 {
03066    ast_channel_lock(chan);
03067 
03068    /* Remove the callback from the IO context */
03069    ast_io_remove(rtp->io, iod[0]);
03070 
03071    /* Restore file descriptors */
03072    chan->fds[0] = ast_rtp_fd(rtp);
03073    ast_channel_unlock(chan);
03074 
03075    /* Restore callback mode if previously used */
03076    if (ast_test_flag(rtp, FLAG_CALLBACK_MODE))
03077       rtp->ioid = ast_io_add(rtp->io, ast_rtp_fd(rtp), rtpread, AST_IO_IN, rtp);
03078 
03079    return 0;
03080 }
03081 
03082 /*! \brief Helper function that sets what an RTP structure is bridged to */
03083 static void p2p_set_bridge(struct ast_rtp *rtp0, struct ast_rtp *rtp1)
03084 {
03085    rtp_bridge_lock(rtp0);
03086         rtp0->bridged = rtp1;
03087    rtp_bridge_unlock(rtp0);
03088 
03089         return;
03090 }
03091 
03092 /*! \brief Bridge loop for partial native bridge (packet2packet) 
03093 
03094    In p2p mode, Asterisk is a very basic RTP proxy, just forwarding whatever
03095    rtp/rtcp we get in to the channel. 
03096    \note this currently only works for Audio
03097 */
03098 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)
03099 {
03100    struct ast_frame *fr = NULL;
03101    struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
03102    int *p0_iod[2] = {NULL, NULL}, *p1_iod[2] = {NULL, NULL};
03103    int p0_callback = 0, p1_callback = 0;
03104    enum ast_bridge_result res = AST_BRIDGE_FAILED;
03105 
03106    /* Okay, setup each RTP structure to do P2P forwarding */
03107    ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
03108    p2p_set_bridge(p0, p1);
03109    ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
03110    p2p_set_bridge(p1, p0);
03111 
03112    /* Activate callback modes if possible */
03113    p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
03114    p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
03115 
03116    /* Now let go of the channel locks and be on our way */
03117    ast_channel_unlock(c0);
03118    ast_channel_unlock(c1);
03119 
03120    /* Go into a loop forwarding frames until we don't need to anymore */
03121    cs[0] = c0;
03122    cs[1] = c1;
03123    cs[2] = NULL;
03124    for (;;) {
03125       /* Check if anything changed */
03126       if ((c0->tech_pvt != pvt0) ||
03127           (c1->tech_pvt != pvt1) ||
03128           (c0->masq || c0->masqr || c1->masq || c1->masqr)) {
03129          if (option_debug > 2)
03130             ast_log(LOG_DEBUG, "p2p-rtp-bridge: Oooh, something is weird, backing out\n");
03131          /* 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 */
03132          if ((c0->masq || c0->masqr) && (fr = ast_read(c0)))
03133             ast_frfree(fr);
03134          if ((c1->masq || c1->masqr) && (fr = ast_read(c1)))
03135             ast_frfree(fr);
03136          res = AST_BRIDGE_RETRY;
03137          break;
03138       }
03139       /* Wait on a channel to feed us a frame */
03140       if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
03141          if (!timeoutms) {
03142             res = AST_BRIDGE_RETRY;
03143             break;
03144          }
03145          if (option_debug > 2)
03146             ast_log(LOG_NOTICE, "p2p-rtp-bridge: Ooh, empty read...\n");
03147          if (ast_check_hangup(c0) || ast_check_hangup(c1))
03148             break;
03149          continue;
03150       }
03151       /* Read in frame from channel */
03152       fr = ast_read(who);
03153       other = (who == c0) ? c1 : c0;
03154       /* Depending on the frame we may need to break out of our bridge */
03155       if (!fr || ((fr->frametype == AST_FRAME_DTMF) &&
03156              ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
03157              ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
03158          /* Record received frame and who */
03159          *fo = fr;
03160          *rc = who;
03161          if (option_debug > 2)
03162             ast_log(LOG_DEBUG, "p2p-rtp-bridge: Ooh, got a %s\n", fr ? "digit" : "hangup");
03163          res = AST_BRIDGE_COMPLETE;
03164          break;
03165       } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
03166          if ((fr->subclass == AST_CONTROL_HOLD) ||
03167              (fr->subclass == AST_CONTROL_UNHOLD) ||
03168              (fr->subclass == AST_CONTROL_VIDUPDATE)) {
03169             /* If we are going on hold, then break callback mode and P2P bridging */
03170             if (fr->subclass == AST_CONTROL_HOLD) {
03171                if (p0_callback)
03172                   p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
03173                if (p1_callback)
03174                   p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
03175                p2p_set_bridge(p0, NULL);
03176                p2p_set_bridge(p1, NULL);
03177             } else if (fr->subclass == AST_CONTROL_UNHOLD) {
03178                /* If we are off hold, then go back to callback mode and P2P bridging */
03179                ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
03180                p2p_set_bridge(p0, p1);
03181                ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
03182                p2p_set_bridge(p1, p0);
03183                p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
03184                p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
03185             }
03186             ast_indicate_data(other, fr->subclass, fr->data, fr->datalen);
03187             ast_frfree(fr);
03188          } else {
03189             *fo = fr;
03190             *rc = who;
03191             if (option_debug > 2)
03192                ast_log(LOG_DEBUG, "p2p-rtp-bridge: Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
03193             res = AST_BRIDGE_COMPLETE;
03194             break;
03195          }
03196       } else {
03197          if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
03198              (fr->frametype == AST_FRAME_DTMF) ||
03199              (fr->frametype == AST_FRAME_VOICE) ||
03200              (fr->frametype == AST_FRAME_VIDEO) ||
03201              (fr->frametype == AST_FRAME_IMAGE) ||
03202              (fr->frametype == AST_FRAME_HTML) ||
03203              (fr->frametype == AST_FRAME_MODEM) ||
03204              (fr->frametype == AST_FRAME_TEXT)) {
03205             ast_write(other, fr);
03206          }
03207 
03208          ast_frfree(fr);
03209       }
03210       /* Swap priority */
03211       cs[2] = cs[0];
03212       cs[0] = cs[1];
03213       cs[1] = cs[2];
03214    }
03215 
03216    /* If we are totally avoiding the core, then restore our link to it */
03217    if (p0_callback)
03218       p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
03219    if (p1_callback)
03220       p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
03221 
03222    /* Break out of the direct bridge */
03223    p2p_set_bridge(p0, NULL);
03224    p2p_set_bridge(p1, NULL);
03225 
03226    return res;
03227 }
03228 
03229 /*! \brief Bridge calls. If possible and allowed, initiate
03230    re-invite so the peers exchange media directly outside 
03231    of Asterisk. 
03232 */
03233 /*! \page AstRTPbridge The Asterisk RTP bridge 
03234    The RTP bridge is called from the channel drivers that are using the RTP
03235    subsystem in Asterisk - like SIP, H.323 and Jingle/Google Talk.
03236 
03237    This bridge aims to offload the Asterisk server by setting up
03238    the media stream directly between the endpoints, keeping the
03239    signalling in Asterisk.
03240 
03241    It checks with the channel driver, using a callback function, if
03242    there are possibilities for a remote bridge.
03243 
03244    If this fails, the bridge hands off to the core bridge. Reasons
03245    can be NAT support needed, DTMF features in audio needed by
03246    the PBX for transfers or spying/monitoring on channels.
03247 
03248    If transcoding is needed - we can't do a remote bridge.
03249    If only NAT support is needed, we're using Asterisk in
03250    RTP proxy mode with the p2p RTP bridge, basically
03251    forwarding incoming audio packets to the outbound
03252    stream on a network level.
03253 
03254    References:
03255    - ast_rtp_bridge()
03256    - ast_channel_early_bridge()
03257    - ast_channel_bridge()
03258 */
03259 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)
03260 {
03261    struct ast_rtp *p0 = NULL, *p1 = NULL;    /* Audio RTP Channels */
03262    struct ast_rtp *vp0 = NULL, *vp1 = NULL;  /* Video RTP channels */
03263    struct ast_rtp_protocol *pr0 = NULL, *pr1 = NULL;
03264    enum ast_rtp_get_result audio_p0_res = AST_RTP_GET_FAILED, video_p0_res = AST_RTP_GET_FAILED;
03265    enum ast_rtp_get_result audio_p1_res = AST_RTP_GET_FAILED, video_p1_res = AST_RTP_GET_FAILED;
03266    enum ast_bridge_result res = AST_BRIDGE_FAILED;
03267    int codec0 = 0, codec1 = 0;
03268    void *pvt0 = NULL, *pvt1 = NULL;
03269 
03270    /* Lock channels */
03271    ast_channel_lock(c0);
03272    while (ast_channel_trylock(c1)) {
03273       ast_channel_unlock(c0);
03274       usleep(1);
03275       ast_channel_lock(c0);
03276    }
03277 
03278    /* Find channel driver interfaces */
03279    if (!(pr0 = get_proto(c0))) {
03280       ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
03281       ast_channel_unlock(c0);
03282       ast_channel_unlock(c1);
03283       return AST_BRIDGE_FAILED;
03284    }
03285    if (!(pr1 = get_proto(c1))) {
03286       ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
03287       ast_channel_unlock(c0);
03288       ast_channel_unlock(c1);
03289       return AST_BRIDGE_FAILED;
03290    }
03291 
03292    /* Get channel specific interface structures */
03293    pvt0 = c0->tech_pvt;
03294    pvt1 = c1->tech_pvt;
03295 
03296    /* Get audio and video interface (if native bridge is possible) */
03297    audio_p0_res = pr0->get_rtp_info(c0, &p0);
03298    video_p0_res = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
03299    audio_p1_res = pr1->get_rtp_info(c1, &p1);
03300    video_p1_res = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
03301 
03302    /* If we are carrying video, and both sides are not reinviting... then fail the native bridge */
03303    if (video_p0_res != AST_RTP_GET_FAILED && (audio_p0_res != AST_RTP_TRY_NATIVE || video_p0_res != AST_RTP_TRY_NATIVE))
03304       audio_p0_res = AST_RTP_GET_FAILED;
03305    if (video_p1_res != AST_RTP_GET_FAILED && (audio_p1_res != AST_RTP_TRY_NATIVE || video_p1_res != AST_RTP_TRY_NATIVE))
03306       audio_p1_res = AST_RTP_GET_FAILED;
03307 
03308    /* Check if a bridge is possible (partial/native) */
03309    if (audio_p0_res == AST_RTP_GET_FAILED || audio_p1_res == AST_RTP_GET_FAILED) {
03310       /* Somebody doesn't want to play... */
03311       ast_channel_unlock(c0);
03312       ast_channel_unlock(c1);
03313       return AST_BRIDGE_FAILED_NOWARN;
03314    }
03315 
03316    /* If we need to feed DTMF frames into the core then only do a partial native bridge */
03317    if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
03318       ast_set_flag(p0, FLAG_P2P_NEED_DTMF);
03319       audio_p0_res = AST_RTP_TRY_PARTIAL;
03320    }
03321 
03322    if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
03323       ast_set_flag(p1, FLAG_P2P_NEED_DTMF);
03324       audio_p1_res = AST_RTP_TRY_PARTIAL;
03325    }
03326 
03327    /* If both sides are not using the same method of DTMF transmission 
03328     * (ie: one is RFC2833, other is INFO... then we can not do direct media. 
03329     * --------------------------------------------------
03330     * | DTMF Mode |  HAS_DTMF  |  Accepts Begin Frames |
03331     * |-----------|------------|-----------------------|
03332     * | Inband    | False      | True                  |
03333     * | RFC2833   | True       | True                  |
03334     * | SIP INFO  | False      | False                 |
03335     * --------------------------------------------------
03336     * However, if DTMF from both channels is being monitored by the core, then
03337     * we can still do packet-to-packet bridging, because passing through the 
03338     * core will handle DTMF mode translation.
03339     */
03340    if ( (ast_test_flag(p0, FLAG_HAS_DTMF) != ast_test_flag(p1, FLAG_HAS_DTMF)) ||
03341        (!c0->tech->send_digit_begin != !c1->tech->send_digit_begin)) {
03342       if (!ast_test_flag(p0, FLAG_P2P_NEED_DTMF) || !ast_test_flag(p1, FLAG_P2P_NEED_DTMF)) {
03343          ast_channel_unlock(c0);
03344          ast_channel_unlock(c1);
03345          return AST_BRIDGE_FAILED_NOWARN;
03346       }
03347       audio_p0_res = AST_RTP_TRY_PARTIAL;
03348       audio_p1_res = AST_RTP_TRY_PARTIAL;
03349    }
03350 
03351    /* Get codecs from both sides */
03352    codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
03353    codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
03354    if (codec0 && codec1 && !(codec0 & codec1)) {
03355       /* Hey, we can't do native bridging if both parties speak different codecs */
03356       if (option_debug > 2)
03357          ast_log(LOG_DEBUG, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
03358       ast_channel_unlock(c0);
03359       ast_channel_unlock(c1);
03360       return AST_BRIDGE_FAILED_NOWARN;
03361    }
03362 
03363    /* If either side can only do a partial bridge, then don't try for a true native bridge */
03364    if (audio_p0_res == AST_RTP_TRY_PARTIAL || audio_p1_res == AST_RTP_TRY_PARTIAL) {
03365       /* In order to do Packet2Packet bridging both sides must be in the same rawread/rawwrite */
03366       if (c0->rawreadformat != c1->rawwriteformat || c1->rawreadformat != c0->rawwriteformat) {
03367          if (option_debug)
03368             ast_log(LOG_DEBUG, "Cannot packet2packet bridge - raw formats are incompatible\n");
03369          ast_channel_unlock(c0);
03370          ast_channel_unlock(c1);
03371          return AST_BRIDGE_FAILED_NOWARN;
03372       }
03373       if (option_verbose > 2)
03374          ast_verbose(VERBOSE_PREFIX_3 "Packet2Packet bridging %s and %s\n", c0->name, c1->name);
03375       res = bridge_p2p_loop(c0, c1, p0, p1, timeoutms, flags, fo, rc, pvt0, pvt1);
03376    } else {
03377       if (option_verbose > 2) 
03378          ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
03379       res = bridge_native_loop(c0, c1, p0, p1, vp0, vp1, pr0, pr1, codec0, codec1, timeoutms, flags, fo, rc, pvt0, pvt1);
03380    }
03381 
03382    return res;
03383 }
03384 
03385 static int rtp_do_debug_ip(int fd, int argc, char *argv[])
03386 {
03387    struct hostent *hp;
03388    struct ast_hostent ahp;
03389    int port = 0;
03390    char *p, *arg;
03391 
03392    if (argc != 4)
03393       return RESULT_SHOWUSAGE;
03394    arg = argv[3];
03395    p = strstr(arg, ":");
03396    if (p) {
03397       *p = '\0';
03398       p++;
03399       port = atoi(p);
03400    }
03401    hp = ast_gethostbyname(arg, &ahp);
03402    if (hp == NULL)
03403       return RESULT_SHOWUSAGE;
03404    rtpdebugaddr.sin_family = AF_INET;
03405    memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
03406    rtpdebugaddr.sin_port = htons(port);
03407    if (port == 0)
03408       ast_cli(fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr.sin_addr));
03409    else
03410       ast_cli(fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr.sin_addr), port);
03411    rtpdebug = 1;
03412    return RESULT_SUCCESS;
03413 }
03414 
03415 static int rtcp_do_debug_ip(int fd, int argc, char *argv[])
03416 {
03417    struct hostent *hp;
03418    struct ast_hostent ahp;
03419    int port = 0;
03420    char *p, *arg;
03421    if (argc != 4)
03422       return RESULT_SHOWUSAGE;
03423 
03424    arg = argv[3];
03425    p = strstr(arg, ":");
03426    if (p) {
03427       *p = '\0';
03428       p++;
03429       port = atoi(p);
03430    }
03431    hp = ast_gethostbyname(arg, &ahp);
03432    if (hp == NULL)
03433       return RESULT_SHOWUSAGE;
03434    rtcpdebugaddr.sin_family = AF_INET;
03435    memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
03436    rtcpdebugaddr.sin_port = htons(port);
03437    if (port == 0)
03438       ast_cli(fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
03439    else
03440       ast_cli(fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
03441    rtcpdebug = 1;
03442    return RESULT_SUCCESS;
03443 }
03444 
03445 static int rtp_do_debug(int fd, int argc, char *argv[])
03446 {
03447    if (argc != 2) {
03448       if (argc != 4)
03449          return RESULT_SHOWUSAGE;
03450       return rtp_do_debug_ip(fd, argc, argv);
03451    }
03452    rtpdebug = 1;
03453    memset(&rtpdebugaddr,0,sizeof(rtpdebugaddr));
03454    ast_cli(fd, "RTP Debugging Enabled\n");
03455    return RESULT_SUCCESS;
03456 }
03457    
03458 static int rtcp_do_debug(int fd, int argc, char *argv[])
03459 {
03460    if (argc != 2) {
03461       if (argc != 4)
03462          return RESULT_SHOWUSAGE;
03463       return rtcp_do_debug_ip(fd, argc, argv);
03464    }
03465    rtcpdebug = 1;
03466    memset(&rtcpdebugaddr,0,sizeof(rtcpdebugaddr));
03467    ast_cli(fd, "RTCP Debugging Enabled\n");
03468    return RESULT_SUCCESS;
03469 }
03470 
03471 static int rtcp_do_stats(int fd, int argc, char *argv[])
03472 {
03473    if (argc != 2)
03474       return RESULT_SHOWUSAGE;
03475    rtcpstats = 1;
03476    ast_cli(fd, "RTCP Stats Enabled\n");
03477    return RESULT_SUCCESS;
03478 }
03479 
03480 static int rtp_no_debug(int fd, int argc, char *argv[])
03481 {
03482    if (argc != 3)
03483       return RESULT_SHOWUSAGE;
03484    rtpdebug = 0;
03485    ast_cli(fd,"RTP Debugging Disabled\n");
03486    return RESULT_SUCCESS;
03487 }
03488 
03489 static int rtcp_no_debug(int fd, int argc, char *argv[])
03490 {
03491    if (argc != 3)
03492       return RESULT_SHOWUSAGE;
03493    rtcpdebug = 0;
03494    ast_cli(fd,"RTCP Debugging Disabled\n");
03495    return RESULT_SUCCESS;
03496 }
03497