Thu Aug 30 20:43:09 2012

Asterisk developer's documentation


res_rtp_asterisk.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2008, 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  * \ingroup rtp_engines
00029  */
00030 
00031 /*** MODULEINFO
00032    <support_level>core</support_level>
00033  ***/
00034 
00035 #include "asterisk.h"
00036 
00037 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 366880 $")
00038 
00039 #include <sys/time.h>
00040 #include <signal.h>
00041 #include <fcntl.h>
00042 
00043 #include "asterisk/stun.h"
00044 #include "asterisk/pbx.h"
00045 #include "asterisk/frame.h"
00046 #include "asterisk/channel.h"
00047 #include "asterisk/acl.h"
00048 #include "asterisk/config.h"
00049 #include "asterisk/lock.h"
00050 #include "asterisk/utils.h"
00051 #include "asterisk/cli.h"
00052 #include "asterisk/manager.h"
00053 #include "asterisk/unaligned.h"
00054 #include "asterisk/module.h"
00055 #include "asterisk/rtp_engine.h"
00056 
00057 #define MAX_TIMESTAMP_SKEW 640
00058 
00059 #define RTP_SEQ_MOD     (1<<16)  /*!< A sequence number can't be more than 16 bits */
00060 #define RTCP_DEFAULT_INTERVALMS   5000 /*!< Default milli-seconds between RTCP reports we send */
00061 #define RTCP_MIN_INTERVALMS       500  /*!< Min milli-seconds between RTCP reports we send */
00062 #define RTCP_MAX_INTERVALMS       60000   /*!< Max milli-seconds between RTCP reports we send */
00063 
00064 #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
00065 #define DEFAULT_RTP_END 31000  /*!< Default maximum port number to end allocating RTP ports at */
00066 
00067 #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
00068 #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
00069 
00070 #define RTCP_PT_FUR     192
00071 #define RTCP_PT_SR      200
00072 #define RTCP_PT_RR      201
00073 #define RTCP_PT_SDES    202
00074 #define RTCP_PT_BYE     203
00075 #define RTCP_PT_APP     204
00076 
00077 #define RTP_MTU      1200
00078 
00079 #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
00080 
00081 #define ZFONE_PROFILE_ID 0x505a
00082 
00083 #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
00084 
00085 extern struct ast_srtp_res *res_srtp;
00086 static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
00087 
00088 static int rtpstart = DEFAULT_RTP_START;        /*!< First port for RTP sessions (set in rtp.conf) */
00089 static int rtpend = DEFAULT_RTP_END;         /*!< Last port for RTP sessions (set in rtp.conf) */
00090 static int rtpdebug;       /*!< Are we debugging? */
00091 static int rtcpdebug;         /*!< Are we debugging RTCP? */
00092 static int rtcpstats;         /*!< Are we debugging RTCP? */
00093 static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
00094 static struct ast_sockaddr rtpdebugaddr;  /*!< Debug packets to/from this host */
00095 static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
00096 static int rtpdebugport;      /*< Debug only RTP packets from IP or IP+Port if port is > 0 */
00097 static int rtcpdebugport;     /*< Debug only RTCP packets from IP or IP+Port if port is > 0 */
00098 #ifdef SO_NO_CHECK
00099 static int nochecksums;
00100 #endif
00101 static int strictrtp;         /*< Only accept RTP frames from a defined source. If we receive an indication of a changing source, enter learning mode. */
00102 static int learning_min_sequential; /*< Number of sequential RTP frames needed from a single source during learning mode to accept new source. */
00103 
00104 enum strict_rtp_state {
00105    STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
00106    STRICT_RTP_LEARN,    /*! Accept next packet as source */
00107    STRICT_RTP_CLOSED,   /*! Drop all RTP packets not coming from source that was learned */
00108 };
00109 
00110 #define FLAG_3389_WARNING               (1 << 0)
00111 #define FLAG_NAT_ACTIVE                 (3 << 1)
00112 #define FLAG_NAT_INACTIVE               (0 << 1)
00113 #define FLAG_NAT_INACTIVE_NOWARN        (1 << 1)
00114 #define FLAG_NEED_MARKER_BIT            (1 << 3)
00115 #define FLAG_DTMF_COMPENSATE            (1 << 4)
00116 
00117 /*! \brief RTP session description */
00118 struct ast_rtp {
00119    int s;
00120    struct ast_frame f;
00121    unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
00122    unsigned int ssrc;      /*!< Synchronization source, RFC 3550, page 10. */
00123    unsigned int themssrc;     /*!< Their SSRC */
00124    unsigned int rxssrc;
00125    unsigned int lastts;
00126    unsigned int lastrxts;
00127    unsigned int lastividtimestamp;
00128    unsigned int lastovidtimestamp;
00129    unsigned int lastitexttimestamp;
00130    unsigned int lastotexttimestamp;
00131    unsigned int lasteventseqn;
00132    int lastrxseqno;                /*!< Last received sequence number */
00133    unsigned short seedrxseqno;     /*!< What sequence number did they start with?*/
00134    unsigned int seedrxts;          /*!< What RTP timestamp did they start with? */
00135    unsigned int rxcount;           /*!< How many packets have we received? */
00136    unsigned int rxoctetcount;      /*!< How many octets have we received? should be rxcount *160*/
00137    unsigned int txcount;           /*!< How many packets have we sent? */
00138    unsigned int txoctetcount;      /*!< How many octets have we sent? (txcount*160)*/
00139    unsigned int cycles;            /*!< Shifted count of sequence number cycles */
00140    double rxjitter;                /*!< Interarrival jitter at the moment in seconds */
00141    double rxtransit;               /*!< Relative transit time for previous packet */
00142    format_t lasttxformat;
00143    format_t lastrxformat;
00144 
00145    int rtptimeout;         /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
00146    int rtpholdtimeout;     /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
00147    int rtpkeepalive;    /*!< Send RTP comfort noice packets for keepalive */
00148 
00149    /* DTMF Reception Variables */
00150    char resp;
00151    unsigned int lastevent;
00152    unsigned int dtmf_duration;     /*!< Total duration in samples since the digit start event */
00153    unsigned int dtmf_timeout;      /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
00154    unsigned int dtmfsamples;
00155    enum ast_rtp_dtmf_mode dtmfmode;/*!< The current DTMF mode of the RTP stream */
00156    /* DTMF Transmission Variables */
00157    unsigned int lastdigitts;
00158    char sending_digit;  /*!< boolean - are we sending digits */
00159    char send_digit;  /*!< digit we are sending */
00160    int send_payload;
00161    int send_duration;
00162    unsigned int flags;
00163    struct timeval rxcore;
00164    struct timeval txcore;
00165    double drxcore;                 /*!< The double representation of the first received packet */
00166    struct timeval lastrx;          /*!< timeval when we last received a packet */
00167    struct timeval dtmfmute;
00168    struct ast_smoother *smoother;
00169    int *ioid;
00170    unsigned short seqno;      /*!< Sequence number, RFC 3550, page 13. */
00171    unsigned short rxseqno;
00172    struct sched_context *sched;
00173    struct io_context *io;
00174    void *data;
00175    struct ast_rtcp *rtcp;
00176    struct ast_rtp *bridged;        /*!< Who we are Packet bridged to */
00177 
00178    enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
00179    struct ast_sockaddr strict_rtp_address;  /*!< Remote address information for strict RTP purposes */
00180    struct ast_sockaddr alt_rtp_address; /*!<Alternate remote address information */
00181 
00182    /*
00183     * Learning mode values based on pjmedia's probation mode.  Many of these values are redundant to the above,
00184     * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
00185     */
00186    uint16_t learning_max_seq;    /*!< Highest sequence number heard */
00187    int learning_probation;    /*!< Sequential packets untill source is valid */
00188 
00189    struct rtp_red *red;
00190 };
00191 
00192 /*!
00193  * \brief Structure defining an RTCP session.
00194  *
00195  * The concept "RTCP session" is not defined in RFC 3550, but since
00196  * this structure is analogous to ast_rtp, which tracks a RTP session,
00197  * it is logical to think of this as a RTCP session.
00198  *
00199  * RTCP packet is defined on page 9 of RFC 3550.
00200  *
00201  */
00202 struct ast_rtcp {
00203    int rtcp_info;
00204    int s;            /*!< Socket */
00205    struct ast_sockaddr us;    /*!< Socket representation of the local endpoint. */
00206    struct ast_sockaddr them;  /*!< Socket representation of the remote endpoint. */
00207    unsigned int soc;    /*!< What they told us */
00208    unsigned int spc;    /*!< What they told us */
00209    unsigned int themrxlsr;    /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
00210    struct timeval rxlsr;      /*!< Time when we got their last SR */
00211    struct timeval txlsr;      /*!< Time when we sent or last SR*/
00212    unsigned int expected_prior;  /*!< no. packets in previous interval */
00213    unsigned int received_prior;  /*!< no. packets received in previous interval */
00214    int schedid;         /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
00215    unsigned int rr_count;     /*!< number of RRs we've sent, not including report blocks in SR's */
00216    unsigned int sr_count;     /*!< number of SRs we've sent */
00217    unsigned int lastsrtxcount;     /*!< Transmit packet count when last SR sent */
00218    double accumulated_transit;   /*!< accumulated a-dlsr-lsr */
00219    double rtt;       /*!< Last reported rtt */
00220    unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
00221    unsigned int reported_lost;   /*!< Reported lost packets in their RR */
00222 
00223    double reported_maxjitter;
00224    double reported_minjitter;
00225    double reported_normdev_jitter;
00226    double reported_stdev_jitter;
00227    unsigned int reported_jitter_count;
00228 
00229    double reported_maxlost;
00230    double reported_minlost;
00231    double reported_normdev_lost;
00232    double reported_stdev_lost;
00233 
00234    double rxlost;
00235    double maxrxlost;
00236    double minrxlost;
00237    double normdev_rxlost;
00238    double stdev_rxlost;
00239    unsigned int rxlost_count;
00240 
00241    double maxrxjitter;
00242    double minrxjitter;
00243    double normdev_rxjitter;
00244    double stdev_rxjitter;
00245    unsigned int rxjitter_count;
00246    double maxrtt;
00247    double minrtt;
00248    double normdevrtt;
00249    double stdevrtt;
00250    unsigned int rtt_count;
00251 };
00252 
00253 struct rtp_red {
00254    struct ast_frame t140;  /*!< Primary data  */
00255    struct ast_frame t140red;   /*!< Redundant t140*/
00256    unsigned char pt[AST_RED_MAX_GENERATION];  /*!< Payload types for redundancy data */
00257    unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
00258    unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
00259    int num_gen; /*!< Number of generations */
00260    int schedid; /*!< Timer id */
00261    int ti; /*!< How long to buffer data before send */
00262    unsigned char t140red_data[64000];
00263    unsigned char buf_data[64000]; /*!< buffered primary data */
00264    int hdrlen;
00265    long int prev_ts;
00266 };
00267 
00268 AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
00269 
00270 /* Forward Declarations */
00271 static int ast_rtp_new(struct ast_rtp_instance *instance, struct sched_context *sched, struct ast_sockaddr *addr, void *data);
00272 static int ast_rtp_destroy(struct ast_rtp_instance *instance);
00273 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
00274 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
00275 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
00276 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
00277 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
00278 static void ast_rtp_update_source(struct ast_rtp_instance *instance);
00279 static void ast_rtp_change_source(struct ast_rtp_instance *instance);
00280 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
00281 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
00282 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
00283 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
00284 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
00285 static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
00286 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
00287 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
00288 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
00289 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
00290 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
00291 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
00292 static void ast_rtp_stop(struct ast_rtp_instance *instance);
00293 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
00294 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
00295 
00296 /* RTP Engine Declaration */
00297 static struct ast_rtp_engine asterisk_rtp_engine = {
00298    .name = "asterisk",
00299    .new = ast_rtp_new,
00300    .destroy = ast_rtp_destroy,
00301    .dtmf_begin = ast_rtp_dtmf_begin,
00302    .dtmf_end = ast_rtp_dtmf_end,
00303    .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
00304    .dtmf_mode_set = ast_rtp_dtmf_mode_set,
00305    .dtmf_mode_get = ast_rtp_dtmf_mode_get,
00306    .update_source = ast_rtp_update_source,
00307    .change_source = ast_rtp_change_source,
00308    .write = ast_rtp_write,
00309    .read = ast_rtp_read,
00310    .prop_set = ast_rtp_prop_set,
00311    .fd = ast_rtp_fd,
00312    .remote_address_set = ast_rtp_remote_address_set,
00313    .alt_remote_address_set = ast_rtp_alt_remote_address_set,
00314    .red_init = rtp_red_init,
00315    .red_buffer = rtp_red_buffer,
00316    .local_bridge = ast_rtp_local_bridge,
00317    .get_stat = ast_rtp_get_stat,
00318    .dtmf_compatible = ast_rtp_dtmf_compatible,
00319    .stun_request = ast_rtp_stun_request,
00320    .stop = ast_rtp_stop,
00321    .qos = ast_rtp_qos_set,
00322    .sendcng = ast_rtp_sendcng,
00323 };
00324 
00325 static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
00326 {
00327    if (!rtpdebug) {
00328       return 0;
00329    }
00330    if (!ast_sockaddr_isnull(&rtpdebugaddr)) {
00331       if (rtpdebugport) {
00332          return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
00333       } else {
00334          return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
00335       }
00336    }
00337 
00338    return 1;
00339 }
00340 
00341 static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
00342 {
00343    if (!rtcpdebug) {
00344       return 0;
00345    }
00346    if (!ast_sockaddr_isnull(&rtcpdebugaddr)) {
00347       if (rtcpdebugport) {
00348          return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
00349       } else {
00350          return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
00351       }
00352    }
00353 
00354    return 1;
00355 }
00356 
00357 static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
00358 {
00359    int len;
00360    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00361    struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
00362 
00363    if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
00364       return len;
00365    }
00366 
00367    if (res_srtp && srtp && res_srtp->unprotect(srtp, buf, &len, rtcp) < 0) {
00368       return -1;
00369    }
00370 
00371    return len;
00372 }
00373 
00374 static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
00375 {
00376    return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
00377 }
00378 
00379 static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
00380 {
00381    return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
00382 }
00383 
00384 static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
00385 {
00386    int len = size;
00387    void *temp = buf;
00388    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00389    struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
00390 
00391    if (res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
00392       return -1;
00393    }
00394 
00395    return ast_sendto(rtcp ? rtp->rtcp->s : rtp->s, temp, len, flags, sa);
00396 }
00397 
00398 static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
00399 {
00400    return __rtp_sendto(instance, buf, size, flags, sa, 1);
00401 }
00402 
00403 static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
00404 {
00405    return __rtp_sendto(instance, buf, size, flags, sa, 0);
00406 }
00407 
00408 static int rtp_get_rate(format_t subclass)
00409 {
00410    return (subclass == AST_FORMAT_G722) ? 8000 : ast_format_rate(subclass);
00411 }
00412 
00413 static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
00414 {
00415    unsigned int interval;
00416    /*! \todo XXX Do a more reasonable calculation on this one
00417     * Look in RFC 3550 Section A.7 for an example*/
00418    interval = rtcpinterval;
00419    return interval;
00420 }
00421 
00422 /*! \brief Calculate normal deviation */
00423 static double normdev_compute(double normdev, double sample, unsigned int sample_count)
00424 {
00425    normdev = normdev * sample_count + sample;
00426    sample_count++;
00427 
00428    return normdev / sample_count;
00429 }
00430 
00431 static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
00432 {
00433 /*
00434       for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
00435       return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
00436       we can compute the sigma^2 and that way we would have to do the sqrt only 1 time at the end and would save another pow 2 compute
00437       optimized formula
00438 */
00439 #define SQUARE(x) ((x) * (x))
00440 
00441    stddev = sample_count * stddev;
00442    sample_count++;
00443 
00444    return stddev +
00445       ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
00446       ( SQUARE(sample - normdev_curent) / sample_count );
00447 
00448 #undef SQUARE
00449 }
00450 
00451 static int create_new_socket(const char *type, int af)
00452 {
00453    int sock = socket(af, SOCK_DGRAM, 0);
00454 
00455    if (sock < 0) {
00456       if (!type) {
00457          type = "RTP/RTCP";
00458       }
00459       ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
00460    } else {
00461       long flags = fcntl(sock, F_GETFL);
00462       fcntl(sock, F_SETFL, flags | O_NONBLOCK);
00463 #ifdef SO_NO_CHECK
00464       if (nochecksums) {
00465          setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
00466       }
00467 #endif
00468    }
00469 
00470    return sock;
00471 }
00472 
00473 /*!
00474  * \internal
00475  * \brief Initializes sequence values and probation for learning mode.
00476  * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
00477  *
00478  * \param rtp pointer to rtp struct used with the received rtp packet.
00479  * \param seq sequence number read from the rtp header
00480  */
00481 static void rtp_learning_seq_init(struct ast_rtp *rtp, uint16_t seq)
00482 {
00483    rtp->learning_max_seq = seq - 1;
00484    rtp->learning_probation = learning_min_sequential;
00485 }
00486 
00487 /*!
00488  * \internal
00489  * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
00490  * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
00491  *
00492  * \param rtp pointer to rtp struct used with the received rtp packet.
00493  * \param seq sequence number read from the rtp header
00494  * \return boolean value indicating if probation mode is active at the end of the function
00495  */
00496 static int rtp_learning_rtp_seq_update(struct ast_rtp *rtp, uint16_t seq)
00497 {
00498    int probation = 1;
00499 
00500    ast_debug(1, "%p -- probation = %d, seq = %d\n", rtp, rtp->learning_probation, seq);
00501 
00502    if (seq == rtp->learning_max_seq + 1) {
00503       /* packet is in sequence */
00504       rtp->learning_probation--;
00505       rtp->learning_max_seq = seq;
00506       if (rtp->learning_probation == 0) {
00507          probation = 0;
00508       }
00509    } else {
00510       rtp->learning_probation = learning_min_sequential - 1;
00511       rtp->learning_max_seq = seq;
00512    }
00513 
00514    return probation;
00515 }
00516 
00517 static int ast_rtp_new(struct ast_rtp_instance *instance,
00518              struct sched_context *sched, struct ast_sockaddr *addr,
00519              void *data)
00520 {
00521    struct ast_rtp *rtp = NULL;
00522    int x, startplace;
00523 
00524    /* Create a new RTP structure to hold all of our data */
00525    if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
00526       return -1;
00527    }
00528 
00529    /* Set default parameters on the newly created RTP structure */
00530    rtp->ssrc = ast_random();
00531    rtp->seqno = ast_random() & 0xffff;
00532    rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
00533    if (strictrtp) {
00534       rtp_learning_seq_init(rtp, (uint16_t)rtp->seqno);
00535    }
00536 
00537    /* Create a new socket for us to listen on and use */
00538    if ((rtp->s =
00539         create_new_socket("RTP",
00540                 ast_sockaddr_is_ipv4(addr) ? AF_INET  :
00541                 ast_sockaddr_is_ipv6(addr) ? AF_INET6 : -1)) < 0) {
00542       ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
00543       ast_free(rtp);
00544       return -1;
00545    }
00546 
00547    /* Now actually find a free RTP port to use */
00548    x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
00549    x = x & ~1;
00550    startplace = x;
00551 
00552    for (;;) {
00553       ast_sockaddr_set_port(addr, x);
00554       /* Try to bind, this will tell us whether the port is available or not */
00555       if (!ast_bind(rtp->s, addr)) {
00556          ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
00557          ast_rtp_instance_set_local_address(instance, addr);
00558          break;
00559       }
00560 
00561       x += 2;
00562       if (x > rtpend) {
00563          x = (rtpstart + 1) & ~1;
00564       }
00565 
00566       /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
00567       if (x == startplace || errno != EADDRINUSE) {
00568          ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
00569          close(rtp->s);
00570          ast_free(rtp);
00571          return -1;
00572       }
00573    }
00574 
00575    /* Record any information we may need */
00576    rtp->sched = sched;
00577 
00578    /* Associate the RTP structure with the RTP instance and be done */
00579    ast_rtp_instance_set_data(instance, rtp);
00580 
00581    return 0;
00582 }
00583 
00584 static int ast_rtp_destroy(struct ast_rtp_instance *instance)
00585 {
00586    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00587 
00588    /* Destroy the smoother that was smoothing out audio if present */
00589    if (rtp->smoother) {
00590       ast_smoother_free(rtp->smoother);
00591    }
00592 
00593    /* Close our own socket so we no longer get packets */
00594    if (rtp->s > -1) {
00595       close(rtp->s);
00596    }
00597 
00598    /* Destroy RTCP if it was being used */
00599    if (rtp->rtcp) {
00600       /*
00601        * It is not possible for there to be an active RTCP scheduler
00602        * entry at this point since it holds a reference to the
00603        * RTP instance while it's active.
00604        */
00605       close(rtp->rtcp->s);
00606       ast_free(rtp->rtcp);
00607    }
00608 
00609    /* Destroy RED if it was being used */
00610    if (rtp->red) {
00611       AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
00612       ast_free(rtp->red);
00613    }
00614 
00615    /* Finally destroy ourselves */
00616    ast_free(rtp);
00617 
00618    return 0;
00619 }
00620 
00621 static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
00622 {
00623    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00624    rtp->dtmfmode = dtmf_mode;
00625    return 0;
00626 }
00627 
00628 static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
00629 {
00630    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00631    return rtp->dtmfmode;
00632 }
00633 
00634 static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
00635 {
00636    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00637    struct ast_sockaddr remote_address = { {0,} };
00638    int hdrlen = 12, res = 0, i = 0, payload = 101;
00639    char data[256];
00640    unsigned int *rtpheader = (unsigned int*)data;
00641 
00642    ast_rtp_instance_get_remote_address(instance, &remote_address);
00643 
00644    /* If we have no remote address information bail out now */
00645    if (ast_sockaddr_isnull(&remote_address)) {
00646       return -1;
00647    }
00648 
00649    /* Convert given digit into what we want to transmit */
00650    if ((digit <= '9') && (digit >= '0')) {
00651       digit -= '0';
00652    } else if (digit == '*') {
00653       digit = 10;
00654    } else if (digit == '#') {
00655       digit = 11;
00656    } else if ((digit >= 'A') && (digit <= 'D')) {
00657       digit = digit - 'A' + 12;
00658    } else if ((digit >= 'a') && (digit <= 'd')) {
00659       digit = digit - 'a' + 12;
00660    } else {
00661       ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
00662       return -1;
00663    }
00664 
00665    /* Grab the payload that they expect the RFC2833 packet to be received in */
00666    payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, AST_RTP_DTMF);
00667 
00668    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
00669    rtp->send_duration = 160;
00670    rtp->lastdigitts = rtp->lastts + rtp->send_duration;
00671 
00672    /* Create the actual packet that we will be sending */
00673    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
00674    rtpheader[1] = htonl(rtp->lastdigitts);
00675    rtpheader[2] = htonl(rtp->ssrc);
00676 
00677    /* Actually send the packet */
00678    for (i = 0; i < 2; i++) {
00679       rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
00680       res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address);
00681       if (res < 0) {
00682          ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
00683             ast_sockaddr_stringify(&remote_address),
00684             strerror(errno));
00685       }
00686       if (rtp_debug_test_addr(&remote_address)) {
00687          ast_verbose("Sent RTP DTMF packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
00688                 ast_sockaddr_stringify(&remote_address),
00689                 payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
00690       }
00691       rtp->seqno++;
00692       rtp->send_duration += 160;
00693       rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
00694    }
00695 
00696    /* Record that we are in the process of sending a digit and information needed to continue doing so */
00697    rtp->sending_digit = 1;
00698    rtp->send_digit = digit;
00699    rtp->send_payload = payload;
00700 
00701    return 0;
00702 }
00703 
00704 static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
00705 {
00706    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00707    struct ast_sockaddr remote_address = { {0,} };
00708    int hdrlen = 12, res = 0;
00709    char data[256];
00710    unsigned int *rtpheader = (unsigned int*)data;
00711 
00712    ast_rtp_instance_get_remote_address(instance, &remote_address);
00713 
00714    /* Make sure we know where the other side is so we can send them the packet */
00715    if (ast_sockaddr_isnull(&remote_address)) {
00716       return -1;
00717    }
00718 
00719    /* Actually create the packet we will be sending */
00720    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
00721    rtpheader[1] = htonl(rtp->lastdigitts);
00722    rtpheader[2] = htonl(rtp->ssrc);
00723    rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
00724    rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
00725 
00726    /* Boom, send it on out */
00727    res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address);
00728    if (res < 0) {
00729       ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
00730          ast_sockaddr_stringify(&remote_address),
00731          strerror(errno));
00732    }
00733 
00734    if (rtp_debug_test_addr(&remote_address)) {
00735       ast_verbose("Sent RTP DTMF packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
00736              ast_sockaddr_stringify(&remote_address),
00737              rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
00738    }
00739 
00740    /* And now we increment some values for the next time we swing by */
00741    rtp->seqno++;
00742    rtp->send_duration += 160;
00743 
00744    return 0;
00745 }
00746 
00747 static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
00748 {
00749    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00750    struct ast_sockaddr remote_address = { {0,} };
00751    int hdrlen = 12, res = 0, i = 0;
00752    char data[256];
00753    unsigned int *rtpheader = (unsigned int*)data;
00754    unsigned int measured_samples;
00755 
00756    ast_rtp_instance_get_remote_address(instance, &remote_address);
00757 
00758    /* Make sure we know where the remote side is so we can send them the packet we construct */
00759    if (ast_sockaddr_isnull(&remote_address)) {
00760       return -1;
00761    }
00762 
00763    /* Convert the given digit to the one we are going to send */
00764    if ((digit <= '9') && (digit >= '0')) {
00765       digit -= '0';
00766    } else if (digit == '*') {
00767       digit = 10;
00768    } else if (digit == '#') {
00769       digit = 11;
00770    } else if ((digit >= 'A') && (digit <= 'D')) {
00771       digit = digit - 'A' + 12;
00772    } else if ((digit >= 'a') && (digit <= 'd')) {
00773       digit = digit - 'a' + 12;
00774    } else {
00775       ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
00776       return -1;
00777    }
00778 
00779    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
00780 
00781    if (duration > 0 && (measured_samples = duration * rtp_get_rate(rtp->f.subclass.codec) / 1000) > rtp->send_duration) {
00782       ast_debug(2, "Adjusting final end duration from %u to %u\n", rtp->send_duration, measured_samples);
00783       rtp->send_duration = measured_samples;
00784    }
00785 
00786    /* Construct the packet we are going to send */
00787    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
00788    rtpheader[1] = htonl(rtp->lastdigitts);
00789    rtpheader[2] = htonl(rtp->ssrc);
00790    rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
00791    rtpheader[3] |= htonl((1 << 23));
00792    rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
00793 
00794    /* Send it 3 times, that's the magical number */
00795    for (i = 0; i < 3; i++) {
00796       res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address);
00797       if (res < 0) {
00798          ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
00799             ast_sockaddr_stringify(&remote_address),
00800             strerror(errno));
00801       }
00802       if (rtp_debug_test_addr(&remote_address)) {
00803          ast_verbose("Sent RTP DTMF packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
00804                 ast_sockaddr_stringify(&remote_address),
00805                 rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
00806       }
00807    }
00808 
00809    /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
00810    rtp->lastts += rtp->send_duration;
00811    rtp->sending_digit = 0;
00812    rtp->send_digit = 0;
00813 
00814    return 0;
00815 }
00816 
00817 static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
00818 {
00819    return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
00820 }
00821 
00822 static void ast_rtp_update_source(struct ast_rtp_instance *instance)
00823 {
00824    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00825 
00826    /* We simply set this bit so that the next packet sent will have the marker bit turned on */
00827    ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
00828    ast_debug(3, "Setting the marker bit due to a source update\n");
00829 
00830    return;
00831 }
00832 
00833 static void ast_rtp_change_source(struct ast_rtp_instance *instance)
00834 {
00835    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00836    struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
00837    unsigned int ssrc = ast_random();
00838 
00839    if (!rtp->lastts) {
00840       ast_debug(3, "Not changing SSRC since we haven't sent any RTP yet\n");
00841       return;
00842    }
00843 
00844    /* We simply set this bit so that the next packet sent will have the marker bit turned on */
00845    ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
00846 
00847    ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
00848 
00849    if (srtp) {
00850       ast_debug(3, "Changing ssrc for SRTP from %u to %u\n", rtp->ssrc, ssrc);
00851       res_srtp->change_source(srtp, rtp->ssrc, ssrc);
00852    }
00853 
00854    rtp->ssrc = ssrc;
00855 
00856    return;
00857 }
00858 
00859 static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
00860 {
00861    struct timeval t;
00862    long ms;
00863 
00864    if (ast_tvzero(rtp->txcore)) {
00865       rtp->txcore = ast_tvnow();
00866       rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
00867    }
00868 
00869    t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
00870    if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
00871       ms = 0;
00872    }
00873    rtp->txcore = t;
00874 
00875    return (unsigned int) ms;
00876 }
00877 
00878 static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
00879 {
00880    unsigned int sec, usec, frac;
00881    sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
00882    usec = tv.tv_usec;
00883    frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
00884    *msw = sec;
00885    *lsw = frac;
00886 }
00887 
00888 /*! \brief Send RTCP recipient's report */
00889 static int ast_rtcp_write_rr(struct ast_rtp_instance *instance)
00890 {
00891    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00892    int res;
00893    int len = 32;
00894    unsigned int lost;
00895    unsigned int extended;
00896    unsigned int expected;
00897    unsigned int expected_interval;
00898    unsigned int received_interval;
00899    int lost_interval;
00900    struct timeval now;
00901    unsigned int *rtcpheader;
00902    char bdata[1024];
00903    struct timeval dlsr;
00904    int fraction;
00905    int rate = rtp_get_rate(rtp->f.subclass.codec);
00906 
00907    double rxlost_current;
00908 
00909    if (!rtp || !rtp->rtcp)
00910       return 0;
00911 
00912    if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
00913       /*
00914        * RTCP was stopped.
00915        */
00916       return 0;
00917    }
00918 
00919    extended = rtp->cycles + rtp->lastrxseqno;
00920    expected = extended - rtp->seedrxseqno + 1;
00921    lost = expected - rtp->rxcount;
00922    expected_interval = expected - rtp->rtcp->expected_prior;
00923    rtp->rtcp->expected_prior = expected;
00924    received_interval = rtp->rxcount - rtp->rtcp->received_prior;
00925    rtp->rtcp->received_prior = rtp->rxcount;
00926    lost_interval = expected_interval - received_interval;
00927 
00928    if (lost_interval <= 0)
00929       rtp->rtcp->rxlost = 0;
00930    else rtp->rtcp->rxlost = rtp->rtcp->rxlost;
00931    if (rtp->rtcp->rxlost_count == 0)
00932       rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
00933    if (lost_interval < rtp->rtcp->minrxlost)
00934       rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
00935    if (lost_interval > rtp->rtcp->maxrxlost)
00936       rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
00937 
00938    rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->rxlost_count);
00939    rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->normdev_rxlost, rxlost_current, rtp->rtcp->rxlost_count);
00940    rtp->rtcp->normdev_rxlost = rxlost_current;
00941    rtp->rtcp->rxlost_count++;
00942 
00943    if (expected_interval == 0 || lost_interval <= 0)
00944       fraction = 0;
00945    else
00946       fraction = (lost_interval << 8) / expected_interval;
00947    gettimeofday(&now, NULL);
00948    timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
00949    rtcpheader = (unsigned int *)bdata;
00950    rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
00951    rtcpheader[1] = htonl(rtp->ssrc);
00952    rtcpheader[2] = htonl(rtp->themssrc);
00953    rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
00954    rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
00955    rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * rate));
00956    rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
00957    rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
00958 
00959    /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
00960      it can change mid call, and SDES can't) */
00961    rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
00962    rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
00963    rtcpheader[(len/4)+2] = htonl(0x01 << 24);              /* Empty for the moment */
00964    len += 12;
00965 
00966    res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &rtp->rtcp->them);
00967 
00968    if (res < 0) {
00969       ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
00970       return 0;
00971    }
00972 
00973    rtp->rtcp->rr_count++;
00974    if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
00975       ast_verbose("\n* Sending RTCP RR to %s\n"
00976          "  Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
00977          "  IA jitter: %.4f\n"
00978          "  Their last SR: %u\n"
00979              "  DLSR: %4.4f (sec)\n\n",
00980              ast_sockaddr_stringify(&rtp->rtcp->them),
00981              rtp->ssrc, rtp->themssrc, fraction, lost,
00982              rtp->rxjitter,
00983              rtp->rtcp->themrxlsr,
00984              (double)(ntohl(rtcpheader[7])/65536.0));
00985    }
00986 
00987    return res;
00988 }
00989 
00990 /*! \brief Send RTCP sender's report */
00991 static int ast_rtcp_write_sr(struct ast_rtp_instance *instance)
00992 {
00993    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
00994    int res;
00995    int len = 0;
00996    struct timeval now;
00997    unsigned int now_lsw;
00998    unsigned int now_msw;
00999    unsigned int *rtcpheader;
01000    unsigned int lost;
01001    unsigned int extended;
01002    unsigned int expected;
01003    unsigned int expected_interval;
01004    unsigned int received_interval;
01005    int lost_interval;
01006    int fraction;
01007    struct timeval dlsr;
01008    char bdata[512];
01009    int rate = rtp_get_rate(rtp->f.subclass.codec);
01010 
01011    if (!rtp || !rtp->rtcp)
01012       return 0;
01013 
01014    if (ast_sockaddr_isnull(&rtp->rtcp->them)) {  /* This'll stop rtcp for this rtp session */
01015       /*
01016        * RTCP was stopped.
01017        */
01018       return 0;
01019    }
01020 
01021    gettimeofday(&now, NULL);
01022    timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
01023    rtcpheader = (unsigned int *)bdata;
01024    rtcpheader[1] = htonl(rtp->ssrc);               /* Our SSRC */
01025    rtcpheader[2] = htonl(now_msw);                 /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
01026    rtcpheader[3] = htonl(now_lsw);                 /* now, LSW */
01027    rtcpheader[4] = htonl(rtp->lastts);             /* FIXME shouldn't be that, it should be now */
01028    rtcpheader[5] = htonl(rtp->txcount);            /* No. packets sent */
01029    rtcpheader[6] = htonl(rtp->txoctetcount);       /* No. bytes sent */
01030    len += 28;
01031 
01032    extended = rtp->cycles + rtp->lastrxseqno;
01033    expected = extended - rtp->seedrxseqno + 1;
01034    if (rtp->rxcount > expected)
01035       expected += rtp->rxcount - expected;
01036    lost = expected - rtp->rxcount;
01037    expected_interval = expected - rtp->rtcp->expected_prior;
01038    rtp->rtcp->expected_prior = expected;
01039    received_interval = rtp->rxcount - rtp->rtcp->received_prior;
01040    rtp->rtcp->received_prior = rtp->rxcount;
01041    lost_interval = expected_interval - received_interval;
01042    if (expected_interval == 0 || lost_interval <= 0)
01043       fraction = 0;
01044    else
01045       fraction = (lost_interval << 8) / expected_interval;
01046    timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
01047    rtcpheader[7] = htonl(rtp->themssrc);
01048    rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
01049    rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
01050    rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * rate));
01051    rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
01052    rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
01053    len += 24;
01054 
01055    rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
01056 
01057    /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
01058    /* it can change mid call, and SDES can't) */
01059    rtcpheader[len/4]     = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
01060    rtcpheader[(len/4)+1] = htonl(rtp->ssrc);               /* Our SSRC */
01061    rtcpheader[(len/4)+2] = htonl(0x01 << 24);                    /* Empty for the moment */
01062    len += 12;
01063 
01064    res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &rtp->rtcp->them);
01065    if (res < 0) {
01066       ast_log(LOG_ERROR, "RTCP SR transmission error to %s, rtcp halted %s\n",
01067          ast_sockaddr_stringify(&rtp->rtcp->them),
01068          strerror(errno));
01069       return 0;
01070    }
01071 
01072    /* FIXME Don't need to get a new one */
01073    gettimeofday(&rtp->rtcp->txlsr, NULL);
01074    rtp->rtcp->sr_count++;
01075 
01076    rtp->rtcp->lastsrtxcount = rtp->txcount;
01077 
01078    if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
01079       ast_verbose("* Sent RTCP SR to %s\n", ast_sockaddr_stringify(&rtp->rtcp->them));
01080       ast_verbose("  Our SSRC: %u\n", rtp->ssrc);
01081       ast_verbose("  Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
01082       ast_verbose("  Sent(RTP): %u\n", rtp->lastts);
01083       ast_verbose("  Sent packets: %u\n", rtp->txcount);
01084       ast_verbose("  Sent octets: %u\n", rtp->txoctetcount);
01085       ast_verbose("  Report block:\n");
01086       ast_verbose("  Fraction lost: %u\n", fraction);
01087       ast_verbose("  Cumulative loss: %u\n", lost);
01088       ast_verbose("  IA jitter: %.4f\n", rtp->rxjitter);
01089       ast_verbose("  Their last SR: %u\n", rtp->rtcp->themrxlsr);
01090       ast_verbose("  DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
01091    }
01092    manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To: %s\r\n"
01093                    "OurSSRC: %u\r\n"
01094                    "SentNTP: %u.%010u\r\n"
01095                    "SentRTP: %u\r\n"
01096                    "SentPackets: %u\r\n"
01097                    "SentOctets: %u\r\n"
01098                    "ReportBlock:\r\n"
01099                    "FractionLost: %u\r\n"
01100                    "CumulativeLoss: %u\r\n"
01101                    "IAJitter: %.4f\r\n"
01102                    "TheirLastSR: %u\r\n"
01103             "DLSR: %4.4f (sec)\r\n",
01104             ast_sockaddr_stringify(&rtp->rtcp->them),
01105             rtp->ssrc,
01106             (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
01107             rtp->lastts,
01108             rtp->txcount,
01109             rtp->txoctetcount,
01110             fraction,
01111             lost,
01112             rtp->rxjitter,
01113             rtp->rtcp->themrxlsr,
01114             (double)(ntohl(rtcpheader[12])/65536.0));
01115    return res;
01116 }
01117 
01118 /*! \brief Write and RTCP packet to the far end
01119  * \note Decide if we are going to send an SR (with Reception Block) or RR
01120  * RR is sent if we have not sent any rtp packets in the previous interval */
01121 static int ast_rtcp_write(const void *data)
01122 {
01123    struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
01124    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01125    int res;
01126 
01127    if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
01128       ao2_ref(instance, -1);
01129       return 0;
01130    }
01131 
01132    if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
01133       res = ast_rtcp_write_sr(instance);
01134    } else {
01135       res = ast_rtcp_write_rr(instance);
01136    }
01137 
01138    if (!res) {
01139       /* 
01140        * Not being rescheduled.
01141        */
01142       ao2_ref(instance, -1);
01143       rtp->rtcp->schedid = -1;
01144    }
01145 
01146    return res;
01147 }
01148 
01149 static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
01150 {
01151    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01152    int pred, mark = 0;
01153    unsigned int ms = calc_txstamp(rtp, &frame->delivery);
01154    struct ast_sockaddr remote_address = { {0,} };
01155    int rate = rtp_get_rate(frame->subclass.codec) / 1000;
01156 
01157    if (frame->subclass.codec == AST_FORMAT_G722) {
01158       frame->samples /= 2;
01159    }
01160 
01161    if (rtp->sending_digit) {
01162       return 0;
01163    }
01164 
01165    if (frame->frametype == AST_FRAME_VOICE) {
01166       pred = rtp->lastts + frame->samples;
01167 
01168       /* Re-calculate last TS */
01169       rtp->lastts = rtp->lastts + ms * rate;
01170       if (ast_tvzero(frame->delivery)) {
01171          /* If this isn't an absolute delivery time, Check if it is close to our prediction,
01172             and if so, go with our prediction */
01173          if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
01174             rtp->lastts = pred;
01175          } else {
01176             ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
01177             mark = 1;
01178          }
01179       }
01180    } else if (frame->frametype == AST_FRAME_VIDEO) {
01181       mark = frame->subclass.codec & 0x1;
01182       pred = rtp->lastovidtimestamp + frame->samples;
01183       /* Re-calculate last TS */
01184       rtp->lastts = rtp->lastts + ms * 90;
01185       /* If it's close to our prediction, go for it */
01186       if (ast_tvzero(frame->delivery)) {
01187          if (abs(rtp->lastts - pred) < 7200) {
01188             rtp->lastts = pred;
01189             rtp->lastovidtimestamp += frame->samples;
01190          } else {
01191             ast_debug(3, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, frame->samples);
01192             rtp->lastovidtimestamp = rtp->lastts;
01193          }
01194       }
01195    } else {
01196       pred = rtp->lastotexttimestamp + frame->samples;
01197       /* Re-calculate last TS */
01198       rtp->lastts = rtp->lastts + ms;
01199       /* If it's close to our prediction, go for it */
01200       if (ast_tvzero(frame->delivery)) {
01201          if (abs(rtp->lastts - pred) < 7200) {
01202             rtp->lastts = pred;
01203             rtp->lastotexttimestamp += frame->samples;
01204          } else {
01205             ast_debug(3, "Difference is %d, ms is %d, pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, rtp->lastts, pred, frame->samples);
01206             rtp->lastotexttimestamp = rtp->lastts;
01207          }
01208       }
01209    }
01210 
01211    /* If we have been explicitly told to set the marker bit then do so */
01212    if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
01213       mark = 1;
01214       ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
01215    }
01216 
01217    /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
01218    if (rtp->lastts > rtp->lastdigitts) {
01219       rtp->lastdigitts = rtp->lastts;
01220    }
01221 
01222    if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
01223       rtp->lastts = frame->ts * rate;
01224    }
01225 
01226    ast_rtp_instance_get_remote_address(instance, &remote_address);
01227 
01228    /* If we know the remote address construct a packet and send it out */
01229    if (!ast_sockaddr_isnull(&remote_address)) {
01230       int hdrlen = 12, res;
01231       unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
01232 
01233       put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
01234       put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
01235       put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
01236 
01237       if ((res = rtp_sendto(instance, (void *)rtpheader, frame->datalen + hdrlen, 0, &remote_address)) < 0) {
01238          if (!ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT) && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
01239             ast_debug(1, "RTP Transmission error of packet %d to %s: %s\n",
01240                  rtp->seqno,
01241                  ast_sockaddr_stringify(&remote_address),
01242                  strerror(errno));
01243          } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
01244             /* Only give this error message once if we are not RTP debugging */
01245             if (option_debug || rtpdebug)
01246                ast_debug(0, "RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
01247                     ast_sockaddr_stringify(&remote_address));
01248             ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
01249          }
01250       } else {
01251          rtp->txcount++;
01252          rtp->txoctetcount += (res - hdrlen);
01253 
01254          if (rtp->rtcp && rtp->rtcp->schedid < 1) {
01255             ast_debug(1, "Starting RTCP transmission on RTP instance '%p'\n", instance);
01256             ao2_ref(instance, +1);
01257             rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
01258             if (rtp->rtcp->schedid < 0) {
01259                ao2_ref(instance, -1);
01260                ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
01261             }
01262          }
01263       }
01264 
01265       if (rtp_debug_test_addr(&remote_address)) {
01266          ast_verbose("Sent RTP packet to      %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
01267                 ast_sockaddr_stringify(&remote_address),
01268                 codec, rtp->seqno, rtp->lastts, res - hdrlen);
01269       }
01270    }
01271 
01272    rtp->seqno++;
01273 
01274    return 0;
01275 }
01276 
01277 static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
01278    unsigned char *data = red->t140red.data.ptr;
01279    int len = 0;
01280    int i;
01281 
01282    /* replace most aged generation */
01283    if (red->len[0]) {
01284       for (i = 1; i < red->num_gen+1; i++)
01285          len += red->len[i];
01286 
01287       memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
01288    }
01289 
01290    /* Store length of each generation and primary data length*/
01291    for (i = 0; i < red->num_gen; i++)
01292       red->len[i] = red->len[i+1];
01293    red->len[i] = red->t140.datalen;
01294 
01295    /* write each generation length in red header */
01296    len = red->hdrlen;
01297    for (i = 0; i < red->num_gen; i++)
01298       len += data[i*4+3] = red->len[i];
01299 
01300    /* add primary data to buffer */
01301    memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
01302    red->t140red.datalen = len + red->t140.datalen;
01303 
01304    /* no primary data and no generations to send */
01305    if (len == red->hdrlen && !red->t140.datalen)
01306       return NULL;
01307 
01308    /* reset t.140 buffer */
01309    red->t140.datalen = 0;
01310 
01311    return &red->t140red;
01312 }
01313 
01314 static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
01315 {
01316    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01317    struct ast_sockaddr remote_address = { {0,} };
01318    format_t codec, subclass;
01319 
01320    ast_rtp_instance_get_remote_address(instance, &remote_address);
01321 
01322    /* If we don't actually know the remote address don't even bother doing anything */
01323    if (ast_sockaddr_isnull(&remote_address)) {
01324       ast_debug(1, "No remote address on RTP instance '%p' so dropping frame\n", instance);
01325       return 0;
01326    }
01327 
01328    /* If there is no data length we can't very well send the packet */
01329    if (!frame->datalen) {
01330       ast_debug(1, "Received frame with no data for RTP instance '%p' so dropping frame\n", instance);
01331       return 0;
01332    }
01333 
01334    /* If the packet is not one our RTP stack supports bail out */
01335    if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
01336       ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
01337       return -1;
01338    }
01339 
01340    if (rtp->red) {
01341       /* return 0; */
01342       /* no primary data or generations to send */
01343       if ((frame = red_t140_to_red(rtp->red)) == NULL)
01344          return 0;
01345    }
01346 
01347    /* Grab the subclass and look up the payload we are going to use */
01348    subclass = frame->subclass.codec;
01349    if (frame->frametype == AST_FRAME_VIDEO) {
01350       subclass &= ~0x1LL;
01351    }
01352    if ((codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 1, subclass)) < 0) {
01353       ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(frame->subclass.codec));
01354       return -1;
01355    }
01356 
01357    /* Oh dear, if the format changed we will have to set up a new smoother */
01358    if (rtp->lasttxformat != subclass) {
01359       ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
01360       rtp->lasttxformat = subclass;
01361       if (rtp->smoother) {
01362          ast_smoother_free(rtp->smoother);
01363          rtp->smoother = NULL;
01364       }
01365    }
01366 
01367    /* If no smoother is present see if we have to set one up */
01368    if (!rtp->smoother) {
01369       struct ast_format_list fmt = ast_codec_pref_getsize(&ast_rtp_instance_get_codecs(instance)->pref, subclass);
01370 
01371       switch (subclass) {
01372       case AST_FORMAT_SPEEX:
01373       case AST_FORMAT_SPEEX16:
01374       case AST_FORMAT_G723_1:
01375       case AST_FORMAT_SIREN7:
01376       case AST_FORMAT_SIREN14:
01377       case AST_FORMAT_G719:
01378          /* these are all frame-based codecs and cannot be safely run through
01379             a smoother */
01380          break;
01381       default:
01382          if (fmt.inc_ms) {
01383             if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
01384                ast_log(LOG_WARNING, "Unable to create smoother: format %s ms: %d len: %d\n", ast_getformatname(subclass), fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
01385                return -1;
01386             }
01387             if (fmt.flags) {
01388                ast_smoother_set_flags(rtp->smoother, fmt.flags);
01389             }
01390             ast_debug(1, "Created smoother: format: %s ms: %d len: %d\n", ast_getformatname(subclass), fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
01391          }
01392       }
01393    }
01394 
01395    /* Feed audio frames into the actual function that will create a frame and send it */
01396    if (rtp->smoother) {
01397       struct ast_frame *f;
01398 
01399       if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
01400          ast_smoother_feed_be(rtp->smoother, frame);
01401       } else {
01402          ast_smoother_feed(rtp->smoother, frame);
01403       }
01404 
01405       while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
01406             ast_rtp_raw_write(instance, f, codec);
01407       }
01408    } else {
01409       int hdrlen = 12;
01410       struct ast_frame *f = NULL;
01411 
01412       if (frame->offset < hdrlen) {
01413          f = ast_frdup(frame);
01414       } else {
01415          f = frame;
01416       }
01417       if (f->data.ptr) {
01418          ast_rtp_raw_write(instance, f, codec);
01419       }
01420       if (f != frame) {
01421          ast_frfree(f);
01422       }
01423 
01424    }
01425 
01426    return 0;
01427 }
01428 
01429 static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
01430 {
01431    struct timeval now;
01432    struct timeval tmp;
01433    double transit;
01434    double current_time;
01435    double d;
01436    double dtv;
01437    double prog;
01438    int rate = rtp_get_rate(rtp->f.subclass.codec);
01439 
01440    double normdev_rxjitter_current;
01441    if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
01442       gettimeofday(&rtp->rxcore, NULL);
01443       rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
01444       /* map timestamp to a real time */
01445       rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
01446       tmp = ast_samp2tv(timestamp, rate);
01447       rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
01448       /* Round to 0.1ms for nice, pretty timestamps */
01449       rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
01450    }
01451 
01452    gettimeofday(&now,NULL);
01453    /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
01454    tmp = ast_samp2tv(timestamp, rate);
01455    *tv = ast_tvadd(rtp->rxcore, tmp);
01456 
01457    prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
01458    dtv = (double)rtp->drxcore + (double)(prog);
01459    current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
01460    transit = current_time - dtv;
01461    d = transit - rtp->rxtransit;
01462    rtp->rxtransit = transit;
01463    if (d<0)
01464       d=-d;
01465    rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
01466 
01467    if (rtp->rtcp) {
01468       if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
01469          rtp->rtcp->maxrxjitter = rtp->rxjitter;
01470       if (rtp->rtcp->rxjitter_count == 1)
01471          rtp->rtcp->minrxjitter = rtp->rxjitter;
01472       if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
01473          rtp->rtcp->minrxjitter = rtp->rxjitter;
01474 
01475       normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
01476       rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
01477 
01478       rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
01479       rtp->rtcp->rxjitter_count++;
01480    }
01481 }
01482 
01483 static struct ast_frame *create_dtmf_frame(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
01484 {
01485    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01486    struct ast_sockaddr remote_address = { {0,} };
01487 
01488    ast_rtp_instance_get_remote_address(instance, &remote_address);
01489 
01490    if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
01491       ast_debug(1, "Ignore potential DTMF echo from '%s'\n",
01492            ast_sockaddr_stringify(&remote_address));
01493       rtp->resp = 0;
01494       rtp->dtmfsamples = 0;
01495       return &ast_null_frame;
01496    }
01497    ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp,
01498         ast_sockaddr_stringify(&remote_address));
01499    if (rtp->resp == 'X') {
01500       rtp->f.frametype = AST_FRAME_CONTROL;
01501       rtp->f.subclass.integer = AST_CONTROL_FLASH;
01502    } else {
01503       rtp->f.frametype = type;
01504       rtp->f.subclass.integer = rtp->resp;
01505    }
01506    rtp->f.datalen = 0;
01507    rtp->f.samples = 0;
01508    rtp->f.mallocd = 0;
01509    rtp->f.src = "RTP";
01510    AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
01511 
01512    return &rtp->f;
01513 }
01514 
01515 static void process_dtmf_rfc2833(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark, struct frame_list *frames)
01516 {
01517    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01518    struct ast_sockaddr remote_address = { {0,} };
01519    unsigned int event, event_end, samples;
01520    char resp = 0;
01521    struct ast_frame *f = NULL;
01522 
01523    ast_rtp_instance_get_remote_address(instance, &remote_address);
01524 
01525    /* Figure out event, event end, and samples */
01526    event = ntohl(*((unsigned int *)(data)));
01527    event >>= 24;
01528    event_end = ntohl(*((unsigned int *)(data)));
01529    event_end <<= 8;
01530    event_end >>= 24;
01531    samples = ntohl(*((unsigned int *)(data)));
01532    samples &= 0xFFFF;
01533 
01534    if (rtp_debug_test_addr(&remote_address)) {
01535       ast_verbose("Got  RTP RFC2833 from   %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n",
01536              ast_sockaddr_stringify(&remote_address),
01537              payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
01538    }
01539 
01540    /* Print out debug if turned on */
01541    if (rtpdebug || option_debug > 2)
01542       ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
01543 
01544    /* Figure out what digit was pressed */
01545    if (event < 10) {
01546       resp = '0' + event;
01547    } else if (event < 11) {
01548       resp = '*';
01549    } else if (event < 12) {
01550       resp = '#';
01551    } else if (event < 16) {
01552       resp = 'A' + (event - 12);
01553    } else if (event < 17) {        /* Event 16: Hook flash */
01554       resp = 'X';
01555    } else {
01556       /* Not a supported event */
01557       ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
01558       return;
01559    }
01560 
01561    if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
01562       if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
01563          rtp->resp = resp;
01564          rtp->dtmf_timeout = 0;
01565          f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)));
01566          f->len = 0;
01567          rtp->lastevent = timestamp;
01568          AST_LIST_INSERT_TAIL(frames, f, frame_list);
01569       }
01570    } else {
01571       /*  The duration parameter measures the complete
01572           duration of the event (from the beginning) - RFC2833.
01573           Account for the fact that duration is only 16 bits long
01574           (about 8 seconds at 8000 Hz) and can wrap is digit
01575           is hold for too long. */
01576       unsigned int new_duration = rtp->dtmf_duration;
01577       unsigned int last_duration = new_duration & 0xFFFF;
01578 
01579       if (last_duration > 64000 && samples < last_duration) {
01580          new_duration += 0xFFFF + 1;
01581       }
01582       new_duration = (new_duration & ~0xFFFF) | samples;
01583 
01584       /* The second portion of this check is to not mistakenly
01585        * stop accepting DTMF if the seqno rolls over beyond
01586        * 65535.
01587        */
01588       if (rtp->lastevent > seqno && rtp->lastevent - seqno < 50) {
01589          /* Out of order frame. Processing this can cause us to
01590           * improperly duplicate incoming DTMF, so just drop
01591           * this.
01592           */
01593          return;
01594       }
01595 
01596       if (event_end & 0x80) {
01597          /* End event */
01598          if ((rtp->lastevent != seqno) && rtp->resp) {
01599             rtp->dtmf_duration = new_duration;
01600             f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
01601             f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.codec)), ast_tv(0, 0));
01602             rtp->resp = 0;
01603             rtp->dtmf_duration = rtp->dtmf_timeout = 0;
01604             AST_LIST_INSERT_TAIL(frames, f, frame_list);
01605          }
01606       } else {
01607          /* Begin/continuation */
01608 
01609          if (rtp->resp && rtp->resp != resp) {
01610             /* Another digit already began. End it */
01611             f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
01612             f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.codec)), ast_tv(0, 0));
01613             rtp->resp = 0;
01614             rtp->dtmf_duration = rtp->dtmf_timeout = 0;
01615             AST_LIST_INSERT_TAIL(frames, f, frame_list);
01616          }
01617 
01618          if (rtp->resp) {
01619             /* Digit continues */
01620             rtp->dtmf_duration = new_duration;
01621          } else {
01622             /* New digit began */
01623             rtp->resp = resp;
01624             f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0));
01625             rtp->dtmf_duration = samples;
01626             AST_LIST_INSERT_TAIL(frames, f, frame_list);
01627          }
01628 
01629          rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
01630       }
01631 
01632       rtp->lastevent = seqno;
01633    }
01634 
01635    rtp->dtmfsamples = samples;
01636 
01637    return;
01638 }
01639 
01640 static struct ast_frame *process_dtmf_cisco(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark)
01641 {
01642    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01643    unsigned int event, flags, power;
01644    char resp = 0;
01645    unsigned char seq;
01646    struct ast_frame *f = NULL;
01647 
01648    if (len < 4) {
01649       return NULL;
01650    }
01651 
01652    /*      The format of Cisco RTP DTMF packet looks like next:
01653       +0                              - sequence number of DTMF RTP packet (begins from 1,
01654                     wrapped to 0)
01655       +1                              - set of flags
01656       +1 (bit 0)              - flaps by different DTMF digits delimited by audio
01657                     or repeated digit without audio???
01658       +2 (+4,+6,...)  - power level? (rises from 0 to 32 at begin of tone
01659                     then falls to 0 at its end)
01660       +3 (+5,+7,...)  - detected DTMF digit (0..9,*,#,A-D,...)
01661       Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
01662       by each new packet and thus provides some redudancy.
01663 
01664       Sample of Cisco RTP DTMF packet is (all data in hex):
01665          19 07 00 02 12 02 20 02
01666       showing end of DTMF digit '2'.
01667 
01668       The packets
01669          27 07 00 02 0A 02 20 02
01670          28 06 20 02 00 02 0A 02
01671       shows begin of new digit '2' with very short pause (20 ms) after
01672       previous digit '2'. Bit +1.0 flips at begin of new digit.
01673 
01674       Cisco RTP DTMF packets comes as replacement of audio RTP packets
01675       so its uses the same sequencing and timestamping rules as replaced
01676       audio packets. Repeat interval of DTMF packets is 20 ms and not rely
01677       on audio framing parameters. Marker bit isn't used within stream of
01678       DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
01679       are not sequential at borders between DTMF and audio streams,
01680    */
01681 
01682    seq = data[0];
01683    flags = data[1];
01684    power = data[2];
01685    event = data[3] & 0x1f;
01686 
01687    if (option_debug > 2 || rtpdebug)
01688       ast_debug(0, "Cisco DTMF Digit: %02x (len=%d, seq=%d, flags=%02x, power=%d, history count=%d)\n", event, len, seq, flags, power, (len - 4) / 2);
01689    if (event < 10) {
01690       resp = '0' + event;
01691    } else if (event < 11) {
01692       resp = '*';
01693    } else if (event < 12) {
01694       resp = '#';
01695    } else if (event < 16) {
01696       resp = 'A' + (event - 12);
01697    } else if (event < 17) {
01698       resp = 'X';
01699    }
01700    if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
01701       rtp->resp = resp;
01702       /* Why we should care on DTMF compensation at reception? */
01703       if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
01704          f = create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0);
01705          rtp->dtmfsamples = 0;
01706       }
01707    } else if ((rtp->resp == resp) && !power) {
01708       f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE));
01709       f->samples = rtp->dtmfsamples * (rtp->lastrxformat ? (rtp_get_rate(rtp->lastrxformat) / 1000) : 8);
01710       rtp->resp = 0;
01711    } else if (rtp->resp == resp)
01712       rtp->dtmfsamples += 20 * (rtp->lastrxformat ? (rtp_get_rate(rtp->lastrxformat) / 1000) : 8);
01713 
01714    rtp->dtmf_timeout = 0;
01715 
01716    return f;
01717 }
01718 
01719 static struct ast_frame *process_cn_rfc3389(struct ast_rtp_instance *instance, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct ast_sockaddr *addr, int payloadtype, int mark)
01720 {
01721    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01722 
01723    /* Convert comfort noise into audio with various codecs.  Unfortunately this doesn't
01724       totally help us out becuase we don't have an engine to keep it going and we are not
01725       guaranteed to have it every 20ms or anything */
01726    if (rtpdebug)
01727       ast_debug(0, "- RTP 3389 Comfort noise event: Level %" PRId64 " (len = %d)\n", rtp->lastrxformat, len);
01728 
01729    if (ast_test_flag(rtp, FLAG_3389_WARNING)) {
01730       struct ast_sockaddr remote_address = { {0,} };
01731 
01732       ast_rtp_instance_get_remote_address(instance, &remote_address);
01733 
01734       ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client address: %s\n",
01735          ast_sockaddr_stringify(&remote_address));
01736       ast_set_flag(rtp, FLAG_3389_WARNING);
01737    }
01738 
01739    /* Must have at least one byte */
01740    if (!len)
01741       return NULL;
01742    if (len < 24) {
01743       rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
01744       rtp->f.datalen = len - 1;
01745       rtp->f.offset = AST_FRIENDLY_OFFSET;
01746       memcpy(rtp->f.data.ptr, data + 1, len - 1);
01747    } else {
01748       rtp->f.data.ptr = NULL;
01749       rtp->f.offset = 0;
01750       rtp->f.datalen = 0;
01751    }
01752    rtp->f.frametype = AST_FRAME_CNG;
01753    rtp->f.subclass.integer = data[0] & 0x7f;
01754    rtp->f.samples = 0;
01755    rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
01756 
01757    return &rtp->f;
01758 }
01759 
01760 static struct ast_frame *ast_rtcp_read(struct ast_rtp_instance *instance)
01761 {
01762    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
01763    struct ast_sockaddr addr;
01764    unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
01765    unsigned int *rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
01766    int res, packetwords, position = 0;
01767    struct ast_frame *f = &ast_null_frame;
01768 
01769    /* Read in RTCP data from the socket */
01770    if ((res = rtcp_recvfrom(instance, rtcpdata + AST_FRIENDLY_OFFSET,
01771             sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
01772             0, &addr)) < 0) {
01773       ast_assert(errno != EBADF);
01774       if (errno != EAGAIN) {
01775          ast_log(LOG_WARNING, "RTCP Read error: %s.  Hanging up.\n", strerror(errno));
01776          return NULL;
01777       }
01778       return &ast_null_frame;
01779    }
01780 
01781    packetwords = res / 4;
01782 
01783    if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
01784       /* Send to whoever sent to us */
01785       if (ast_sockaddr_cmp(&rtp->rtcp->them, &addr)) {
01786          ast_sockaddr_copy(&rtp->rtcp->them, &addr);
01787          if (option_debug || rtpdebug)
01788             ast_debug(0, "RTCP NAT: Got RTCP from other end. Now sending to address %s\n",
01789                  ast_sockaddr_stringify(&rtp->rtcp->them));
01790       }
01791    }
01792 
01793    ast_debug(1, "Got RTCP report of %d bytes\n", res);
01794 
01795    while (position < packetwords) {
01796       int i, pt, rc;
01797       unsigned int length, dlsr, lsr, msw, lsw, comp;
01798       struct timeval now;
01799       double rttsec, reported_jitter, reported_normdev_jitter_current, normdevrtt_current, reported_lost, reported_normdev_lost_current;
01800       uint64_t rtt = 0;
01801 
01802       i = position;
01803       length = ntohl(rtcpheader[i]);
01804       pt = (length & 0xff0000) >> 16;
01805       rc = (length & 0x1f000000) >> 24;
01806       length &= 0xffff;
01807 
01808       if ((i + length) > packetwords) {
01809          if (option_debug || rtpdebug)
01810             ast_log(LOG_DEBUG, "RTCP Read too short\n");
01811          return &ast_null_frame;
01812       }
01813 
01814       if (rtcp_debug_test_addr(&addr)) {
01815          ast_verbose("\n\nGot RTCP from %s\n",
01816                 ast_sockaddr_stringify(&addr));
01817          ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
01818          ast_verbose("Reception reports: %d\n", rc);
01819          ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
01820       }
01821 
01822       i += 2; /* Advance past header and ssrc */
01823       if (rc == 0 && pt == RTCP_PT_RR) {      /* We're receiving a receiver report with no reports, which is ok */
01824          position += (length + 1);
01825          continue;
01826       }
01827 
01828       switch (pt) {
01829       case RTCP_PT_SR:
01830          gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
01831          rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
01832          rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
01833          rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
01834 
01835          if (rtcp_debug_test_addr(&addr)) {
01836             ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
01837             ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
01838             ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
01839          }
01840          i += 5;
01841          if (rc < 1)
01842             break;
01843          /* Intentional fall through */
01844       case RTCP_PT_RR:
01845          /* Don't handle multiple reception reports (rc > 1) yet */
01846          /* Calculate RTT per RFC */
01847          gettimeofday(&now, NULL);
01848          timeval2ntp(now, &msw, &lsw);
01849          if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
01850             comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
01851             lsr = ntohl(rtcpheader[i + 4]);
01852             dlsr = ntohl(rtcpheader[i + 5]);
01853             rtt = comp - lsr - dlsr;
01854 
01855             /* Convert end to end delay to usec (keeping the calculation in 64bit space)
01856                sess->ee_delay = (eedelay * 1000) / 65536; */
01857             if (rtt < 4294) {
01858                rtt = (rtt * 1000000) >> 16;
01859             } else {
01860                rtt = (rtt * 1000) >> 16;
01861                rtt *= 1000;
01862             }
01863             rtt = rtt / 1000.;
01864             rttsec = rtt / 1000.;
01865             rtp->rtcp->rtt = rttsec;
01866 
01867             if (comp - dlsr >= lsr) {
01868                rtp->rtcp->accumulated_transit += rttsec;
01869 
01870                if (rtp->rtcp->rtt_count == 0)
01871                   rtp->rtcp->minrtt = rttsec;
01872 
01873                if (rtp->rtcp->maxrtt<rttsec)
01874                   rtp->rtcp->maxrtt = rttsec;
01875                if (rtp->rtcp->minrtt>rttsec)
01876                   rtp->rtcp->minrtt = rttsec;
01877 
01878                normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt, rttsec, rtp->rtcp->rtt_count);
01879 
01880                rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt, rttsec, rtp->rtcp->normdevrtt, normdevrtt_current, rtp->rtcp->rtt_count);
01881 
01882                rtp->rtcp->normdevrtt = normdevrtt_current;
01883 
01884                rtp->rtcp->rtt_count++;
01885             } else if (rtcp_debug_test_addr(&addr)) {
01886                ast_verbose("Internal RTCP NTP clock skew detected: "
01887                         "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
01888                       "diff=%d\n",
01889                       lsr, comp, dlsr, dlsr / 65536,
01890                       (dlsr % 65536) * 1000 / 65536,
01891                       dlsr - (comp - lsr));
01892             }
01893          }
01894 
01895          rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
01896          reported_jitter = (double) rtp->rtcp->reported_jitter;
01897 
01898          if (rtp->rtcp->reported_jitter_count == 0)
01899             rtp->rtcp->reported_minjitter = reported_jitter;
01900 
01901          if (reported_jitter < rtp->rtcp->reported_minjitter)
01902             rtp->rtcp->reported_minjitter = reported_jitter;
01903 
01904          if (reported_jitter > rtp->rtcp->reported_maxjitter)
01905             rtp->rtcp->reported_maxjitter = reported_jitter;
01906 
01907          reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);
01908 
01909          rtp->rtcp->reported_stdev_jitter = stddev_compute(rtp->rtcp->reported_stdev_jitter, reported_jitter, rtp->rtcp->reported_normdev_jitter, reported_normdev_jitter_current, rtp->rtcp->reported_jitter_count);
01910 
01911          rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;
01912 
01913          rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
01914 
01915          reported_lost = (double) rtp->rtcp->reported_lost;
01916 
01917          /* using same counter as for jitter */
01918          if (rtp->rtcp->reported_jitter_count == 0)
01919             rtp->rtcp->reported_minlost = reported_lost;
01920 
01921          if (reported_lost < rtp->rtcp->reported_minlost)
01922             rtp->rtcp->reported_minlost = reported_lost;
01923 
01924          if (reported_lost > rtp->rtcp->reported_maxlost)
01925             rtp->rtcp->reported_maxlost = reported_lost;
01926          reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);
01927 
01928          rtp->rtcp->reported_stdev_lost = stddev_compute(rtp->rtcp->reported_stdev_lost, reported_lost, rtp->rtcp->reported_normdev_lost, reported_normdev_lost_current, rtp->rtcp->reported_jitter_count);
01929 
01930          rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;
01931 
01932          rtp->rtcp->reported_jitter_count++;
01933 
01934          if (rtcp_debug_test_addr(&addr)) {
01935             ast_verbose("  Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
01936             ast_verbose("  Packets lost so far: %d\n", rtp->rtcp->reported_lost);
01937             ast_verbose("  Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
01938             ast_verbose("  Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2])) >> 16);
01939             ast_verbose("  Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
01940             ast_verbose("  Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
01941             ast_verbose("  DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
01942             if (rtt)
01943                ast_verbose("  RTT: %lu(sec)\n", (unsigned long) rtt);
01944          }
01945          if (rtt) {
01946             manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s\r\n"
01947                             "PT: %d(%s)\r\n"
01948                             "ReceptionReports: %d\r\n"
01949                             "SenderSSRC: %u\r\n"
01950                             "FractionLost: %ld\r\n"
01951                             "PacketsLost: %d\r\n"
01952                             "HighestSequence: %ld\r\n"
01953                             "SequenceNumberCycles: %ld\r\n"
01954                             "IAJitter: %u\r\n"
01955                             "LastSR: %lu.%010lu\r\n"
01956                             "DLSR: %4.4f(sec)\r\n"
01957                      "RTT: %llu(sec)\r\n",
01958                      ast_sockaddr_stringify(&addr),
01959                      pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
01960                      rc,
01961                      rtcpheader[i + 1],
01962                      (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
01963                      rtp->rtcp->reported_lost,
01964                      (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
01965                      (long) (ntohl(rtcpheader[i + 2])) >> 16,
01966                      rtp->rtcp->reported_jitter,
01967                      (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
01968                      ntohl(rtcpheader[i + 5])/65536.0,
01969                      (unsigned long long)rtt);
01970          } else {
01971             manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s\r\n"
01972                             "PT: %d(%s)\r\n"
01973                             "ReceptionReports: %d\r\n"
01974                             "SenderSSRC: %u\r\n"
01975                             "FractionLost: %ld\r\n"
01976                             "PacketsLost: %d\r\n"
01977                             "HighestSequence: %ld\r\n"
01978                             "SequenceNumberCycles: %ld\r\n"
01979                             "IAJitter: %u\r\n"
01980                             "LastSR: %lu.%010lu\r\n"
01981                      "DLSR: %4.4f(sec)\r\n",
01982                      ast_sockaddr_stringify(&addr),
01983                      pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
01984                      rc,
01985                      rtcpheader[i + 1],
01986                      (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
01987                      rtp->rtcp->reported_lost,
01988                      (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
01989                      (long) (ntohl(rtcpheader[i + 2])) >> 16,
01990                      rtp->rtcp->reported_jitter,
01991                      (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
01992                      ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
01993                      ntohl(rtcpheader[i + 5])/65536.0);
01994          }
01995          break;
01996       case RTCP_PT_FUR:
01997          if (rtcp_debug_test_addr(&addr))
01998             ast_verbose("Received an RTCP Fast Update Request\n");
01999          rtp->f.frametype = AST_FRAME_CONTROL;
02000          rtp->f.subclass.integer = AST_CONTROL_VIDUPDATE;
02001          rtp->f.datalen = 0;
02002          rtp->f.samples = 0;
02003          rtp->f.mallocd = 0;
02004          rtp->f.src = "RTP";
02005          f = &rtp->f;
02006          break;
02007       case RTCP_PT_SDES:
02008          if (rtcp_debug_test_addr(&addr))
02009             ast_verbose("Received an SDES from %s\n",
02010                    ast_sockaddr_stringify(&rtp->rtcp->them));
02011          break;
02012       case RTCP_PT_BYE:
02013          if (rtcp_debug_test_addr(&addr))
02014             ast_verbose("Received a BYE from %s\n",
02015                    ast_sockaddr_stringify(&rtp->rtcp->them));
02016          break;
02017       default:
02018          ast_debug(1, "Unknown RTCP packet (pt=%d) received from %s\n",
02019               pt, ast_sockaddr_stringify(&rtp->rtcp->them));
02020          break;
02021       }
02022       position += (length + 1);
02023    }
02024 
02025    rtp->rtcp->rtcp_info = 1;
02026 
02027    return f;
02028 }
02029 
02030 static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance, unsigned int *rtpheader, int len, int hdrlen)
02031 {
02032    struct ast_rtp_instance *instance1 = ast_rtp_instance_get_bridged(instance);
02033    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance), *bridged = ast_rtp_instance_get_data(instance1);
02034    int res = 0, payload = 0, bridged_payload = 0, mark;
02035    struct ast_rtp_payload_type payload_type;
02036    int reconstruct = ntohl(rtpheader[0]);
02037    struct ast_sockaddr remote_address = { {0,} };
02038 
02039    /* Get fields from packet */
02040    payload = (reconstruct & 0x7f0000) >> 16;
02041    mark = (((reconstruct & 0x800000) >> 23) != 0);
02042 
02043    /* Check what the payload value should be */
02044    payload_type = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), payload);
02045 
02046    /* Otherwise adjust bridged payload to match */
02047    bridged_payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance1), payload_type.asterisk_format, payload_type.code);
02048 
02049    /* If no codec could be matched between instance and instance1, then somehow things were made incompatible while we were still bridged.  Bail. */
02050    if (bridged_payload < 0) {
02051       return -1;
02052    }
02053 
02054    /* If the payload coming in is not one of the negotiated ones then send it to the core, this will cause formats to change and the bridge to break */
02055    if (!(ast_rtp_instance_get_codecs(instance1)->payloads[bridged_payload].code)) {
02056       return -1;
02057    }
02058 
02059    /* If the marker bit has been explicitly set turn it on */
02060    if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
02061       mark = 1;
02062       ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
02063    }
02064 
02065    /* Reconstruct part of the packet */
02066    reconstruct &= 0xFF80FFFF;
02067    reconstruct |= (bridged_payload << 16);
02068    reconstruct |= (mark << 23);
02069    rtpheader[0] = htonl(reconstruct);
02070 
02071    ast_rtp_instance_get_remote_address(instance1, &remote_address);
02072 
02073    if (ast_sockaddr_isnull(&remote_address)) {
02074       ast_debug(1, "Remote address is null, most likely RTP has been stopped\n");
02075       return 0;
02076    }
02077 
02078    /* Send the packet back out */
02079    res = rtp_sendto(instance1, (void *)rtpheader, len, 0, &remote_address);
02080    if (res < 0) {
02081       if (!ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_NAT) || (ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_NAT) && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
02082          ast_log(LOG_WARNING,
02083             "RTP Transmission error of packet to %s: %s\n",
02084             ast_sockaddr_stringify(&remote_address),
02085             strerror(errno));
02086       } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
02087          if (option_debug || rtpdebug)
02088             ast_log(LOG_WARNING,
02089                "RTP NAT: Can't write RTP to private "
02090                "address %s, waiting for other end to "
02091                "send audio...\n",
02092                ast_sockaddr_stringify(&remote_address));
02093          ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
02094       }
02095       return 0;
02096    } else if (rtp_debug_test_addr(&remote_address)) {
02097       ast_verbose("Sent RTP P2P packet to %s (type %-2.2d, len %-6.6u)\n",
02098              ast_sockaddr_stringify(&remote_address),
02099              bridged_payload, len - hdrlen);
02100    }
02101 
02102    return 0;
02103 }
02104 
02105 static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
02106 {
02107    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02108    struct ast_sockaddr addr;
02109    int res, hdrlen = 12, version, payloadtype, padding, mark, ext, cc, prev_seqno;
02110    unsigned int *rtpheader = (unsigned int*)(rtp->rawdata + AST_FRIENDLY_OFFSET), seqno, ssrc, timestamp;
02111    struct ast_rtp_payload_type payload;
02112    struct ast_sockaddr remote_address = { {0,} };
02113    struct frame_list frames;
02114 
02115    /* If this is actually RTCP let's hop on over and handle it */
02116    if (rtcp) {
02117       if (rtp->rtcp) {
02118          return ast_rtcp_read(instance);
02119       }
02120       return &ast_null_frame;
02121    }
02122 
02123    /* If we are currently sending DTMF to the remote party send a continuation packet */
02124    if (rtp->sending_digit) {
02125       ast_rtp_dtmf_continuation(instance);
02126    }
02127 
02128    /* Actually read in the data from the socket */
02129    if ((res = rtp_recvfrom(instance, rtp->rawdata + AST_FRIENDLY_OFFSET,
02130             sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0,
02131             &addr)) < 0) {
02132       ast_assert(errno != EBADF);
02133       if (errno != EAGAIN) {
02134          ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
02135          return NULL;
02136       }
02137       return &ast_null_frame;
02138    }
02139 
02140    /* Make sure the data that was read in is actually enough to make up an RTP packet */
02141    if (res < hdrlen) {
02142       ast_log(LOG_WARNING, "RTP Read too short\n");
02143       return &ast_null_frame;
02144    }
02145 
02146    /* If strict RTP protection is enabled see if we need to learn the remote address or if we need to drop the packet */
02147    if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
02148       ast_debug(1, "%p -- start learning mode pass with addr = %s\n", rtp, ast_sockaddr_stringify(&addr));
02149       /* For now, we always copy the address. */
02150       ast_sockaddr_copy(&rtp->strict_rtp_address, &addr);
02151 
02152       /* Send the rtp and the seqno from header to rtp_learning_rtp_seq_update to see whether we can exit or not*/
02153       if (rtp_learning_rtp_seq_update(rtp, ntohl(rtpheader[0]))) {
02154          ast_debug(1, "%p -- Condition for learning hasn't exited, so reject the frame.\n", rtp);
02155          return &ast_null_frame;
02156       }
02157 
02158       ast_debug(1, "%p -- Probation Ended. Set strict_rtp_state to STRICT_RTP_CLOSED with address %s\n", rtp, ast_sockaddr_stringify(&addr));
02159       rtp->strict_rtp_state = STRICT_RTP_CLOSED;
02160    } else if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
02161       if (ast_sockaddr_cmp(&rtp->strict_rtp_address, &addr)) {
02162          /* Hmm, not the strict addres. Perhaps we're getting audio from the alternate? */
02163          if (!ast_sockaddr_cmp(&rtp->alt_rtp_address, &addr)) {
02164             /* ooh, we did! You're now the new expected address, son! */
02165             ast_sockaddr_copy(&rtp->strict_rtp_address,
02166                     &addr);
02167          } else  {
02168             const char *real_addr = ast_strdupa(ast_sockaddr_stringify(&addr));
02169             const char *expected_addr = ast_strdupa(ast_sockaddr_stringify(&rtp->strict_rtp_address));
02170 
02171             ast_debug(1, "Received RTP packet from %s, dropping due to strict RTP protection. Expected it to be from %s\n",
02172                   real_addr, expected_addr);
02173 
02174             return &ast_null_frame;
02175          }
02176       }
02177    }
02178 
02179    /* Get fields and verify this is an RTP packet */
02180    seqno = ntohl(rtpheader[0]);
02181 
02182    ast_rtp_instance_get_remote_address(instance, &remote_address);
02183 
02184    if (!(version = (seqno & 0xC0000000) >> 30)) {
02185       struct sockaddr_in addr_tmp;
02186       struct ast_sockaddr addr_v4;
02187       if (ast_sockaddr_is_ipv4(&addr)) {
02188          ast_sockaddr_to_sin(&addr, &addr_tmp);
02189       } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
02190          ast_debug(1, "Using IPv6 mapped address %s for STUN\n",
02191               ast_sockaddr_stringify(&addr));
02192          ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
02193       } else {
02194          ast_debug(1, "Cannot do STUN for non IPv4 address %s\n",
02195               ast_sockaddr_stringify(&addr));
02196          return &ast_null_frame;
02197       }
02198       if ((ast_stun_handle_packet(rtp->s, &addr_tmp, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == AST_STUN_ACCEPT) &&
02199           ast_sockaddr_isnull(&remote_address)) {
02200          ast_sockaddr_from_sin(&addr, &addr_tmp);
02201          ast_rtp_instance_set_remote_address(instance, &addr);
02202       }
02203       return &ast_null_frame;
02204    }
02205 
02206    /* If symmetric RTP is enabled see if the remote side is not what we expected and change where we are sending audio */
02207    if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
02208       if (ast_sockaddr_cmp(&remote_address, &addr)) {
02209          ast_rtp_instance_set_remote_address(instance, &addr);
02210          ast_sockaddr_copy(&remote_address, &addr);
02211          if (rtp->rtcp) {
02212             ast_sockaddr_copy(&rtp->rtcp->them, &addr);
02213             ast_sockaddr_set_port(&rtp->rtcp->them, ast_sockaddr_port(&addr) + 1);
02214          }
02215          rtp->rxseqno = 0;
02216          ast_set_flag(rtp, FLAG_NAT_ACTIVE);
02217          if (option_debug || rtpdebug)
02218             ast_debug(0, "RTP NAT: Got audio from other end. Now sending to address %s\n",
02219                  ast_sockaddr_stringify(&remote_address));
02220       }
02221    }
02222 
02223    /* If we are directly bridged to another instance send the audio directly out */
02224    if (ast_rtp_instance_get_bridged(instance) && !bridge_p2p_rtp_write(instance, rtpheader, res, hdrlen)) {
02225       return &ast_null_frame;
02226    }
02227 
02228    /* If the version is not what we expected by this point then just drop the packet */
02229    if (version != 2) {
02230       return &ast_null_frame;
02231    }
02232 
02233    /* Pull out the various other fields we will need */
02234    payloadtype = (seqno & 0x7f0000) >> 16;
02235    padding = seqno & (1 << 29);
02236    mark = seqno & (1 << 23);
02237    ext = seqno & (1 << 28);
02238    cc = (seqno & 0xF000000) >> 24;
02239    seqno &= 0xffff;
02240    timestamp = ntohl(rtpheader[1]);
02241    ssrc = ntohl(rtpheader[2]);
02242 
02243    AST_LIST_HEAD_INIT_NOLOCK(&frames);
02244    /* Force a marker bit and change SSRC if the SSRC changes */
02245    if (rtp->rxssrc && rtp->rxssrc != ssrc) {
02246       struct ast_frame *f, srcupdate = {
02247          AST_FRAME_CONTROL,
02248          .subclass.integer = AST_CONTROL_SRCCHANGE,
02249       };
02250 
02251       if (!mark) {
02252          if (option_debug || rtpdebug) {
02253             ast_debug(1, "Forcing Marker bit, because SSRC has changed\n");
02254          }
02255          mark = 1;
02256       }
02257 
02258       f = ast_frisolate(&srcupdate);
02259       AST_LIST_INSERT_TAIL(&frames, f, frame_list);
02260    }
02261 
02262    rtp->rxssrc = ssrc;
02263 
02264    /* Remove any padding bytes that may be present */
02265    if (padding) {
02266       res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
02267    }
02268 
02269    /* Skip over any CSRC fields */
02270    if (cc) {
02271       hdrlen += cc * 4;
02272    }
02273 
02274    /* Look for any RTP extensions, currently we do not support any */
02275    if (ext) {
02276       hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
02277       hdrlen += 4;
02278       if (option_debug) {
02279          int profile;
02280          profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
02281          if (profile == 0x505a)
02282             ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
02283          else
02284             ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
02285       }
02286    }
02287 
02288    /* Make sure after we potentially mucked with the header length that it is once again valid */
02289    if (res < hdrlen) {
02290       ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d\n", res, hdrlen);
02291       return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
02292    }
02293 
02294    rtp->rxcount++;
02295    if (rtp->rxcount == 1) {
02296       rtp->seedrxseqno = seqno;
02297    }
02298 
02299    /* Do not schedule RR if RTCP isn't run */
02300    if (rtp->rtcp && !ast_sockaddr_isnull(&rtp->rtcp->them) && rtp->rtcp->schedid < 1) {
02301       /* Schedule transmission of Receiver Report */
02302       ao2_ref(instance, +1);
02303       rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
02304       if (rtp->rtcp->schedid < 0) {
02305          ao2_ref(instance, -1);
02306          ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
02307       }
02308    }
02309    if ((int)rtp->lastrxseqno - (int)seqno  > 100) /* if so it would indicate that the sender cycled; allow for misordering */
02310       rtp->cycles += RTP_SEQ_MOD;
02311 
02312    prev_seqno = rtp->lastrxseqno;
02313    rtp->lastrxseqno = seqno;
02314 
02315    if (!rtp->themssrc) {
02316       rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
02317    }
02318 
02319    if (rtp_debug_test_addr(&addr)) {
02320       ast_verbose("Got  RTP packet from    %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
02321              ast_sockaddr_stringify(&addr),
02322              payloadtype, seqno, timestamp,res - hdrlen);
02323    }
02324 
02325    payload = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), payloadtype);
02326 
02327    /* If the payload is not actually an Asterisk one but a special one pass it off to the respective handler */
02328    if (!payload.asterisk_format) {
02329       struct ast_frame *f = NULL;
02330       if (payload.code == AST_RTP_DTMF) {
02331          /* process_dtmf_rfc2833 may need to return multiple frames. We do this
02332           * by passing the pointer to the frame list to it so that the method
02333           * can append frames to the list as needed.
02334           */
02335          process_dtmf_rfc2833(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark, &frames);
02336       } else if (payload.code == AST_RTP_CISCO_DTMF) {
02337          f = process_dtmf_cisco(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
02338       } else if (payload.code == AST_RTP_CN) {
02339          f = process_cn_rfc3389(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
02340       } else {
02341          ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n",
02342             payloadtype,
02343             ast_sockaddr_stringify(&remote_address));
02344       }
02345 
02346       if (f) {
02347          AST_LIST_INSERT_TAIL(&frames, f, frame_list);
02348       }
02349       /* Even if no frame was returned by one of the above methods,
02350        * we may have a frame to return in our frame list
02351        */
02352       if (!AST_LIST_EMPTY(&frames)) {
02353          return AST_LIST_FIRST(&frames);
02354       }
02355       return &ast_null_frame;
02356    }
02357 
02358    rtp->lastrxformat = rtp->f.subclass.codec = payload.code;
02359    rtp->f.frametype = (rtp->f.subclass.codec & AST_FORMAT_AUDIO_MASK) ? AST_FRAME_VOICE : (rtp->f.subclass.codec & AST_FORMAT_VIDEO_MASK) ? AST_FRAME_VIDEO : AST_FRAME_TEXT;
02360 
02361    rtp->rxseqno = seqno;
02362 
02363    if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
02364       rtp->dtmf_timeout = 0;
02365 
02366       if (rtp->resp) {
02367          struct ast_frame *f;
02368          f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0);
02369          f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass.codec)), ast_tv(0, 0));
02370          rtp->resp = 0;
02371          rtp->dtmf_timeout = rtp->dtmf_duration = 0;
02372          AST_LIST_INSERT_TAIL(&frames, f, frame_list);
02373          return AST_LIST_FIRST(&frames);
02374       }
02375    }
02376 
02377    rtp->lastrxts = timestamp;
02378 
02379    rtp->f.src = "RTP";
02380    rtp->f.mallocd = 0;
02381    rtp->f.datalen = res - hdrlen;
02382    rtp->f.data.ptr = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
02383    rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
02384    rtp->f.seqno = seqno;
02385 
02386    if (rtp->f.subclass.codec == AST_FORMAT_T140 && (int)seqno - (prev_seqno+1) > 0 && (int)seqno - (prev_seqno+1) < 10) {
02387       unsigned char *data = rtp->f.data.ptr;
02388 
02389       memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
02390       rtp->f.datalen +=3;
02391       *data++ = 0xEF;
02392       *data++ = 0xBF;
02393       *data = 0xBD;
02394    }
02395 
02396    if (rtp->f.subclass.codec == AST_FORMAT_T140RED) {
02397       unsigned char *data = rtp->f.data.ptr;
02398       unsigned char *header_end;
02399       int num_generations;
02400       int header_length;
02401       int len;
02402       int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
02403       int x;
02404 
02405       rtp->f.subclass.codec = AST_FORMAT_T140;
02406       header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
02407       if (header_end == NULL) {
02408          return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
02409       }
02410       header_end++;
02411 
02412       header_length = header_end - data;
02413       num_generations = header_length / 4;
02414       len = header_length;
02415 
02416       if (!diff) {
02417          for (x = 0; x < num_generations; x++)
02418             len += data[x * 4 + 3];
02419 
02420          if (!(rtp->f.datalen - len))
02421             return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
02422 
02423          rtp->f.data.ptr += len;
02424          rtp->f.datalen -= len;
02425       } else if (diff > num_generations && diff < 10) {
02426          len -= 3;
02427          rtp->f.data.ptr += len;
02428          rtp->f.datalen -= len;
02429 
02430          data = rtp->f.data.ptr;
02431          *data++ = 0xEF;
02432          *data++ = 0xBF;
02433          *data = 0xBD;
02434       } else {
02435          for ( x = 0; x < num_generations - diff; x++)
02436             len += data[x * 4 + 3];
02437 
02438          rtp->f.data.ptr += len;
02439          rtp->f.datalen -= len;
02440       }
02441    }
02442 
02443    if (rtp->f.subclass.codec & AST_FORMAT_AUDIO_MASK) {
02444       rtp->f.samples = ast_codec_get_samples(&rtp->f);
02445       if ((rtp->f.subclass.codec == AST_FORMAT_SLINEAR) || (rtp->f.subclass.codec == AST_FORMAT_SLINEAR16)) {
02446          ast_frame_byteswap_be(&rtp->f);
02447       }
02448       calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
02449       /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
02450       ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
02451       rtp->f.ts = timestamp / (rtp_get_rate(rtp->f.subclass.codec) / 1000);
02452       rtp->f.len = rtp->f.samples / ((ast_format_rate(rtp->f.subclass.codec) / 1000));
02453    } else if (rtp->f.subclass.codec & AST_FORMAT_VIDEO_MASK) {
02454       /* Video -- samples is # of samples vs. 90000 */
02455       if (!rtp->lastividtimestamp)
02456          rtp->lastividtimestamp = timestamp;
02457       rtp->f.samples = timestamp - rtp->lastividtimestamp;
02458       rtp->lastividtimestamp = timestamp;
02459       rtp->f.delivery.tv_sec = 0;
02460       rtp->f.delivery.tv_usec = 0;
02461       /* Pass the RTP marker bit as bit 0 in the subclass field.
02462        * This is ok because subclass is actually a bitmask, and
02463        * the low bits represent audio formats, that are not
02464        * involved here since we deal with video.
02465        */
02466       if (mark)
02467          rtp->f.subclass.codec |= 0x1;
02468    } else {
02469       /* TEXT -- samples is # of samples vs. 1000 */
02470       if (!rtp->lastitexttimestamp)
02471          rtp->lastitexttimestamp = timestamp;
02472       rtp->f.samples = timestamp - rtp->lastitexttimestamp;
02473       rtp->lastitexttimestamp = timestamp;
02474       rtp->f.delivery.tv_sec = 0;
02475       rtp->f.delivery.tv_usec = 0;
02476    }
02477 
02478    AST_LIST_INSERT_TAIL(&frames, &rtp->f, frame_list);
02479    return AST_LIST_FIRST(&frames);
02480 }
02481 
02482 static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
02483 {
02484    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02485 
02486    if (property == AST_RTP_PROPERTY_RTCP) {
02487       if (value) {
02488          if (rtp->rtcp) {
02489             ast_debug(1, "Ignoring duplicate RTCP property on RTP instance '%p'\n", instance);
02490             return;
02491          }
02492          /* Setup RTCP to be activated on the next RTP write */
02493          if (!(rtp->rtcp = ast_calloc(1, sizeof(*rtp->rtcp)))) {
02494             return;
02495          }
02496 
02497          /* Grab the IP address and port we are going to use */
02498          ast_rtp_instance_get_local_address(instance, &rtp->rtcp->us);
02499          ast_sockaddr_set_port(&rtp->rtcp->us,
02500                      ast_sockaddr_port(&rtp->rtcp->us) + 1);
02501 
02502          if ((rtp->rtcp->s =
02503               create_new_socket("RTCP",
02504                       ast_sockaddr_is_ipv4(&rtp->rtcp->us) ?
02505                       AF_INET :
02506                       ast_sockaddr_is_ipv6(&rtp->rtcp->us) ?
02507                       AF_INET6 : -1)) < 0) {
02508             ast_debug(1, "Failed to create a new socket for RTCP on instance '%p'\n", instance);
02509             ast_free(rtp->rtcp);
02510             rtp->rtcp = NULL;
02511             return;
02512          }
02513 
02514          /* Try to actually bind to the IP address and port we are going to use for RTCP, if this fails we have to bail out */
02515          if (ast_bind(rtp->rtcp->s, &rtp->rtcp->us)) {
02516             ast_debug(1, "Failed to setup RTCP on RTP instance '%p'\n", instance);
02517             close(rtp->rtcp->s);
02518             ast_free(rtp->rtcp);
02519             rtp->rtcp = NULL;
02520             return;
02521          }
02522 
02523          ast_debug(1, "Setup RTCP on RTP instance '%p'\n", instance);
02524          rtp->rtcp->schedid = -1;
02525 
02526          return;
02527       } else {
02528          if (rtp->rtcp) {
02529             if (rtp->rtcp->schedid > 0) {
02530                if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
02531                   /* Successfully cancelled scheduler entry. */
02532                   ao2_ref(instance, -1);
02533                } else {
02534                   /* Unable to cancel scheduler entry */
02535                   ast_debug(1, "Failed to tear down RTCP on RTP instance '%p'\n", instance);
02536                   return;
02537                }
02538                rtp->rtcp->schedid = -1;
02539             }
02540             close(rtp->rtcp->s);
02541             ast_free(rtp->rtcp);
02542             rtp->rtcp = NULL;
02543          }
02544          return;
02545       }
02546    }
02547 
02548    return;
02549 }
02550 
02551 static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp)
02552 {
02553    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02554 
02555    return rtcp ? (rtp->rtcp ? rtp->rtcp->s : -1) : rtp->s;
02556 }
02557 
02558 static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
02559 {
02560    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02561 
02562    if (rtp->rtcp) {
02563       ast_debug(1, "Setting RTCP address on RTP instance '%p'\n", instance);
02564       ast_sockaddr_copy(&rtp->rtcp->them, addr);
02565       if (!ast_sockaddr_isnull(addr)) {
02566          ast_sockaddr_set_port(&rtp->rtcp->them,
02567                      ast_sockaddr_port(addr) + 1);
02568       }
02569    }
02570 
02571    rtp->rxseqno = 0;
02572 
02573    if (strictrtp) {
02574       rtp->strict_rtp_state = STRICT_RTP_LEARN;
02575       rtp_learning_seq_init(rtp, rtp->seqno);
02576    }
02577 
02578    return;
02579 }
02580 
02581 static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
02582 {
02583    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02584 
02585    /* No need to futz with rtp->rtcp here because ast_rtcp_read is already able to adjust if receiving
02586     * RTCP from an "unexpected" source
02587     */
02588    ast_sockaddr_copy(&rtp->alt_rtp_address, addr);
02589 
02590    return;
02591 }
02592 
02593 /*! \brief Write t140 redundacy frame
02594  * \param data primary data to be buffered
02595  */
02596 static int red_write(const void *data)
02597 {
02598    struct ast_rtp_instance *instance = (struct ast_rtp_instance*) data;
02599    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02600 
02601    ast_rtp_write(instance, &rtp->red->t140);
02602 
02603    return 1;
02604 }
02605 
02606 static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
02607 {
02608    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02609    int x;
02610 
02611    if (!(rtp->red = ast_calloc(1, sizeof(*rtp->red)))) {
02612       return -1;
02613    }
02614 
02615    rtp->red->t140.frametype = AST_FRAME_TEXT;
02616    rtp->red->t140.subclass.codec = AST_FORMAT_T140RED;
02617    rtp->red->t140.data.ptr = &rtp->red->buf_data;
02618 
02619    rtp->red->t140.ts = 0;
02620    rtp->red->t140red = rtp->red->t140;
02621    rtp->red->t140red.data.ptr = &rtp->red->t140red_data;
02622    rtp->red->t140red.datalen = 0;
02623    rtp->red->ti = buffer_time;
02624    rtp->red->num_gen = generations;
02625    rtp->red->hdrlen = generations * 4 + 1;
02626    rtp->red->prev_ts = 0;
02627 
02628    for (x = 0; x < generations; x++) {
02629       rtp->red->pt[x] = payloads[x];
02630       rtp->red->pt[x] |= 1 << 7; /* mark redundant generations pt */
02631       rtp->red->t140red_data[x*4] = rtp->red->pt[x];
02632    }
02633    rtp->red->t140red_data[x*4] = rtp->red->pt[x] = payloads[x]; /* primary pt */
02634    rtp->red->schedid = ast_sched_add(rtp->sched, generations, red_write, instance);
02635 
02636    rtp->red->t140.datalen = 0;
02637 
02638    return 0;
02639 }
02640 
02641 static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
02642 {
02643    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02644 
02645    if (frame->datalen > -1) {
02646       struct rtp_red *red = rtp->red;
02647       memcpy(&red->buf_data[red->t140.datalen], frame->data.ptr, frame->datalen);
02648       red->t140.datalen += frame->datalen;
02649       red->t140.ts = frame->ts;
02650    }
02651 
02652    return 0;
02653 }
02654 
02655 static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1)
02656 {
02657    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance0);
02658 
02659    ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
02660 
02661    return 0;
02662 }
02663 
02664 static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
02665 {
02666    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02667 
02668    if (!rtp->rtcp) {
02669       return -1;
02670    }
02671 
02672    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXCOUNT, -1, stats->txcount, rtp->txcount);
02673    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXCOUNT, -1, stats->rxcount, rtp->rxcount);
02674 
02675    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->txploss, rtp->rtcp->reported_lost);
02676    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->rxploss, rtp->rtcp->expected_prior - rtp->rtcp->received_prior);
02677    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_maxrxploss, rtp->rtcp->reported_maxlost);
02678    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_minrxploss, rtp->rtcp->reported_minlost);
02679    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_normdevrxploss, rtp->rtcp->reported_normdev_lost);
02680    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_stdevrxploss, rtp->rtcp->reported_stdev_lost);
02681    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_maxrxploss, rtp->rtcp->maxrxlost);
02682    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_minrxploss, rtp->rtcp->minrxlost);
02683    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_normdevrxploss, rtp->rtcp->normdev_rxlost);
02684    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_stdevrxploss, rtp->rtcp->stdev_rxlost);
02685    AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_LOSS);
02686 
02687    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->txjitter, rtp->rxjitter);
02688    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->rxjitter, rtp->rtcp->reported_jitter / (unsigned int) 65536.0);
02689    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_maxjitter, rtp->rtcp->reported_maxjitter);
02690    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_minjitter, rtp->rtcp->reported_minjitter);
02691    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_normdevjitter, rtp->rtcp->reported_normdev_jitter);
02692    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_stdevjitter, rtp->rtcp->reported_stdev_jitter);
02693    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_maxjitter, rtp->rtcp->maxrxjitter);
02694    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_minjitter, rtp->rtcp->minrxjitter);
02695    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_normdevjitter, rtp->rtcp->normdev_rxjitter);
02696    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_stdevjitter, rtp->rtcp->stdev_rxjitter);
02697    AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_JITTER);
02698 
02699    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->rtt, rtp->rtcp->rtt);
02700    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MAX_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->maxrtt, rtp->rtcp->maxrtt);
02701    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MIN_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->minrtt, rtp->rtcp->minrtt);
02702    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_NORMDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->normdevrtt, rtp->rtcp->normdevrtt);
02703    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_STDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->stdevrtt, rtp->rtcp->stdevrtt);
02704    AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_RTT);
02705 
02706    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_SSRC, -1, stats->local_ssrc, rtp->ssrc);
02707    AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_SSRC, -1, stats->remote_ssrc, rtp->themssrc);
02708 
02709    return 0;
02710 }
02711 
02712 static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1)
02713 {
02714    /* If both sides are not using the same method of DTMF transmission
02715     * (ie: one is RFC2833, other is INFO... then we can not do direct media.
02716     * --------------------------------------------------
02717     * | DTMF Mode |  HAS_DTMF  |  Accepts Begin Frames |
02718     * |-----------|------------|-----------------------|
02719     * | Inband    | False      | True                  |
02720     * | RFC2833   | True       | True                  |
02721     * | SIP INFO  | False      | False                 |
02722     * --------------------------------------------------
02723     */
02724    return (((ast_rtp_instance_get_prop(instance0, AST_RTP_PROPERTY_DTMF) != ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_DTMF)) ||
02725        (!chan0->tech->send_digit_begin != !chan1->tech->send_digit_begin)) ? 0 : 1);
02726 }
02727 
02728 static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username)
02729 {
02730    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02731    struct sockaddr_in suggestion_tmp;
02732 
02733    ast_sockaddr_to_sin(suggestion, &suggestion_tmp);
02734    ast_stun_request(rtp->s, &suggestion_tmp, username, NULL);
02735    ast_sockaddr_from_sin(suggestion, &suggestion_tmp);
02736 }
02737 
02738 static void ast_rtp_stop(struct ast_rtp_instance *instance)
02739 {
02740    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02741    struct ast_sockaddr addr = { {0,} };
02742 
02743    if (rtp->rtcp && rtp->rtcp->schedid > 0) {
02744       if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
02745          /* successfully cancelled scheduler entry. */
02746          ao2_ref(instance, -1);
02747       }
02748       rtp->rtcp->schedid = -1;
02749    }
02750 
02751    if (rtp->red) {
02752       AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
02753       free(rtp->red);
02754       rtp->red = NULL;
02755    }
02756 
02757    ast_rtp_instance_set_remote_address(instance, &addr);
02758    if (rtp->rtcp) {
02759       ast_sockaddr_setnull(&rtp->rtcp->them);
02760    }
02761 
02762    ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
02763 }
02764 
02765 static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
02766 {
02767    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02768 
02769    return ast_set_qos(rtp->s, tos, cos, desc);
02770 }
02771 
02772 /*! \brief generate comfort noice (CNG) */
02773 static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level)
02774 {
02775    unsigned int *rtpheader;
02776    int hdrlen = 12;
02777    int res;
02778    struct ast_rtp_payload_type payload;
02779    char data[256];
02780    struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
02781    struct ast_sockaddr remote_address = { {0,} };
02782 
02783    ast_rtp_instance_get_remote_address(instance, &remote_address);
02784 
02785    if (ast_sockaddr_isnull(&remote_address)) {
02786       return -1;
02787    }
02788 
02789    payload = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), AST_RTP_CN);
02790 
02791    level = 127 - (level & 0x7f);
02792    
02793    rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
02794 
02795    /* Get a pointer to the header */
02796    rtpheader = (unsigned int *)data;
02797    rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload.code << 16) | (rtp->seqno++));
02798    rtpheader[1] = htonl(rtp->lastts);
02799    rtpheader[2] = htonl(rtp->ssrc); 
02800    data[12] = level;
02801 
02802    res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 1, 0, &remote_address);
02803 
02804    if (res < 0) {
02805       ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s: %s\n", ast_sockaddr_stringify(&remote_address), strerror(errno));
02806    } else if (rtp_debug_test_addr(&remote_address)) {
02807       ast_verbose("Sent Comfort Noise RTP packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
02808             ast_sockaddr_stringify(&remote_address),
02809             AST_RTP_CN, rtp->seqno, rtp->lastdigitts, res - hdrlen);
02810    }
02811 
02812    return res;
02813 }
02814 
02815 static char *rtp_do_debug_ip(struct ast_cli_args *a)
02816 {
02817    char *arg = ast_strdupa(a->argv[4]);
02818    char *debughost = NULL;
02819    char *debugport = NULL;
02820 
02821    if (!ast_sockaddr_parse(&rtpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
02822       ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
02823       return CLI_FAILURE;
02824    }
02825    rtpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
02826    ast_cli(a->fd, "RTP Debugging Enabled for address: %s\n",
02827       ast_sockaddr_stringify(&rtpdebugaddr));
02828    rtpdebug = 1;
02829    return CLI_SUCCESS;
02830 }
02831 
02832 static char *rtcp_do_debug_ip(struct ast_cli_args *a)
02833 {
02834    char *arg = ast_strdupa(a->argv[4]);
02835    char *debughost = NULL;
02836    char *debugport = NULL;
02837 
02838    if (!ast_sockaddr_parse(&rtcpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
02839       ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
02840       return CLI_FAILURE;
02841    }
02842    rtcpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
02843    ast_cli(a->fd, "RTCP Debugging Enabled for address: %s\n",
02844       ast_sockaddr_stringify(&rtcpdebugaddr));
02845    rtcpdebug = 1;
02846    return CLI_SUCCESS;
02847 }
02848 
02849 static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02850 {
02851    switch (cmd) {
02852    case CLI_INIT:
02853       e->command = "rtp set debug {on|off|ip}";
02854       e->usage =
02855          "Usage: rtp set debug {on|off|ip host[:port]}\n"
02856          "       Enable/Disable dumping of all RTP packets. If 'ip' is\n"
02857          "       specified, limit the dumped packets to those to and from\n"
02858          "       the specified 'host' with optional port.\n";
02859       return NULL;
02860    case CLI_GENERATE:
02861       return NULL;
02862    }
02863 
02864    if (a->argc == e->args) { /* set on or off */
02865       if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
02866          rtpdebug = 1;
02867          memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
02868          ast_cli(a->fd, "RTP Debugging Enabled\n");
02869          return CLI_SUCCESS;
02870       } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
02871          rtpdebug = 0;
02872          ast_cli(a->fd, "RTP Debugging Disabled\n");
02873          return CLI_SUCCESS;
02874       }
02875    } else if (a->argc == e->args +1) { /* ip */
02876       return rtp_do_debug_ip(a);
02877    }
02878 
02879    return CLI_SHOWUSAGE;   /* default, failure */
02880 }
02881 
02882 static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02883 {
02884    switch (cmd) {
02885    case CLI_INIT:
02886       e->command = "rtcp set debug {on|off|ip}";
02887       e->usage =
02888          "Usage: rtcp set debug {on|off|ip host[:port]}\n"
02889          "       Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
02890          "       specified, limit the dumped packets to those to and from\n"
02891          "       the specified 'host' with optional port.\n";
02892       return NULL;
02893    case CLI_GENERATE:
02894       return NULL;
02895    }
02896 
02897    if (a->argc == e->args) { /* set on or off */
02898       if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
02899          rtcpdebug = 1;
02900          memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
02901          ast_cli(a->fd, "RTCP Debugging Enabled\n");
02902          return CLI_SUCCESS;
02903       } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
02904          rtcpdebug = 0;
02905          ast_cli(a->fd, "RTCP Debugging Disabled\n");
02906          return CLI_SUCCESS;
02907       }
02908    } else if (a->argc == e->args +1) { /* ip */
02909       return rtcp_do_debug_ip(a);
02910    }
02911 
02912    return CLI_SHOWUSAGE;   /* default, failure */
02913 }
02914 
02915 static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02916 {
02917    switch (cmd) {
02918    case CLI_INIT:
02919       e->command = "rtcp set stats {on|off}";
02920       e->usage =
02921          "Usage: rtcp set stats {on|off}\n"
02922          "       Enable/Disable dumping of RTCP stats.\n";
02923       return NULL;
02924    case CLI_GENERATE:
02925       return NULL;
02926    }
02927 
02928    if (a->argc != e->args)
02929       return CLI_SHOWUSAGE;
02930 
02931    if (!strncasecmp(a->argv[e->args-1], "on", 2))
02932       rtcpstats = 1;
02933    else if (!strncasecmp(a->argv[e->args-1], "off", 3))
02934       rtcpstats = 0;
02935    else
02936       return CLI_SHOWUSAGE;
02937 
02938    ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
02939    return CLI_SUCCESS;
02940 }
02941 
02942 static struct ast_cli_entry cli_rtp[] = {
02943    AST_CLI_DEFINE(handle_cli_rtp_set_debug,  "Enable/Disable RTP debugging"),
02944    AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging"),
02945    AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats"),
02946 };
02947 
02948 static int rtp_reload(int reload)
02949 {
02950    struct ast_config *cfg;
02951    const char *s;
02952    struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
02953 
02954    cfg = ast_config_load2("rtp.conf", "rtp", config_flags);
02955    if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
02956       return 0;
02957    }
02958 
02959    rtpstart = DEFAULT_RTP_START;
02960    rtpend = DEFAULT_RTP_END;
02961    dtmftimeout = DEFAULT_DTMF_TIMEOUT;
02962    strictrtp = STRICT_RTP_OPEN;
02963    learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL;
02964    if (cfg) {
02965       if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
02966          rtpstart = atoi(s);
02967          if (rtpstart < MINIMUM_RTP_PORT)
02968             rtpstart = MINIMUM_RTP_PORT;
02969          if (rtpstart > MAXIMUM_RTP_PORT)
02970             rtpstart = MAXIMUM_RTP_PORT;
02971       }
02972       if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
02973          rtpend = atoi(s);
02974          if (rtpend < MINIMUM_RTP_PORT)
02975             rtpend = MINIMUM_RTP_PORT;
02976          if (rtpend > MAXIMUM_RTP_PORT)
02977             rtpend = MAXIMUM_RTP_PORT;
02978       }
02979       if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
02980          rtcpinterval = atoi(s);
02981          if (rtcpinterval == 0)
02982             rtcpinterval = 0; /* Just so we're clear... it's zero */
02983          if (rtcpinterval < RTCP_MIN_INTERVALMS)
02984             rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
02985          if (rtcpinterval > RTCP_MAX_INTERVALMS)
02986             rtcpinterval = RTCP_MAX_INTERVALMS;
02987       }
02988       if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
02989 #ifdef SO_NO_CHECK
02990          nochecksums = ast_false(s) ? 1 : 0;
02991 #else
02992          if (ast_false(s))
02993             ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
02994 #endif
02995       }
02996       if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
02997          dtmftimeout = atoi(s);
02998          if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
02999             ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
03000                dtmftimeout, DEFAULT_DTMF_TIMEOUT);
03001             dtmftimeout = DEFAULT_DTMF_TIMEOUT;
03002          };
03003       }
03004       if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
03005          strictrtp = ast_true(s);
03006       }
03007       if ((s = ast_variable_retrieve(cfg, "general", "probation"))) {
03008          if ((sscanf(s, "%d", &learning_min_sequential) <= 0) || learning_min_sequential <= 0) {
03009             ast_log(LOG_WARNING, "Value for 'probation' could not be read, using default of '%d' instead\n",
03010                DEFAULT_LEARNING_MIN_SEQUENTIAL);
03011          }
03012       }
03013       ast_config_destroy(cfg);
03014    }
03015    if (rtpstart >= rtpend) {
03016       ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
03017       rtpstart = DEFAULT_RTP_START;
03018       rtpend = DEFAULT_RTP_END;
03019    }
03020    ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
03021    return 0;
03022 }
03023 
03024 static int reload_module(void)
03025 {
03026    rtp_reload(1);
03027    return 0;
03028 }
03029 
03030 static int load_module(void)
03031 {
03032    if (ast_rtp_engine_register(&asterisk_rtp_engine)) {
03033       return AST_MODULE_LOAD_DECLINE;
03034    }
03035 
03036    if (ast_cli_register_multiple(cli_rtp, ARRAY_LEN(cli_rtp))) {
03037       ast_rtp_engine_unregister(&asterisk_rtp_engine);
03038       return AST_MODULE_LOAD_DECLINE;
03039    }
03040 
03041    rtp_reload(0);
03042 
03043    return AST_MODULE_LOAD_SUCCESS;
03044 }
03045 
03046 static int unload_module(void)
03047 {
03048    ast_rtp_engine_unregister(&asterisk_rtp_engine);
03049    ast_cli_unregister_multiple(cli_rtp, ARRAY_LEN(cli_rtp));
03050 
03051    return 0;
03052 }
03053 
03054 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk RTP Stack",
03055       .load = load_module,
03056       .unload = unload_module,
03057       .reload = reload_module,
03058       .load_pri = AST_MODPRI_CHANNEL_DEPEND,
03059       );

Generated on 30 Aug 2012 for Asterisk - The Open Source Telephony Project by  doxygen 1.6.1