Sun Oct 16 2011 08:41:46

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