res_rtp_asterisk.c 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2008, Digium, Inc.
  5. *
  6. * Mark Spencer <markster@digium.com>
  7. *
  8. * See http://www.asterisk.org for more information about
  9. * the Asterisk project. Please do not directly contact
  10. * any of the maintainers of this project for assistance;
  11. * the project provides a web site, mailing lists and IRC
  12. * channels for your use.
  13. *
  14. * This program is free software, distributed under the terms of
  15. * the GNU General Public License Version 2. See the LICENSE file
  16. * at the top of the source tree.
  17. */
  18. /*!
  19. * \file
  20. *
  21. * \brief Supports RTP and RTCP with Symmetric RTP support for NAT traversal.
  22. *
  23. * \author Mark Spencer <markster@digium.com>
  24. *
  25. * \note RTP is defined in RFC 3550.
  26. *
  27. * \ingroup rtp_engines
  28. */
  29. /*** MODULEINFO
  30. <support_level>core</support_level>
  31. ***/
  32. #include "asterisk.h"
  33. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  34. #include <sys/time.h>
  35. #include <signal.h>
  36. #include <fcntl.h>
  37. #include "asterisk/stun.h"
  38. #include "asterisk/pbx.h"
  39. #include "asterisk/frame.h"
  40. #include "asterisk/channel.h"
  41. #include "asterisk/acl.h"
  42. #include "asterisk/config.h"
  43. #include "asterisk/lock.h"
  44. #include "asterisk/utils.h"
  45. #include "asterisk/cli.h"
  46. #include "asterisk/manager.h"
  47. #include "asterisk/unaligned.h"
  48. #include "asterisk/module.h"
  49. #include "asterisk/rtp_engine.h"
  50. #define MAX_TIMESTAMP_SKEW 640
  51. #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
  52. #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
  53. #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
  54. #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
  55. #define DEFAULT_RTP_START 5000 /*!< Default port number to start allocating RTP ports from */
  56. #define DEFAULT_RTP_END 31000 /*!< Default maximum port number to end allocating RTP ports at */
  57. #define MINIMUM_RTP_PORT 1024 /*!< Minimum port number to accept */
  58. #define MAXIMUM_RTP_PORT 65535 /*!< Maximum port number to accept */
  59. #define RTCP_PT_FUR 192
  60. #define RTCP_PT_SR 200
  61. #define RTCP_PT_RR 201
  62. #define RTCP_PT_SDES 202
  63. #define RTCP_PT_BYE 203
  64. #define RTCP_PT_APP 204
  65. #define RTP_MTU 1200
  66. #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
  67. #define ZFONE_PROFILE_ID 0x505a
  68. #define DEFAULT_LEARNING_MIN_SEQUENTIAL 4
  69. extern struct ast_srtp_res *res_srtp;
  70. static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  71. static int rtpstart = DEFAULT_RTP_START; /*!< First port for RTP sessions (set in rtp.conf) */
  72. static int rtpend = DEFAULT_RTP_END; /*!< Last port for RTP sessions (set in rtp.conf) */
  73. static int rtpdebug; /*!< Are we debugging? */
  74. static int rtcpdebug; /*!< Are we debugging RTCP? */
  75. static int rtcpstats; /*!< Are we debugging RTCP? */
  76. static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
  77. static struct ast_sockaddr rtpdebugaddr; /*!< Debug packets to/from this host */
  78. static struct ast_sockaddr rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
  79. static int rtpdebugport; /*< Debug only RTP packets from IP or IP+Port if port is > 0 */
  80. static int rtcpdebugport; /*< Debug only RTCP packets from IP or IP+Port if port is > 0 */
  81. #ifdef SO_NO_CHECK
  82. static int nochecksums;
  83. #endif
  84. static int strictrtp; /*< Only accept RTP frames from a defined source. If we receive an indication of a changing source, enter learning mode. */
  85. static int learning_min_sequential; /*< Number of sequential RTP frames needed from a single source during learning mode to accept new source. */
  86. enum strict_rtp_state {
  87. STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
  88. STRICT_RTP_LEARN, /*! Accept next packet as source */
  89. STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
  90. };
  91. #define FLAG_3389_WARNING (1 << 0)
  92. #define FLAG_NAT_ACTIVE (3 << 1)
  93. #define FLAG_NAT_INACTIVE (0 << 1)
  94. #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
  95. #define FLAG_NEED_MARKER_BIT (1 << 3)
  96. #define FLAG_DTMF_COMPENSATE (1 << 4)
  97. /*! \brief RTP session description */
  98. struct ast_rtp {
  99. int s;
  100. struct ast_frame f;
  101. unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
  102. unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
  103. unsigned int themssrc; /*!< Their SSRC */
  104. unsigned int rxssrc;
  105. unsigned int lastts;
  106. unsigned int lastrxts;
  107. unsigned int lastividtimestamp;
  108. unsigned int lastovidtimestamp;
  109. unsigned int lastitexttimestamp;
  110. unsigned int lastotexttimestamp;
  111. unsigned int lasteventseqn;
  112. int lastrxseqno; /*!< Last received sequence number */
  113. unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
  114. unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
  115. unsigned int rxcount; /*!< How many packets have we received? */
  116. unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
  117. unsigned int txcount; /*!< How many packets have we sent? */
  118. unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
  119. unsigned int cycles; /*!< Shifted count of sequence number cycles */
  120. double rxjitter; /*!< Interarrival jitter at the moment in seconds */
  121. double rxtransit; /*!< Relative transit time for previous packet */
  122. struct ast_format lasttxformat;
  123. struct ast_format lastrxformat;
  124. int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
  125. int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
  126. int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
  127. /* DTMF Reception Variables */
  128. char resp; /*!< The current digit being processed */
  129. unsigned int last_seqno; /*!< The last known sequence number for any DTMF packet */
  130. unsigned int last_end_timestamp; /*!< The last known timestamp received from an END packet */
  131. unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
  132. unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
  133. unsigned int dtmfsamples;
  134. enum ast_rtp_dtmf_mode dtmfmode; /*!< The current DTMF mode of the RTP stream */
  135. /* DTMF Transmission Variables */
  136. unsigned int lastdigitts;
  137. char sending_digit; /*!< boolean - are we sending digits */
  138. char send_digit; /*!< digit we are sending */
  139. int send_payload;
  140. int send_duration;
  141. unsigned int flags;
  142. struct timeval rxcore;
  143. struct timeval txcore;
  144. double drxcore; /*!< The double representation of the first received packet */
  145. struct timeval lastrx; /*!< timeval when we last received a packet */
  146. struct timeval dtmfmute;
  147. struct ast_smoother *smoother;
  148. int *ioid;
  149. unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
  150. unsigned short rxseqno;
  151. struct ast_sched_context *sched;
  152. struct io_context *io;
  153. void *data;
  154. struct ast_rtcp *rtcp;
  155. struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
  156. enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
  157. struct ast_sockaddr strict_rtp_address; /*!< Remote address information for strict RTP purposes */
  158. struct ast_sockaddr alt_rtp_address; /*!<Alternate remote address information */
  159. /*
  160. * Learning mode values based on pjmedia's probation mode. Many of these values are redundant to the above,
  161. * but these are in place to keep learning mode sequence values sealed from their normal counterparts.
  162. */
  163. uint16_t learning_max_seq; /*!< Highest sequence number heard */
  164. int learning_probation; /*!< Sequential packets untill source is valid */
  165. struct rtp_red *red;
  166. };
  167. /*!
  168. * \brief Structure defining an RTCP session.
  169. *
  170. * The concept "RTCP session" is not defined in RFC 3550, but since
  171. * this structure is analogous to ast_rtp, which tracks a RTP session,
  172. * it is logical to think of this as a RTCP session.
  173. *
  174. * RTCP packet is defined on page 9 of RFC 3550.
  175. *
  176. */
  177. struct ast_rtcp {
  178. int rtcp_info;
  179. int s; /*!< Socket */
  180. struct ast_sockaddr us; /*!< Socket representation of the local endpoint. */
  181. struct ast_sockaddr them; /*!< Socket representation of the remote endpoint. */
  182. unsigned int soc; /*!< What they told us */
  183. unsigned int spc; /*!< What they told us */
  184. unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
  185. struct timeval rxlsr; /*!< Time when we got their last SR */
  186. struct timeval txlsr; /*!< Time when we sent or last SR*/
  187. unsigned int expected_prior; /*!< no. packets in previous interval */
  188. unsigned int received_prior; /*!< no. packets received in previous interval */
  189. int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
  190. unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
  191. unsigned int sr_count; /*!< number of SRs we've sent */
  192. unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
  193. double accumulated_transit; /*!< accumulated a-dlsr-lsr */
  194. double rtt; /*!< Last reported rtt */
  195. unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
  196. unsigned int reported_lost; /*!< Reported lost packets in their RR */
  197. double reported_maxjitter;
  198. double reported_minjitter;
  199. double reported_normdev_jitter;
  200. double reported_stdev_jitter;
  201. unsigned int reported_jitter_count;
  202. double reported_maxlost;
  203. double reported_minlost;
  204. double reported_normdev_lost;
  205. double reported_stdev_lost;
  206. double rxlost;
  207. double maxrxlost;
  208. double minrxlost;
  209. double normdev_rxlost;
  210. double stdev_rxlost;
  211. unsigned int rxlost_count;
  212. double maxrxjitter;
  213. double minrxjitter;
  214. double normdev_rxjitter;
  215. double stdev_rxjitter;
  216. unsigned int rxjitter_count;
  217. double maxrtt;
  218. double minrtt;
  219. double normdevrtt;
  220. double stdevrtt;
  221. unsigned int rtt_count;
  222. };
  223. struct rtp_red {
  224. struct ast_frame t140; /*!< Primary data */
  225. struct ast_frame t140red; /*!< Redundant t140*/
  226. unsigned char pt[AST_RED_MAX_GENERATION]; /*!< Payload types for redundancy data */
  227. unsigned char ts[AST_RED_MAX_GENERATION]; /*!< Time stamps */
  228. unsigned char len[AST_RED_MAX_GENERATION]; /*!< length of each generation */
  229. int num_gen; /*!< Number of generations */
  230. int schedid; /*!< Timer id */
  231. int ti; /*!< How long to buffer data before send */
  232. unsigned char t140red_data[64000];
  233. unsigned char buf_data[64000]; /*!< buffered primary data */
  234. int hdrlen;
  235. long int prev_ts;
  236. };
  237. AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
  238. /* Forward Declarations */
  239. static int ast_rtp_new(struct ast_rtp_instance *instance, struct ast_sched_context *sched, struct ast_sockaddr *addr, void *data);
  240. static int ast_rtp_destroy(struct ast_rtp_instance *instance);
  241. static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit);
  242. static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit);
  243. static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration);
  244. static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode);
  245. static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance);
  246. static void ast_rtp_update_source(struct ast_rtp_instance *instance);
  247. static void ast_rtp_change_source(struct ast_rtp_instance *instance);
  248. static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame);
  249. static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp);
  250. static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value);
  251. static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp);
  252. static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
  253. static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr);
  254. static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations);
  255. static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame);
  256. static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1);
  257. static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat);
  258. static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1);
  259. static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username);
  260. static void ast_rtp_stop(struct ast_rtp_instance *instance);
  261. static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char* desc);
  262. static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level);
  263. /* RTP Engine Declaration */
  264. static struct ast_rtp_engine asterisk_rtp_engine = {
  265. .name = "asterisk",
  266. .new = ast_rtp_new,
  267. .destroy = ast_rtp_destroy,
  268. .dtmf_begin = ast_rtp_dtmf_begin,
  269. .dtmf_end = ast_rtp_dtmf_end,
  270. .dtmf_end_with_duration = ast_rtp_dtmf_end_with_duration,
  271. .dtmf_mode_set = ast_rtp_dtmf_mode_set,
  272. .dtmf_mode_get = ast_rtp_dtmf_mode_get,
  273. .update_source = ast_rtp_update_source,
  274. .change_source = ast_rtp_change_source,
  275. .write = ast_rtp_write,
  276. .read = ast_rtp_read,
  277. .prop_set = ast_rtp_prop_set,
  278. .fd = ast_rtp_fd,
  279. .remote_address_set = ast_rtp_remote_address_set,
  280. .alt_remote_address_set = ast_rtp_alt_remote_address_set,
  281. .red_init = rtp_red_init,
  282. .red_buffer = rtp_red_buffer,
  283. .local_bridge = ast_rtp_local_bridge,
  284. .get_stat = ast_rtp_get_stat,
  285. .dtmf_compatible = ast_rtp_dtmf_compatible,
  286. .stun_request = ast_rtp_stun_request,
  287. .stop = ast_rtp_stop,
  288. .qos = ast_rtp_qos_set,
  289. .sendcng = ast_rtp_sendcng,
  290. };
  291. static inline int rtp_debug_test_addr(struct ast_sockaddr *addr)
  292. {
  293. if (!rtpdebug) {
  294. return 0;
  295. }
  296. if (!ast_sockaddr_isnull(&rtpdebugaddr)) {
  297. if (rtpdebugport) {
  298. return (ast_sockaddr_cmp(&rtpdebugaddr, addr) == 0); /* look for RTP packets from IP+Port */
  299. } else {
  300. return (ast_sockaddr_cmp_addr(&rtpdebugaddr, addr) == 0); /* only look for RTP packets from IP */
  301. }
  302. }
  303. return 1;
  304. }
  305. static inline int rtcp_debug_test_addr(struct ast_sockaddr *addr)
  306. {
  307. if (!rtcpdebug) {
  308. return 0;
  309. }
  310. if (!ast_sockaddr_isnull(&rtcpdebugaddr)) {
  311. if (rtcpdebugport) {
  312. return (ast_sockaddr_cmp(&rtcpdebugaddr, addr) == 0); /* look for RTCP packets from IP+Port */
  313. } else {
  314. return (ast_sockaddr_cmp_addr(&rtcpdebugaddr, addr) == 0); /* only look for RTCP packets from IP */
  315. }
  316. }
  317. return 1;
  318. }
  319. static int __rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
  320. {
  321. int len;
  322. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  323. struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
  324. if ((len = ast_recvfrom(rtcp ? rtp->rtcp->s : rtp->s, buf, size, flags, sa)) < 0) {
  325. return len;
  326. }
  327. if (res_srtp && srtp && res_srtp->unprotect(srtp, buf, &len, rtcp) < 0) {
  328. return -1;
  329. }
  330. return len;
  331. }
  332. static int rtcp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
  333. {
  334. return __rtp_recvfrom(instance, buf, size, flags, sa, 1);
  335. }
  336. static int rtp_recvfrom(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
  337. {
  338. return __rtp_recvfrom(instance, buf, size, flags, sa, 0);
  339. }
  340. static int __rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa, int rtcp)
  341. {
  342. int len = size;
  343. void *temp = buf;
  344. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  345. struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
  346. if (res_srtp && srtp && res_srtp->protect(srtp, &temp, &len, rtcp) < 0) {
  347. return -1;
  348. }
  349. return ast_sendto(rtcp ? rtp->rtcp->s : rtp->s, temp, len, flags, sa);
  350. }
  351. static int rtcp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
  352. {
  353. return __rtp_sendto(instance, buf, size, flags, sa, 1);
  354. }
  355. static int rtp_sendto(struct ast_rtp_instance *instance, void *buf, size_t size, int flags, struct ast_sockaddr *sa)
  356. {
  357. return __rtp_sendto(instance, buf, size, flags, sa, 0);
  358. }
  359. static int rtp_get_rate(struct ast_format *format)
  360. {
  361. return (format->id == AST_FORMAT_G722) ? 8000 : ast_format_rate(format);
  362. }
  363. static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
  364. {
  365. unsigned int interval;
  366. /*! \todo XXX Do a more reasonable calculation on this one
  367. * Look in RFC 3550 Section A.7 for an example*/
  368. interval = rtcpinterval;
  369. return interval;
  370. }
  371. /*! \brief Calculate normal deviation */
  372. static double normdev_compute(double normdev, double sample, unsigned int sample_count)
  373. {
  374. normdev = normdev * sample_count + sample;
  375. sample_count++;
  376. return normdev / sample_count;
  377. }
  378. static double stddev_compute(double stddev, double sample, double normdev, double normdev_curent, unsigned int sample_count)
  379. {
  380. /*
  381. for the formula check http://www.cs.umd.edu/~austinjp/constSD.pdf
  382. return sqrt( (sample_count*pow(stddev,2) + sample_count*pow((sample-normdev)/(sample_count+1),2) + pow(sample-normdev_curent,2)) / (sample_count+1));
  383. 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
  384. optimized formula
  385. */
  386. #define SQUARE(x) ((x) * (x))
  387. stddev = sample_count * stddev;
  388. sample_count++;
  389. return stddev +
  390. ( sample_count * SQUARE( (sample - normdev) / sample_count ) ) +
  391. ( SQUARE(sample - normdev_curent) / sample_count );
  392. #undef SQUARE
  393. }
  394. static int create_new_socket(const char *type, int af)
  395. {
  396. int sock = socket(af, SOCK_DGRAM, 0);
  397. if (sock < 0) {
  398. if (!type) {
  399. type = "RTP/RTCP";
  400. }
  401. ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
  402. } else {
  403. long flags = fcntl(sock, F_GETFL);
  404. fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  405. #ifdef SO_NO_CHECK
  406. if (nochecksums) {
  407. setsockopt(sock, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
  408. }
  409. #endif
  410. }
  411. return sock;
  412. }
  413. /*!
  414. * \internal
  415. * \brief Initializes sequence values and probation for learning mode.
  416. * \note This is an adaptation of pjmedia's pjmedia_rtp_seq_init function.
  417. *
  418. * \param rtp pointer to rtp struct used with the received rtp packet.
  419. * \param seq sequence number read from the rtp header
  420. */
  421. static void rtp_learning_seq_init(struct ast_rtp *rtp, uint16_t seq)
  422. {
  423. rtp->learning_max_seq = seq - 1;
  424. rtp->learning_probation = learning_min_sequential;
  425. }
  426. /*!
  427. * \internal
  428. * \brief Updates sequence information for learning mode and determines if probation/learning mode should remain in effect.
  429. * \note This function was adapted from pjmedia's pjmedia_rtp_seq_update function.
  430. *
  431. * \param rtp pointer to rtp struct used with the received rtp packet.
  432. * \param seq sequence number read from the rtp header
  433. * \return boolean value indicating if probation mode is active at the end of the function
  434. */
  435. static int rtp_learning_rtp_seq_update(struct ast_rtp *rtp, uint16_t seq)
  436. {
  437. int probation = 1;
  438. ast_debug(1, "%p -- probation = %d, seq = %d\n", rtp, rtp->learning_probation, seq);
  439. if (seq == rtp->learning_max_seq + 1) {
  440. /* packet is in sequence */
  441. rtp->learning_probation--;
  442. rtp->learning_max_seq = seq;
  443. if (rtp->learning_probation == 0) {
  444. probation = 0;
  445. }
  446. } else {
  447. rtp->learning_probation = learning_min_sequential - 1;
  448. rtp->learning_max_seq = seq;
  449. }
  450. return probation;
  451. }
  452. static int ast_rtp_new(struct ast_rtp_instance *instance,
  453. struct ast_sched_context *sched, struct ast_sockaddr *addr,
  454. void *data)
  455. {
  456. struct ast_rtp *rtp = NULL;
  457. int x, startplace;
  458. /* Create a new RTP structure to hold all of our data */
  459. if (!(rtp = ast_calloc(1, sizeof(*rtp)))) {
  460. return -1;
  461. }
  462. /* Set default parameters on the newly created RTP structure */
  463. rtp->ssrc = ast_random();
  464. rtp->seqno = ast_random() & 0xffff;
  465. rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
  466. if (strictrtp) {
  467. rtp_learning_seq_init(rtp, (uint16_t)rtp->seqno);
  468. }
  469. /* Create a new socket for us to listen on and use */
  470. if ((rtp->s =
  471. create_new_socket("RTP",
  472. ast_sockaddr_is_ipv4(addr) ? AF_INET :
  473. ast_sockaddr_is_ipv6(addr) ? AF_INET6 : -1)) < 0) {
  474. ast_debug(1, "Failed to create a new socket for RTP instance '%p'\n", instance);
  475. ast_free(rtp);
  476. return -1;
  477. }
  478. /* Now actually find a free RTP port to use */
  479. x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
  480. x = x & ~1;
  481. startplace = x;
  482. for (;;) {
  483. ast_sockaddr_set_port(addr, x);
  484. /* Try to bind, this will tell us whether the port is available or not */
  485. if (!ast_bind(rtp->s, addr)) {
  486. ast_debug(1, "Allocated port %d for RTP instance '%p'\n", x, instance);
  487. ast_rtp_instance_set_local_address(instance, addr);
  488. break;
  489. }
  490. x += 2;
  491. if (x > rtpend) {
  492. x = (rtpstart + 1) & ~1;
  493. }
  494. /* See if we ran out of ports or if the bind actually failed because of something other than the address being in use */
  495. if (x == startplace || errno != EADDRINUSE) {
  496. ast_log(LOG_ERROR, "Oh dear... we couldn't allocate a port for RTP instance '%p'\n", instance);
  497. close(rtp->s);
  498. ast_free(rtp);
  499. return -1;
  500. }
  501. }
  502. /* Record any information we may need */
  503. rtp->sched = sched;
  504. /* Associate the RTP structure with the RTP instance and be done */
  505. ast_rtp_instance_set_data(instance, rtp);
  506. return 0;
  507. }
  508. static int ast_rtp_destroy(struct ast_rtp_instance *instance)
  509. {
  510. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  511. /* Destroy the smoother that was smoothing out audio if present */
  512. if (rtp->smoother) {
  513. ast_smoother_free(rtp->smoother);
  514. }
  515. /* Close our own socket so we no longer get packets */
  516. if (rtp->s > -1) {
  517. close(rtp->s);
  518. }
  519. /* Destroy RTCP if it was being used */
  520. if (rtp->rtcp) {
  521. /*
  522. * It is not possible for there to be an active RTCP scheduler
  523. * entry at this point since it holds a reference to the
  524. * RTP instance while it's active.
  525. */
  526. close(rtp->rtcp->s);
  527. ast_free(rtp->rtcp);
  528. }
  529. /* Destroy RED if it was being used */
  530. if (rtp->red) {
  531. AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
  532. ast_free(rtp->red);
  533. }
  534. /* Finally destroy ourselves */
  535. ast_free(rtp);
  536. return 0;
  537. }
  538. static int ast_rtp_dtmf_mode_set(struct ast_rtp_instance *instance, enum ast_rtp_dtmf_mode dtmf_mode)
  539. {
  540. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  541. rtp->dtmfmode = dtmf_mode;
  542. return 0;
  543. }
  544. static enum ast_rtp_dtmf_mode ast_rtp_dtmf_mode_get(struct ast_rtp_instance *instance)
  545. {
  546. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  547. return rtp->dtmfmode;
  548. }
  549. static int ast_rtp_dtmf_begin(struct ast_rtp_instance *instance, char digit)
  550. {
  551. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  552. struct ast_sockaddr remote_address = { {0,} };
  553. int hdrlen = 12, res = 0, i = 0, payload = 101;
  554. char data[256];
  555. unsigned int *rtpheader = (unsigned int*)data;
  556. ast_rtp_instance_get_remote_address(instance, &remote_address);
  557. /* If we have no remote address information bail out now */
  558. if (ast_sockaddr_isnull(&remote_address)) {
  559. return -1;
  560. }
  561. /* Convert given digit into what we want to transmit */
  562. if ((digit <= '9') && (digit >= '0')) {
  563. digit -= '0';
  564. } else if (digit == '*') {
  565. digit = 10;
  566. } else if (digit == '#') {
  567. digit = 11;
  568. } else if ((digit >= 'A') && (digit <= 'D')) {
  569. digit = digit - 'A' + 12;
  570. } else if ((digit >= 'a') && (digit <= 'd')) {
  571. digit = digit - 'a' + 12;
  572. } else {
  573. ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
  574. return -1;
  575. }
  576. /* Grab the payload that they expect the RFC2833 packet to be received in */
  577. payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_DTMF);
  578. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  579. rtp->send_duration = 160;
  580. rtp->lastdigitts = rtp->lastts + rtp->send_duration;
  581. /* Create the actual packet that we will be sending */
  582. rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
  583. rtpheader[1] = htonl(rtp->lastdigitts);
  584. rtpheader[2] = htonl(rtp->ssrc);
  585. /* Actually send the packet */
  586. for (i = 0; i < 2; i++) {
  587. rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
  588. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address);
  589. if (res < 0) {
  590. ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
  591. ast_sockaddr_stringify(&remote_address),
  592. strerror(errno));
  593. }
  594. if (rtp_debug_test_addr(&remote_address)) {
  595. ast_verbose("Sent RTP DTMF packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  596. ast_sockaddr_stringify(&remote_address),
  597. payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  598. }
  599. rtp->seqno++;
  600. rtp->send_duration += 160;
  601. rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
  602. }
  603. /* Record that we are in the process of sending a digit and information needed to continue doing so */
  604. rtp->sending_digit = 1;
  605. rtp->send_digit = digit;
  606. rtp->send_payload = payload;
  607. return 0;
  608. }
  609. static int ast_rtp_dtmf_continuation(struct ast_rtp_instance *instance)
  610. {
  611. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  612. struct ast_sockaddr remote_address = { {0,} };
  613. int hdrlen = 12, res = 0;
  614. char data[256];
  615. unsigned int *rtpheader = (unsigned int*)data;
  616. ast_rtp_instance_get_remote_address(instance, &remote_address);
  617. /* Make sure we know where the other side is so we can send them the packet */
  618. if (ast_sockaddr_isnull(&remote_address)) {
  619. return -1;
  620. }
  621. /* Actually create the packet we will be sending */
  622. rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
  623. rtpheader[1] = htonl(rtp->lastdigitts);
  624. rtpheader[2] = htonl(rtp->ssrc);
  625. rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
  626. /* Boom, send it on out */
  627. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address);
  628. if (res < 0) {
  629. ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
  630. ast_sockaddr_stringify(&remote_address),
  631. strerror(errno));
  632. }
  633. if (rtp_debug_test_addr(&remote_address)) {
  634. ast_verbose("Sent RTP DTMF packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  635. ast_sockaddr_stringify(&remote_address),
  636. rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  637. }
  638. /* And now we increment some values for the next time we swing by */
  639. rtp->seqno++;
  640. rtp->send_duration += 160;
  641. return 0;
  642. }
  643. static int ast_rtp_dtmf_end_with_duration(struct ast_rtp_instance *instance, char digit, unsigned int duration)
  644. {
  645. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  646. struct ast_sockaddr remote_address = { {0,} };
  647. int hdrlen = 12, res = 0, i = 0;
  648. char data[256];
  649. unsigned int *rtpheader = (unsigned int*)data;
  650. unsigned int measured_samples;
  651. ast_rtp_instance_get_remote_address(instance, &remote_address);
  652. /* Make sure we know where the remote side is so we can send them the packet we construct */
  653. if (ast_sockaddr_isnull(&remote_address)) {
  654. return -1;
  655. }
  656. /* Convert the given digit to the one we are going to send */
  657. if ((digit <= '9') && (digit >= '0')) {
  658. digit -= '0';
  659. } else if (digit == '*') {
  660. digit = 10;
  661. } else if (digit == '#') {
  662. digit = 11;
  663. } else if ((digit >= 'A') && (digit <= 'D')) {
  664. digit = digit - 'A' + 12;
  665. } else if ((digit >= 'a') && (digit <= 'd')) {
  666. digit = digit - 'a' + 12;
  667. } else {
  668. ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
  669. return -1;
  670. }
  671. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  672. if (duration > 0 && (measured_samples = duration * rtp_get_rate(&rtp->f.subclass.format) / 1000) > rtp->send_duration) {
  673. ast_debug(2, "Adjusting final end duration from %u to %u\n", rtp->send_duration, measured_samples);
  674. rtp->send_duration = measured_samples;
  675. }
  676. /* Construct the packet we are going to send */
  677. rtpheader[1] = htonl(rtp->lastdigitts);
  678. rtpheader[2] = htonl(rtp->ssrc);
  679. rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
  680. rtpheader[3] |= htonl((1 << 23));
  681. /* Send it 3 times, that's the magical number */
  682. for (i = 0; i < 3; i++) {
  683. rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
  684. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 4, 0, &remote_address);
  685. if (res < 0) {
  686. ast_log(LOG_ERROR, "RTP Transmission error to %s: %s\n",
  687. ast_sockaddr_stringify(&remote_address),
  688. strerror(errno));
  689. }
  690. if (rtp_debug_test_addr(&remote_address)) {
  691. ast_verbose("Sent RTP DTMF packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  692. ast_sockaddr_stringify(&remote_address),
  693. rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  694. }
  695. rtp->seqno++;
  696. }
  697. /* Oh and we can't forget to turn off the stuff that says we are sending DTMF */
  698. rtp->lastts += rtp->send_duration;
  699. rtp->sending_digit = 0;
  700. rtp->send_digit = 0;
  701. return 0;
  702. }
  703. static int ast_rtp_dtmf_end(struct ast_rtp_instance *instance, char digit)
  704. {
  705. return ast_rtp_dtmf_end_with_duration(instance, digit, 0);
  706. }
  707. static void ast_rtp_update_source(struct ast_rtp_instance *instance)
  708. {
  709. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  710. /* We simply set this bit so that the next packet sent will have the marker bit turned on */
  711. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  712. ast_debug(3, "Setting the marker bit due to a source update\n");
  713. return;
  714. }
  715. static void ast_rtp_change_source(struct ast_rtp_instance *instance)
  716. {
  717. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  718. struct ast_srtp *srtp = ast_rtp_instance_get_srtp(instance);
  719. unsigned int ssrc = ast_random();
  720. if (!rtp->lastts) {
  721. ast_debug(3, "Not changing SSRC since we haven't sent any RTP yet\n");
  722. return;
  723. }
  724. /* We simply set this bit so that the next packet sent will have the marker bit turned on */
  725. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  726. ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
  727. if (srtp) {
  728. ast_debug(3, "Changing ssrc for SRTP from %u to %u\n", rtp->ssrc, ssrc);
  729. res_srtp->change_source(srtp, rtp->ssrc, ssrc);
  730. }
  731. rtp->ssrc = ssrc;
  732. return;
  733. }
  734. static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
  735. {
  736. struct timeval t;
  737. long ms;
  738. if (ast_tvzero(rtp->txcore)) {
  739. rtp->txcore = ast_tvnow();
  740. rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
  741. }
  742. t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
  743. if ((ms = ast_tvdiff_ms(t, rtp->txcore)) < 0) {
  744. ms = 0;
  745. }
  746. rtp->txcore = t;
  747. return (unsigned int) ms;
  748. }
  749. static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
  750. {
  751. unsigned int sec, usec, frac;
  752. sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
  753. usec = tv.tv_usec;
  754. frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
  755. *msw = sec;
  756. *lsw = frac;
  757. }
  758. /*! \brief Send RTCP recipient's report */
  759. static int ast_rtcp_write_rr(struct ast_rtp_instance *instance)
  760. {
  761. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  762. int res;
  763. int len = 32;
  764. unsigned int lost;
  765. unsigned int extended;
  766. unsigned int expected;
  767. unsigned int expected_interval;
  768. unsigned int received_interval;
  769. int lost_interval;
  770. struct timeval now;
  771. unsigned int *rtcpheader;
  772. char bdata[1024];
  773. struct timeval dlsr;
  774. int fraction;
  775. int rate = rtp_get_rate(&rtp->f.subclass.format);
  776. double rxlost_current;
  777. if (!rtp || !rtp->rtcp)
  778. return 0;
  779. if (ast_sockaddr_isnull(&rtp->rtcp->them)) {
  780. /*
  781. * RTCP was stopped.
  782. */
  783. return 0;
  784. }
  785. extended = rtp->cycles + rtp->lastrxseqno;
  786. expected = extended - rtp->seedrxseqno + 1;
  787. lost = expected - rtp->rxcount;
  788. expected_interval = expected - rtp->rtcp->expected_prior;
  789. rtp->rtcp->expected_prior = expected;
  790. received_interval = rtp->rxcount - rtp->rtcp->received_prior;
  791. rtp->rtcp->received_prior = rtp->rxcount;
  792. lost_interval = expected_interval - received_interval;
  793. if (lost_interval <= 0)
  794. rtp->rtcp->rxlost = 0;
  795. else rtp->rtcp->rxlost = rtp->rtcp->rxlost;
  796. if (rtp->rtcp->rxlost_count == 0)
  797. rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
  798. if (lost_interval < rtp->rtcp->minrxlost)
  799. rtp->rtcp->minrxlost = rtp->rtcp->rxlost;
  800. if (lost_interval > rtp->rtcp->maxrxlost)
  801. rtp->rtcp->maxrxlost = rtp->rtcp->rxlost;
  802. rxlost_current = normdev_compute(rtp->rtcp->normdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->rxlost_count);
  803. rtp->rtcp->stdev_rxlost = stddev_compute(rtp->rtcp->stdev_rxlost, rtp->rtcp->rxlost, rtp->rtcp->normdev_rxlost, rxlost_current, rtp->rtcp->rxlost_count);
  804. rtp->rtcp->normdev_rxlost = rxlost_current;
  805. rtp->rtcp->rxlost_count++;
  806. if (expected_interval == 0 || lost_interval <= 0)
  807. fraction = 0;
  808. else
  809. fraction = (lost_interval << 8) / expected_interval;
  810. gettimeofday(&now, NULL);
  811. timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
  812. rtcpheader = (unsigned int *)bdata;
  813. rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
  814. rtcpheader[1] = htonl(rtp->ssrc);
  815. rtcpheader[2] = htonl(rtp->themssrc);
  816. rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
  817. rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
  818. rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * rate));
  819. rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
  820. rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
  821. /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
  822. it can change mid call, and SDES can't) */
  823. rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
  824. rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
  825. rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
  826. len += 12;
  827. res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &rtp->rtcp->them);
  828. if (res < 0) {
  829. ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
  830. return 0;
  831. }
  832. rtp->rtcp->rr_count++;
  833. if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
  834. ast_verbose("\n* Sending RTCP RR to %s\n"
  835. " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
  836. " IA jitter: %.4f\n"
  837. " Their last SR: %u\n"
  838. " DLSR: %4.4f (sec)\n\n",
  839. ast_sockaddr_stringify(&rtp->rtcp->them),
  840. rtp->ssrc, rtp->themssrc, fraction, lost,
  841. rtp->rxjitter,
  842. rtp->rtcp->themrxlsr,
  843. (double)(ntohl(rtcpheader[7])/65536.0));
  844. }
  845. return res;
  846. }
  847. /*! \brief Send RTCP sender's report */
  848. static int ast_rtcp_write_sr(struct ast_rtp_instance *instance)
  849. {
  850. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  851. int res;
  852. int len = 0;
  853. struct timeval now;
  854. unsigned int now_lsw;
  855. unsigned int now_msw;
  856. unsigned int *rtcpheader;
  857. unsigned int lost;
  858. unsigned int extended;
  859. unsigned int expected;
  860. unsigned int expected_interval;
  861. unsigned int received_interval;
  862. int lost_interval;
  863. int fraction;
  864. struct timeval dlsr;
  865. char bdata[512];
  866. int rate = rtp_get_rate(&rtp->f.subclass.format);
  867. if (!rtp || !rtp->rtcp)
  868. return 0;
  869. if (ast_sockaddr_isnull(&rtp->rtcp->them)) { /* This'll stop rtcp for this rtp session */
  870. /*
  871. * RTCP was stopped.
  872. */
  873. return 0;
  874. }
  875. gettimeofday(&now, NULL);
  876. timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
  877. rtcpheader = (unsigned int *)bdata;
  878. rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
  879. rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
  880. rtcpheader[3] = htonl(now_lsw); /* now, LSW */
  881. rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
  882. rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
  883. rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
  884. len += 28;
  885. extended = rtp->cycles + rtp->lastrxseqno;
  886. expected = extended - rtp->seedrxseqno + 1;
  887. if (rtp->rxcount > expected)
  888. expected += rtp->rxcount - expected;
  889. lost = expected - rtp->rxcount;
  890. expected_interval = expected - rtp->rtcp->expected_prior;
  891. rtp->rtcp->expected_prior = expected;
  892. received_interval = rtp->rxcount - rtp->rtcp->received_prior;
  893. rtp->rtcp->received_prior = rtp->rxcount;
  894. lost_interval = expected_interval - received_interval;
  895. if (expected_interval == 0 || lost_interval <= 0)
  896. fraction = 0;
  897. else
  898. fraction = (lost_interval << 8) / expected_interval;
  899. timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
  900. rtcpheader[7] = htonl(rtp->themssrc);
  901. rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
  902. rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
  903. rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * rate));
  904. rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
  905. rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
  906. len += 24;
  907. rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
  908. /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
  909. /* it can change mid call, and SDES can't) */
  910. rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
  911. rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
  912. rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
  913. len += 12;
  914. res = rtcp_sendto(instance, (unsigned int *)rtcpheader, len, 0, &rtp->rtcp->them);
  915. if (res < 0) {
  916. ast_log(LOG_ERROR, "RTCP SR transmission error to %s, rtcp halted %s\n",
  917. ast_sockaddr_stringify(&rtp->rtcp->them),
  918. strerror(errno));
  919. return 0;
  920. }
  921. /* FIXME Don't need to get a new one */
  922. gettimeofday(&rtp->rtcp->txlsr, NULL);
  923. rtp->rtcp->sr_count++;
  924. rtp->rtcp->lastsrtxcount = rtp->txcount;
  925. if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
  926. ast_verbose("* Sent RTCP SR to %s\n", ast_sockaddr_stringify(&rtp->rtcp->them));
  927. ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
  928. ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
  929. ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
  930. ast_verbose(" Sent packets: %u\n", rtp->txcount);
  931. ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
  932. ast_verbose(" Report block:\n");
  933. ast_verbose(" Fraction lost: %u\n", fraction);
  934. ast_verbose(" Cumulative loss: %u\n", lost);
  935. ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
  936. ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
  937. ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
  938. }
  939. manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To: %s\r\n"
  940. "OurSSRC: %u\r\n"
  941. "SentNTP: %u.%010u\r\n"
  942. "SentRTP: %u\r\n"
  943. "SentPackets: %u\r\n"
  944. "SentOctets: %u\r\n"
  945. "ReportBlock:\r\n"
  946. "FractionLost: %u\r\n"
  947. "CumulativeLoss: %u\r\n"
  948. "IAJitter: %.4f\r\n"
  949. "TheirLastSR: %u\r\n"
  950. "DLSR: %4.4f (sec)\r\n",
  951. ast_sockaddr_stringify(&rtp->rtcp->them),
  952. rtp->ssrc,
  953. (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
  954. rtp->lastts,
  955. rtp->txcount,
  956. rtp->txoctetcount,
  957. fraction,
  958. lost,
  959. rtp->rxjitter,
  960. rtp->rtcp->themrxlsr,
  961. (double)(ntohl(rtcpheader[12])/65536.0));
  962. return res;
  963. }
  964. /*! \brief Write and RTCP packet to the far end
  965. * \note Decide if we are going to send an SR (with Reception Block) or RR
  966. * RR is sent if we have not sent any rtp packets in the previous interval */
  967. static int ast_rtcp_write(const void *data)
  968. {
  969. struct ast_rtp_instance *instance = (struct ast_rtp_instance *) data;
  970. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  971. int res;
  972. if (!rtp || !rtp->rtcp || rtp->rtcp->schedid == -1) {
  973. ao2_ref(instance, -1);
  974. return 0;
  975. }
  976. if (rtp->txcount > rtp->rtcp->lastsrtxcount) {
  977. res = ast_rtcp_write_sr(instance);
  978. } else {
  979. res = ast_rtcp_write_rr(instance);
  980. }
  981. if (!res) {
  982. /*
  983. * Not being rescheduled.
  984. */
  985. ao2_ref(instance, -1);
  986. rtp->rtcp->schedid = -1;
  987. }
  988. return res;
  989. }
  990. static int ast_rtp_raw_write(struct ast_rtp_instance *instance, struct ast_frame *frame, int codec)
  991. {
  992. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  993. int pred, mark = 0;
  994. unsigned int ms = calc_txstamp(rtp, &frame->delivery);
  995. struct ast_sockaddr remote_address = { {0,} };
  996. int rate = rtp_get_rate(&frame->subclass.format) / 1000;
  997. if (frame->subclass.format.id == AST_FORMAT_G722) {
  998. frame->samples /= 2;
  999. }
  1000. if (rtp->sending_digit) {
  1001. return 0;
  1002. }
  1003. if (frame->frametype == AST_FRAME_VOICE) {
  1004. pred = rtp->lastts + frame->samples;
  1005. /* Re-calculate last TS */
  1006. rtp->lastts = rtp->lastts + ms * rate;
  1007. if (ast_tvzero(frame->delivery)) {
  1008. /* If this isn't an absolute delivery time, Check if it is close to our prediction,
  1009. and if so, go with our prediction */
  1010. if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW) {
  1011. rtp->lastts = pred;
  1012. } else {
  1013. ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
  1014. mark = 1;
  1015. }
  1016. }
  1017. } else if (frame->frametype == AST_FRAME_VIDEO) {
  1018. mark = ast_format_get_video_mark(&frame->subclass.format);
  1019. pred = rtp->lastovidtimestamp + frame->samples;
  1020. /* Re-calculate last TS */
  1021. rtp->lastts = rtp->lastts + ms * 90;
  1022. /* If it's close to our prediction, go for it */
  1023. if (ast_tvzero(frame->delivery)) {
  1024. if (abs(rtp->lastts - pred) < 7200) {
  1025. rtp->lastts = pred;
  1026. rtp->lastovidtimestamp += frame->samples;
  1027. } else {
  1028. 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);
  1029. rtp->lastovidtimestamp = rtp->lastts;
  1030. }
  1031. }
  1032. } else {
  1033. pred = rtp->lastotexttimestamp + frame->samples;
  1034. /* Re-calculate last TS */
  1035. rtp->lastts = rtp->lastts + ms;
  1036. /* If it's close to our prediction, go for it */
  1037. if (ast_tvzero(frame->delivery)) {
  1038. if (abs(rtp->lastts - pred) < 7200) {
  1039. rtp->lastts = pred;
  1040. rtp->lastotexttimestamp += frame->samples;
  1041. } else {
  1042. 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);
  1043. rtp->lastotexttimestamp = rtp->lastts;
  1044. }
  1045. }
  1046. }
  1047. /* If we have been explicitly told to set the marker bit then do so */
  1048. if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
  1049. mark = 1;
  1050. ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
  1051. }
  1052. /* If the timestamp for non-digt packets has moved beyond the timestamp for digits, update the digit timestamp */
  1053. if (rtp->lastts > rtp->lastdigitts) {
  1054. rtp->lastdigitts = rtp->lastts;
  1055. }
  1056. if (ast_test_flag(frame, AST_FRFLAG_HAS_TIMING_INFO)) {
  1057. rtp->lastts = frame->ts * rate;
  1058. }
  1059. ast_rtp_instance_get_remote_address(instance, &remote_address);
  1060. /* If we know the remote address construct a packet and send it out */
  1061. if (!ast_sockaddr_isnull(&remote_address)) {
  1062. int hdrlen = 12, res;
  1063. unsigned char *rtpheader = (unsigned char *)(frame->data.ptr - hdrlen);
  1064. put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
  1065. put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
  1066. put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
  1067. if ((res = rtp_sendto(instance, (void *)rtpheader, frame->datalen + hdrlen, 0, &remote_address)) < 0) {
  1068. 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))) {
  1069. ast_debug(1, "RTP Transmission error of packet %d to %s: %s\n",
  1070. rtp->seqno,
  1071. ast_sockaddr_stringify(&remote_address),
  1072. strerror(errno));
  1073. } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
  1074. /* Only give this error message once if we are not RTP debugging */
  1075. if (rtpdebug)
  1076. ast_debug(0, "RTP NAT: Can't write RTP to private address %s, waiting for other end to send audio...\n",
  1077. ast_sockaddr_stringify(&remote_address));
  1078. ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
  1079. }
  1080. } else {
  1081. rtp->txcount++;
  1082. rtp->txoctetcount += (res - hdrlen);
  1083. if (rtp->rtcp && rtp->rtcp->schedid < 1) {
  1084. ast_debug(1, "Starting RTCP transmission on RTP instance '%p'\n", instance);
  1085. ao2_ref(instance, +1);
  1086. rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
  1087. if (rtp->rtcp->schedid < 0) {
  1088. ao2_ref(instance, -1);
  1089. ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
  1090. }
  1091. }
  1092. }
  1093. if (rtp_debug_test_addr(&remote_address)) {
  1094. ast_verbose("Sent RTP packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  1095. ast_sockaddr_stringify(&remote_address),
  1096. codec, rtp->seqno, rtp->lastts, res - hdrlen);
  1097. }
  1098. }
  1099. rtp->seqno++;
  1100. return 0;
  1101. }
  1102. static struct ast_frame *red_t140_to_red(struct rtp_red *red) {
  1103. unsigned char *data = red->t140red.data.ptr;
  1104. int len = 0;
  1105. int i;
  1106. /* replace most aged generation */
  1107. if (red->len[0]) {
  1108. for (i = 1; i < red->num_gen+1; i++)
  1109. len += red->len[i];
  1110. memmove(&data[red->hdrlen], &data[red->hdrlen+red->len[0]], len);
  1111. }
  1112. /* Store length of each generation and primary data length*/
  1113. for (i = 0; i < red->num_gen; i++)
  1114. red->len[i] = red->len[i+1];
  1115. red->len[i] = red->t140.datalen;
  1116. /* write each generation length in red header */
  1117. len = red->hdrlen;
  1118. for (i = 0; i < red->num_gen; i++)
  1119. len += data[i*4+3] = red->len[i];
  1120. /* add primary data to buffer */
  1121. memcpy(&data[len], red->t140.data.ptr, red->t140.datalen);
  1122. red->t140red.datalen = len + red->t140.datalen;
  1123. /* no primary data and no generations to send */
  1124. if (len == red->hdrlen && !red->t140.datalen)
  1125. return NULL;
  1126. /* reset t.140 buffer */
  1127. red->t140.datalen = 0;
  1128. return &red->t140red;
  1129. }
  1130. static int ast_rtp_write(struct ast_rtp_instance *instance, struct ast_frame *frame)
  1131. {
  1132. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1133. struct ast_sockaddr remote_address = { {0,} };
  1134. struct ast_format subclass;
  1135. int codec;
  1136. ast_rtp_instance_get_remote_address(instance, &remote_address);
  1137. /* If we don't actually know the remote address don't even bother doing anything */
  1138. if (ast_sockaddr_isnull(&remote_address)) {
  1139. ast_debug(1, "No remote address on RTP instance '%p' so dropping frame\n", instance);
  1140. return 0;
  1141. }
  1142. /* If there is no data length we can't very well send the packet */
  1143. if (!frame->datalen) {
  1144. ast_debug(1, "Received frame with no data for RTP instance '%p' so dropping frame\n", instance);
  1145. return 0;
  1146. }
  1147. /* If the packet is not one our RTP stack supports bail out */
  1148. if (frame->frametype != AST_FRAME_VOICE && frame->frametype != AST_FRAME_VIDEO && frame->frametype != AST_FRAME_TEXT) {
  1149. ast_log(LOG_WARNING, "RTP can only send voice, video, and text\n");
  1150. return -1;
  1151. }
  1152. if (rtp->red) {
  1153. /* return 0; */
  1154. /* no primary data or generations to send */
  1155. if ((frame = red_t140_to_red(rtp->red)) == NULL)
  1156. return 0;
  1157. }
  1158. /* Grab the subclass and look up the payload we are going to use */
  1159. ast_format_copy(&subclass, &frame->subclass.format);
  1160. if ((codec = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 1, &subclass, 0)) < 0) {
  1161. ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(&frame->subclass.format));
  1162. return -1;
  1163. }
  1164. /* Oh dear, if the format changed we will have to set up a new smoother */
  1165. if (ast_format_cmp(&rtp->lasttxformat, &subclass) == AST_FORMAT_CMP_NOT_EQUAL) {
  1166. ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(&rtp->lasttxformat), ast_getformatname(&subclass));
  1167. rtp->lasttxformat = subclass;
  1168. ast_format_copy(&rtp->lasttxformat, &subclass);
  1169. if (rtp->smoother) {
  1170. ast_smoother_free(rtp->smoother);
  1171. rtp->smoother = NULL;
  1172. }
  1173. }
  1174. /* If no smoother is present see if we have to set one up */
  1175. if (!rtp->smoother) {
  1176. struct ast_format_list fmt = ast_codec_pref_getsize(&ast_rtp_instance_get_codecs(instance)->pref, &subclass);
  1177. switch (subclass.id) {
  1178. case AST_FORMAT_SPEEX:
  1179. case AST_FORMAT_SPEEX16:
  1180. case AST_FORMAT_SPEEX32:
  1181. case AST_FORMAT_SILK:
  1182. case AST_FORMAT_CELT:
  1183. case AST_FORMAT_G723_1:
  1184. case AST_FORMAT_SIREN7:
  1185. case AST_FORMAT_SIREN14:
  1186. case AST_FORMAT_G719:
  1187. /* these are all frame-based codecs and cannot be safely run through
  1188. a smoother */
  1189. break;
  1190. default:
  1191. if (fmt.inc_ms) {
  1192. if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
  1193. 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));
  1194. return -1;
  1195. }
  1196. if (fmt.flags) {
  1197. ast_smoother_set_flags(rtp->smoother, fmt.flags);
  1198. }
  1199. 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));
  1200. }
  1201. }
  1202. }
  1203. /* Feed audio frames into the actual function that will create a frame and send it */
  1204. if (rtp->smoother) {
  1205. struct ast_frame *f;
  1206. if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
  1207. ast_smoother_feed_be(rtp->smoother, frame);
  1208. } else {
  1209. ast_smoother_feed(rtp->smoother, frame);
  1210. }
  1211. while ((f = ast_smoother_read(rtp->smoother)) && (f->data.ptr)) {
  1212. ast_rtp_raw_write(instance, f, codec);
  1213. }
  1214. } else {
  1215. int hdrlen = 12;
  1216. struct ast_frame *f = NULL;
  1217. if (frame->offset < hdrlen) {
  1218. f = ast_frdup(frame);
  1219. } else {
  1220. f = frame;
  1221. }
  1222. if (f->data.ptr) {
  1223. ast_rtp_raw_write(instance, f, codec);
  1224. }
  1225. if (f != frame) {
  1226. ast_frfree(f);
  1227. }
  1228. }
  1229. return 0;
  1230. }
  1231. static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
  1232. {
  1233. struct timeval now;
  1234. struct timeval tmp;
  1235. double transit;
  1236. double current_time;
  1237. double d;
  1238. double dtv;
  1239. double prog;
  1240. int rate = rtp_get_rate(&rtp->f.subclass.format);
  1241. double normdev_rxjitter_current;
  1242. if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
  1243. gettimeofday(&rtp->rxcore, NULL);
  1244. rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
  1245. /* map timestamp to a real time */
  1246. rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
  1247. tmp = ast_samp2tv(timestamp, rate);
  1248. rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
  1249. /* Round to 0.1ms for nice, pretty timestamps */
  1250. rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
  1251. }
  1252. gettimeofday(&now,NULL);
  1253. /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
  1254. tmp = ast_samp2tv(timestamp, rate);
  1255. *tv = ast_tvadd(rtp->rxcore, tmp);
  1256. prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
  1257. dtv = (double)rtp->drxcore + (double)(prog);
  1258. current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
  1259. transit = current_time - dtv;
  1260. d = transit - rtp->rxtransit;
  1261. rtp->rxtransit = transit;
  1262. if (d<0)
  1263. d=-d;
  1264. rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
  1265. if (rtp->rtcp) {
  1266. if (rtp->rxjitter > rtp->rtcp->maxrxjitter)
  1267. rtp->rtcp->maxrxjitter = rtp->rxjitter;
  1268. if (rtp->rtcp->rxjitter_count == 1)
  1269. rtp->rtcp->minrxjitter = rtp->rxjitter;
  1270. if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
  1271. rtp->rtcp->minrxjitter = rtp->rxjitter;
  1272. normdev_rxjitter_current = normdev_compute(rtp->rtcp->normdev_rxjitter,rtp->rxjitter,rtp->rtcp->rxjitter_count);
  1273. rtp->rtcp->stdev_rxjitter = stddev_compute(rtp->rtcp->stdev_rxjitter,rtp->rxjitter,rtp->rtcp->normdev_rxjitter,normdev_rxjitter_current,rtp->rtcp->rxjitter_count);
  1274. rtp->rtcp->normdev_rxjitter = normdev_rxjitter_current;
  1275. rtp->rtcp->rxjitter_count++;
  1276. }
  1277. }
  1278. static struct ast_frame *create_dtmf_frame(struct ast_rtp_instance *instance, enum ast_frame_type type, int compensate)
  1279. {
  1280. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1281. struct ast_sockaddr remote_address = { {0,} };
  1282. ast_rtp_instance_get_remote_address(instance, &remote_address);
  1283. if (((compensate && type == AST_FRAME_DTMF_END) || (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
  1284. ast_debug(1, "Ignore potential DTMF echo from '%s'\n",
  1285. ast_sockaddr_stringify(&remote_address));
  1286. rtp->resp = 0;
  1287. rtp->dtmfsamples = 0;
  1288. return &ast_null_frame;
  1289. }
  1290. ast_debug(1, "Creating %s DTMF Frame: %d (%c), at %s\n",
  1291. type == AST_FRAME_DTMF_END ? "END" : "BEGIN",
  1292. rtp->resp, rtp->resp,
  1293. ast_sockaddr_stringify(&remote_address));
  1294. if (rtp->resp == 'X') {
  1295. rtp->f.frametype = AST_FRAME_CONTROL;
  1296. rtp->f.subclass.integer = AST_CONTROL_FLASH;
  1297. } else {
  1298. rtp->f.frametype = type;
  1299. rtp->f.subclass.integer = rtp->resp;
  1300. }
  1301. rtp->f.datalen = 0;
  1302. rtp->f.samples = 0;
  1303. rtp->f.mallocd = 0;
  1304. rtp->f.src = "RTP";
  1305. AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
  1306. return &rtp->f;
  1307. }
  1308. 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)
  1309. {
  1310. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1311. struct ast_sockaddr remote_address = { {0,} };
  1312. unsigned int event, event_end, samples;
  1313. char resp = 0;
  1314. struct ast_frame *f = NULL;
  1315. ast_rtp_instance_get_remote_address(instance, &remote_address);
  1316. /* Figure out event, event end, and samples */
  1317. event = ntohl(*((unsigned int *)(data)));
  1318. event >>= 24;
  1319. event_end = ntohl(*((unsigned int *)(data)));
  1320. event_end <<= 8;
  1321. event_end >>= 24;
  1322. samples = ntohl(*((unsigned int *)(data)));
  1323. samples &= 0xFFFF;
  1324. if (rtp_debug_test_addr(&remote_address)) {
  1325. 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",
  1326. ast_sockaddr_stringify(&remote_address),
  1327. payloadtype, seqno, timestamp, len, (mark?1:0), event, ((event_end & 0x80)?1:0), samples);
  1328. }
  1329. /* Print out debug if turned on */
  1330. if (rtpdebug)
  1331. ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
  1332. /* Figure out what digit was pressed */
  1333. if (event < 10) {
  1334. resp = '0' + event;
  1335. } else if (event < 11) {
  1336. resp = '*';
  1337. } else if (event < 12) {
  1338. resp = '#';
  1339. } else if (event < 16) {
  1340. resp = 'A' + (event - 12);
  1341. } else if (event < 17) { /* Event 16: Hook flash */
  1342. resp = 'X';
  1343. } else {
  1344. /* Not a supported event */
  1345. ast_debug(1, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
  1346. return;
  1347. }
  1348. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
  1349. if ((rtp->last_end_timestamp != timestamp) || (rtp->resp && rtp->resp != resp)) {
  1350. rtp->resp = resp;
  1351. rtp->dtmf_timeout = 0;
  1352. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)));
  1353. f->len = 0;
  1354. rtp->last_end_timestamp = timestamp;
  1355. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  1356. }
  1357. } else {
  1358. /* The duration parameter measures the complete
  1359. duration of the event (from the beginning) - RFC2833.
  1360. Account for the fact that duration is only 16 bits long
  1361. (about 8 seconds at 8000 Hz) and can wrap is digit
  1362. is hold for too long. */
  1363. unsigned int new_duration = rtp->dtmf_duration;
  1364. unsigned int last_duration = new_duration & 0xFFFF;
  1365. if (last_duration > 64000 && samples < last_duration) {
  1366. new_duration += 0xFFFF + 1;
  1367. }
  1368. new_duration = (new_duration & ~0xFFFF) | samples;
  1369. if (event_end & 0x80) {
  1370. if ((seqno != rtp->last_seqno) && (timestamp > rtp->last_end_timestamp)) {
  1371. rtp->last_end_timestamp = timestamp;
  1372. rtp->dtmf_duration = new_duration;
  1373. rtp->resp = resp;
  1374. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
  1375. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
  1376. rtp->resp = 0;
  1377. rtp->dtmf_duration = rtp->dtmf_timeout = 0;
  1378. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  1379. } else if (rtpdebug) {
  1380. ast_debug(1, "Dropping re-transmitted, duplicate, or out of order DTMF END frame (seqno: %d, ts %d, digit %c)\n",
  1381. seqno, timestamp, resp);
  1382. }
  1383. } else {
  1384. /* Begin/continuation */
  1385. /* The second portion of the seqno check is to not mistakenly
  1386. * stop accepting DTMF if the seqno rolls over beyond
  1387. * 65535.
  1388. */
  1389. if ((rtp->last_seqno > seqno && rtp->last_seqno - seqno < 50)
  1390. || timestamp <= rtp->last_end_timestamp) {
  1391. /* Out of order frame. Processing this can cause us to
  1392. * improperly duplicate incoming DTMF, so just drop
  1393. * this.
  1394. */
  1395. if (rtpdebug) {
  1396. ast_debug(1, "Dropping out of order DTMF frame (seqno %d, ts %d, digit %c)\n",
  1397. seqno, timestamp, resp);
  1398. }
  1399. return;
  1400. }
  1401. if (rtp->resp && rtp->resp != resp) {
  1402. /* Another digit already began. End it */
  1403. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0));
  1404. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
  1405. rtp->resp = 0;
  1406. rtp->dtmf_duration = rtp->dtmf_timeout = 0;
  1407. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  1408. }
  1409. if (rtp->resp) {
  1410. /* Digit continues */
  1411. rtp->dtmf_duration = new_duration;
  1412. } else {
  1413. /* New digit began */
  1414. rtp->resp = resp;
  1415. f = ast_frdup(create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0));
  1416. rtp->dtmf_duration = samples;
  1417. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  1418. }
  1419. rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
  1420. }
  1421. rtp->last_seqno = seqno;
  1422. }
  1423. rtp->dtmfsamples = samples;
  1424. return;
  1425. }
  1426. 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)
  1427. {
  1428. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1429. unsigned int event, flags, power;
  1430. char resp = 0;
  1431. unsigned char seq;
  1432. struct ast_frame *f = NULL;
  1433. if (len < 4) {
  1434. return NULL;
  1435. }
  1436. /* The format of Cisco RTP DTMF packet looks like next:
  1437. +0 - sequence number of DTMF RTP packet (begins from 1,
  1438. wrapped to 0)
  1439. +1 - set of flags
  1440. +1 (bit 0) - flaps by different DTMF digits delimited by audio
  1441. or repeated digit without audio???
  1442. +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
  1443. then falls to 0 at its end)
  1444. +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
  1445. Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
  1446. by each new packet and thus provides some redudancy.
  1447. Sample of Cisco RTP DTMF packet is (all data in hex):
  1448. 19 07 00 02 12 02 20 02
  1449. showing end of DTMF digit '2'.
  1450. The packets
  1451. 27 07 00 02 0A 02 20 02
  1452. 28 06 20 02 00 02 0A 02
  1453. shows begin of new digit '2' with very short pause (20 ms) after
  1454. previous digit '2'. Bit +1.0 flips at begin of new digit.
  1455. Cisco RTP DTMF packets comes as replacement of audio RTP packets
  1456. so its uses the same sequencing and timestamping rules as replaced
  1457. audio packets. Repeat interval of DTMF packets is 20 ms and not rely
  1458. on audio framing parameters. Marker bit isn't used within stream of
  1459. DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
  1460. are not sequential at borders between DTMF and audio streams,
  1461. */
  1462. seq = data[0];
  1463. flags = data[1];
  1464. power = data[2];
  1465. event = data[3] & 0x1f;
  1466. if (rtpdebug)
  1467. 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);
  1468. if (event < 10) {
  1469. resp = '0' + event;
  1470. } else if (event < 11) {
  1471. resp = '*';
  1472. } else if (event < 12) {
  1473. resp = '#';
  1474. } else if (event < 16) {
  1475. resp = 'A' + (event - 12);
  1476. } else if (event < 17) {
  1477. resp = 'X';
  1478. }
  1479. if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
  1480. rtp->resp = resp;
  1481. /* Why we should care on DTMF compensation at reception? */
  1482. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE)) {
  1483. f = create_dtmf_frame(instance, AST_FRAME_DTMF_BEGIN, 0);
  1484. rtp->dtmfsamples = 0;
  1485. }
  1486. } else if ((rtp->resp == resp) && !power) {
  1487. f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_DTMF_COMPENSATE));
  1488. f->samples = rtp->dtmfsamples * (rtp->lastrxformat.id ? (rtp_get_rate(&rtp->lastrxformat) / 1000) : 8);
  1489. rtp->resp = 0;
  1490. } else if (rtp->resp == resp)
  1491. rtp->dtmfsamples += 20 * (rtp->lastrxformat.id ? (rtp_get_rate(&rtp->lastrxformat) / 1000) : 8);
  1492. rtp->dtmf_timeout = 0;
  1493. return f;
  1494. }
  1495. 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)
  1496. {
  1497. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1498. /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
  1499. totally help us out becuase we don't have an engine to keep it going and we are not
  1500. guaranteed to have it every 20ms or anything */
  1501. if (rtpdebug)
  1502. ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", (int) rtp->lastrxformat.id, len);
  1503. if (ast_test_flag(rtp, FLAG_3389_WARNING)) {
  1504. struct ast_sockaddr remote_address = { {0,} };
  1505. ast_rtp_instance_get_remote_address(instance, &remote_address);
  1506. ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client address: %s\n",
  1507. ast_sockaddr_stringify(&remote_address));
  1508. ast_set_flag(rtp, FLAG_3389_WARNING);
  1509. }
  1510. /* Must have at least one byte */
  1511. if (!len)
  1512. return NULL;
  1513. if (len < 24) {
  1514. rtp->f.data.ptr = rtp->rawdata + AST_FRIENDLY_OFFSET;
  1515. rtp->f.datalen = len - 1;
  1516. rtp->f.offset = AST_FRIENDLY_OFFSET;
  1517. memcpy(rtp->f.data.ptr, data + 1, len - 1);
  1518. } else {
  1519. rtp->f.data.ptr = NULL;
  1520. rtp->f.offset = 0;
  1521. rtp->f.datalen = 0;
  1522. }
  1523. rtp->f.frametype = AST_FRAME_CNG;
  1524. rtp->f.subclass.integer = data[0] & 0x7f;
  1525. rtp->f.samples = 0;
  1526. rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
  1527. return &rtp->f;
  1528. }
  1529. static struct ast_frame *ast_rtcp_read(struct ast_rtp_instance *instance)
  1530. {
  1531. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1532. struct ast_sockaddr addr;
  1533. unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
  1534. unsigned int *rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
  1535. int res, packetwords, position = 0;
  1536. struct ast_frame *f = &ast_null_frame;
  1537. /* Read in RTCP data from the socket */
  1538. if ((res = rtcp_recvfrom(instance, rtcpdata + AST_FRIENDLY_OFFSET,
  1539. sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
  1540. 0, &addr)) < 0) {
  1541. ast_assert(errno != EBADF);
  1542. if (errno != EAGAIN) {
  1543. ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n", strerror(errno));
  1544. return NULL;
  1545. }
  1546. return &ast_null_frame;
  1547. }
  1548. packetwords = res / 4;
  1549. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
  1550. /* Send to whoever sent to us */
  1551. if (ast_sockaddr_cmp(&rtp->rtcp->them, &addr)) {
  1552. ast_sockaddr_copy(&rtp->rtcp->them, &addr);
  1553. if (rtpdebug)
  1554. ast_debug(0, "RTCP NAT: Got RTCP from other end. Now sending to address %s\n",
  1555. ast_sockaddr_stringify(&rtp->rtcp->them));
  1556. }
  1557. }
  1558. ast_debug(1, "Got RTCP report of %d bytes\n", res);
  1559. while (position < packetwords) {
  1560. int i, pt, rc;
  1561. unsigned int length, dlsr, lsr, msw, lsw, comp;
  1562. struct timeval now;
  1563. double rttsec, reported_jitter, reported_normdev_jitter_current, normdevrtt_current, reported_lost, reported_normdev_lost_current;
  1564. uint64_t rtt = 0;
  1565. i = position;
  1566. length = ntohl(rtcpheader[i]);
  1567. pt = (length & 0xff0000) >> 16;
  1568. rc = (length & 0x1f000000) >> 24;
  1569. length &= 0xffff;
  1570. if ((i + length) > packetwords) {
  1571. if (rtpdebug)
  1572. ast_debug(1, "RTCP Read too short\n");
  1573. return &ast_null_frame;
  1574. }
  1575. if (rtcp_debug_test_addr(&addr)) {
  1576. ast_verbose("\n\nGot RTCP from %s\n",
  1577. ast_sockaddr_stringify(&addr));
  1578. ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
  1579. ast_verbose("Reception reports: %d\n", rc);
  1580. ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
  1581. }
  1582. i += 2; /* Advance past header and ssrc */
  1583. if (rc == 0 && pt == RTCP_PT_RR) { /* We're receiving a receiver report with no reports, which is ok */
  1584. position += (length + 1);
  1585. continue;
  1586. }
  1587. switch (pt) {
  1588. case RTCP_PT_SR:
  1589. gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
  1590. rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
  1591. rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
  1592. rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
  1593. if (rtcp_debug_test_addr(&addr)) {
  1594. ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
  1595. ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
  1596. ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
  1597. }
  1598. i += 5;
  1599. if (rc < 1)
  1600. break;
  1601. /* Intentional fall through */
  1602. case RTCP_PT_RR:
  1603. /* Don't handle multiple reception reports (rc > 1) yet */
  1604. /* Calculate RTT per RFC */
  1605. gettimeofday(&now, NULL);
  1606. timeval2ntp(now, &msw, &lsw);
  1607. if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
  1608. comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
  1609. lsr = ntohl(rtcpheader[i + 4]);
  1610. dlsr = ntohl(rtcpheader[i + 5]);
  1611. rtt = comp - lsr - dlsr;
  1612. /* Convert end to end delay to usec (keeping the calculation in 64bit space)
  1613. sess->ee_delay = (eedelay * 1000) / 65536; */
  1614. if (rtt < 4294) {
  1615. rtt = (rtt * 1000000) >> 16;
  1616. } else {
  1617. rtt = (rtt * 1000) >> 16;
  1618. rtt *= 1000;
  1619. }
  1620. rtt = rtt / 1000.;
  1621. rttsec = rtt / 1000.;
  1622. rtp->rtcp->rtt = rttsec;
  1623. if (comp - dlsr >= lsr) {
  1624. rtp->rtcp->accumulated_transit += rttsec;
  1625. if (rtp->rtcp->rtt_count == 0)
  1626. rtp->rtcp->minrtt = rttsec;
  1627. if (rtp->rtcp->maxrtt<rttsec)
  1628. rtp->rtcp->maxrtt = rttsec;
  1629. if (rtp->rtcp->minrtt>rttsec)
  1630. rtp->rtcp->minrtt = rttsec;
  1631. normdevrtt_current = normdev_compute(rtp->rtcp->normdevrtt, rttsec, rtp->rtcp->rtt_count);
  1632. rtp->rtcp->stdevrtt = stddev_compute(rtp->rtcp->stdevrtt, rttsec, rtp->rtcp->normdevrtt, normdevrtt_current, rtp->rtcp->rtt_count);
  1633. rtp->rtcp->normdevrtt = normdevrtt_current;
  1634. rtp->rtcp->rtt_count++;
  1635. } else if (rtcp_debug_test_addr(&addr)) {
  1636. ast_verbose("Internal RTCP NTP clock skew detected: "
  1637. "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
  1638. "diff=%d\n",
  1639. lsr, comp, dlsr, dlsr / 65536,
  1640. (dlsr % 65536) * 1000 / 65536,
  1641. dlsr - (comp - lsr));
  1642. }
  1643. }
  1644. rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
  1645. reported_jitter = (double) rtp->rtcp->reported_jitter;
  1646. if (rtp->rtcp->reported_jitter_count == 0)
  1647. rtp->rtcp->reported_minjitter = reported_jitter;
  1648. if (reported_jitter < rtp->rtcp->reported_minjitter)
  1649. rtp->rtcp->reported_minjitter = reported_jitter;
  1650. if (reported_jitter > rtp->rtcp->reported_maxjitter)
  1651. rtp->rtcp->reported_maxjitter = reported_jitter;
  1652. reported_normdev_jitter_current = normdev_compute(rtp->rtcp->reported_normdev_jitter, reported_jitter, rtp->rtcp->reported_jitter_count);
  1653. 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);
  1654. rtp->rtcp->reported_normdev_jitter = reported_normdev_jitter_current;
  1655. rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
  1656. reported_lost = (double) rtp->rtcp->reported_lost;
  1657. /* using same counter as for jitter */
  1658. if (rtp->rtcp->reported_jitter_count == 0)
  1659. rtp->rtcp->reported_minlost = reported_lost;
  1660. if (reported_lost < rtp->rtcp->reported_minlost)
  1661. rtp->rtcp->reported_minlost = reported_lost;
  1662. if (reported_lost > rtp->rtcp->reported_maxlost)
  1663. rtp->rtcp->reported_maxlost = reported_lost;
  1664. reported_normdev_lost_current = normdev_compute(rtp->rtcp->reported_normdev_lost, reported_lost, rtp->rtcp->reported_jitter_count);
  1665. 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);
  1666. rtp->rtcp->reported_normdev_lost = reported_normdev_lost_current;
  1667. rtp->rtcp->reported_jitter_count++;
  1668. if (rtcp_debug_test_addr(&addr)) {
  1669. ast_verbose(" Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
  1670. ast_verbose(" Packets lost so far: %d\n", rtp->rtcp->reported_lost);
  1671. ast_verbose(" Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
  1672. ast_verbose(" Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2])) >> 16);
  1673. ast_verbose(" Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
  1674. ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
  1675. ast_verbose(" DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
  1676. if (rtt)
  1677. ast_verbose(" RTT: %lu(sec)\n", (unsigned long) rtt);
  1678. }
  1679. if (rtt) {
  1680. manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s\r\n"
  1681. "PT: %d(%s)\r\n"
  1682. "ReceptionReports: %d\r\n"
  1683. "SenderSSRC: %u\r\n"
  1684. "FractionLost: %ld\r\n"
  1685. "PacketsLost: %d\r\n"
  1686. "HighestSequence: %ld\r\n"
  1687. "SequenceNumberCycles: %ld\r\n"
  1688. "IAJitter: %u\r\n"
  1689. "LastSR: %lu.%010lu\r\n"
  1690. "DLSR: %4.4f(sec)\r\n"
  1691. "RTT: %llu(sec)\r\n",
  1692. ast_sockaddr_stringify(&addr),
  1693. pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
  1694. rc,
  1695. rtcpheader[i + 1],
  1696. (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
  1697. rtp->rtcp->reported_lost,
  1698. (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
  1699. (long) (ntohl(rtcpheader[i + 2])) >> 16,
  1700. rtp->rtcp->reported_jitter,
  1701. (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
  1702. ntohl(rtcpheader[i + 5])/65536.0,
  1703. (unsigned long long)rtt);
  1704. } else {
  1705. manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s\r\n"
  1706. "PT: %d(%s)\r\n"
  1707. "ReceptionReports: %d\r\n"
  1708. "SenderSSRC: %u\r\n"
  1709. "FractionLost: %ld\r\n"
  1710. "PacketsLost: %d\r\n"
  1711. "HighestSequence: %ld\r\n"
  1712. "SequenceNumberCycles: %ld\r\n"
  1713. "IAJitter: %u\r\n"
  1714. "LastSR: %lu.%010lu\r\n"
  1715. "DLSR: %4.4f(sec)\r\n",
  1716. ast_sockaddr_stringify(&addr),
  1717. pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
  1718. rc,
  1719. rtcpheader[i + 1],
  1720. (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
  1721. rtp->rtcp->reported_lost,
  1722. (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
  1723. (long) (ntohl(rtcpheader[i + 2])) >> 16,
  1724. rtp->rtcp->reported_jitter,
  1725. (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
  1726. ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
  1727. ntohl(rtcpheader[i + 5])/65536.0);
  1728. }
  1729. break;
  1730. case RTCP_PT_FUR:
  1731. if (rtcp_debug_test_addr(&addr))
  1732. ast_verbose("Received an RTCP Fast Update Request\n");
  1733. rtp->f.frametype = AST_FRAME_CONTROL;
  1734. rtp->f.subclass.integer = AST_CONTROL_VIDUPDATE;
  1735. rtp->f.datalen = 0;
  1736. rtp->f.samples = 0;
  1737. rtp->f.mallocd = 0;
  1738. rtp->f.src = "RTP";
  1739. f = &rtp->f;
  1740. break;
  1741. case RTCP_PT_SDES:
  1742. if (rtcp_debug_test_addr(&addr))
  1743. ast_verbose("Received an SDES from %s\n",
  1744. ast_sockaddr_stringify(&rtp->rtcp->them));
  1745. break;
  1746. case RTCP_PT_BYE:
  1747. if (rtcp_debug_test_addr(&addr))
  1748. ast_verbose("Received a BYE from %s\n",
  1749. ast_sockaddr_stringify(&rtp->rtcp->them));
  1750. break;
  1751. default:
  1752. ast_debug(1, "Unknown RTCP packet (pt=%d) received from %s\n",
  1753. pt, ast_sockaddr_stringify(&rtp->rtcp->them));
  1754. break;
  1755. }
  1756. position += (length + 1);
  1757. }
  1758. rtp->rtcp->rtcp_info = 1;
  1759. return f;
  1760. }
  1761. static int bridge_p2p_rtp_write(struct ast_rtp_instance *instance, unsigned int *rtpheader, int len, int hdrlen)
  1762. {
  1763. struct ast_rtp_instance *instance1 = ast_rtp_instance_get_bridged(instance);
  1764. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance), *bridged = ast_rtp_instance_get_data(instance1);
  1765. int res = 0, payload = 0, bridged_payload = 0, mark;
  1766. struct ast_rtp_payload_type payload_type;
  1767. int reconstruct = ntohl(rtpheader[0]);
  1768. struct ast_sockaddr remote_address = { {0,} };
  1769. /* Get fields from packet */
  1770. payload = (reconstruct & 0x7f0000) >> 16;
  1771. mark = (((reconstruct & 0x800000) >> 23) != 0);
  1772. /* Check what the payload value should be */
  1773. payload_type = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), payload);
  1774. /* Otherwise adjust bridged payload to match */
  1775. bridged_payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance1), payload_type.asterisk_format, &payload_type.format, payload_type.rtp_code);
  1776. /* If no codec could be matched between instance and instance1, then somehow things were made incompatible while we were still bridged. Bail. */
  1777. if (bridged_payload < 0) {
  1778. return -1;
  1779. }
  1780. /* 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 */
  1781. if (!(ast_rtp_instance_get_codecs(instance1)->payloads[bridged_payload].rtp_code) &&
  1782. !(ast_rtp_instance_get_codecs(instance1)->payloads[bridged_payload].asterisk_format)) {
  1783. return -1;
  1784. }
  1785. /* If the marker bit has been explicitly set turn it on */
  1786. if (ast_test_flag(rtp, FLAG_NEED_MARKER_BIT)) {
  1787. mark = 1;
  1788. ast_clear_flag(rtp, FLAG_NEED_MARKER_BIT);
  1789. }
  1790. /* Reconstruct part of the packet */
  1791. reconstruct &= 0xFF80FFFF;
  1792. reconstruct |= (bridged_payload << 16);
  1793. reconstruct |= (mark << 23);
  1794. rtpheader[0] = htonl(reconstruct);
  1795. ast_rtp_instance_get_remote_address(instance1, &remote_address);
  1796. if (ast_sockaddr_isnull(&remote_address)) {
  1797. ast_debug(1, "Remote address is null, most likely RTP has been stopped\n");
  1798. return 0;
  1799. }
  1800. /* Send the packet back out */
  1801. res = rtp_sendto(instance1, (void *)rtpheader, len, 0, &remote_address);
  1802. if (res < 0) {
  1803. 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))) {
  1804. ast_log(LOG_WARNING,
  1805. "RTP Transmission error of packet to %s: %s\n",
  1806. ast_sockaddr_stringify(&remote_address),
  1807. strerror(errno));
  1808. } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
  1809. if (option_debug || rtpdebug)
  1810. ast_log(LOG_WARNING,
  1811. "RTP NAT: Can't write RTP to private "
  1812. "address %s, waiting for other end to "
  1813. "send audio...\n",
  1814. ast_sockaddr_stringify(&remote_address));
  1815. ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
  1816. }
  1817. return 0;
  1818. } else if (rtp_debug_test_addr(&remote_address)) {
  1819. ast_verbose("Sent RTP P2P packet to %s (type %-2.2d, len %-6.6u)\n",
  1820. ast_sockaddr_stringify(&remote_address),
  1821. bridged_payload, len - hdrlen);
  1822. }
  1823. return 0;
  1824. }
  1825. static struct ast_frame *ast_rtp_read(struct ast_rtp_instance *instance, int rtcp)
  1826. {
  1827. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  1828. struct ast_sockaddr addr;
  1829. int res, hdrlen = 12, version, payloadtype, padding, mark, ext, cc, prev_seqno;
  1830. unsigned int *rtpheader = (unsigned int*)(rtp->rawdata + AST_FRIENDLY_OFFSET), seqno, ssrc, timestamp;
  1831. struct ast_rtp_payload_type payload;
  1832. struct ast_sockaddr remote_address = { {0,} };
  1833. struct frame_list frames;
  1834. /* If this is actually RTCP let's hop on over and handle it */
  1835. if (rtcp) {
  1836. if (rtp->rtcp) {
  1837. return ast_rtcp_read(instance);
  1838. }
  1839. return &ast_null_frame;
  1840. }
  1841. /* If we are currently sending DTMF to the remote party send a continuation packet */
  1842. if (rtp->sending_digit) {
  1843. ast_rtp_dtmf_continuation(instance);
  1844. }
  1845. /* Actually read in the data from the socket */
  1846. if ((res = rtp_recvfrom(instance, rtp->rawdata + AST_FRIENDLY_OFFSET,
  1847. sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0,
  1848. &addr)) < 0) {
  1849. ast_assert(errno != EBADF);
  1850. if (errno != EAGAIN) {
  1851. ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
  1852. return NULL;
  1853. }
  1854. return &ast_null_frame;
  1855. }
  1856. /* Make sure the data that was read in is actually enough to make up an RTP packet */
  1857. if (res < hdrlen) {
  1858. ast_log(LOG_WARNING, "RTP Read too short\n");
  1859. return &ast_null_frame;
  1860. }
  1861. /* Get fields and verify this is an RTP packet */
  1862. seqno = ntohl(rtpheader[0]);
  1863. ast_rtp_instance_get_remote_address(instance, &remote_address);
  1864. if (!(version = (seqno & 0xC0000000) >> 30)) {
  1865. struct sockaddr_in addr_tmp;
  1866. struct ast_sockaddr addr_v4;
  1867. if (ast_sockaddr_is_ipv4(&addr)) {
  1868. ast_sockaddr_to_sin(&addr, &addr_tmp);
  1869. } else if (ast_sockaddr_ipv4_mapped(&addr, &addr_v4)) {
  1870. ast_debug(1, "Using IPv6 mapped address %s for STUN\n",
  1871. ast_sockaddr_stringify(&addr));
  1872. ast_sockaddr_to_sin(&addr_v4, &addr_tmp);
  1873. } else {
  1874. ast_debug(1, "Cannot do STUN for non IPv4 address %s\n",
  1875. ast_sockaddr_stringify(&addr));
  1876. return &ast_null_frame;
  1877. }
  1878. if ((ast_stun_handle_packet(rtp->s, &addr_tmp, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == AST_STUN_ACCEPT) &&
  1879. ast_sockaddr_isnull(&remote_address)) {
  1880. ast_sockaddr_from_sin(&addr, &addr_tmp);
  1881. ast_rtp_instance_set_remote_address(instance, &addr);
  1882. }
  1883. return &ast_null_frame;
  1884. }
  1885. /* If strict RTP protection is enabled see if we need to learn the remote address or if we need to drop the packet */
  1886. if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
  1887. ast_debug(1, "%p -- start learning mode pass with addr = %s\n", rtp, ast_sockaddr_stringify(&addr));
  1888. /* For now, we always copy the address. */
  1889. ast_sockaddr_copy(&rtp->strict_rtp_address, &addr);
  1890. /* Send the rtp and the seqno from header to rtp_learning_rtp_seq_update to see whether we can exit or not*/
  1891. if (rtp_learning_rtp_seq_update(rtp, ntohl(rtpheader[0]))) {
  1892. ast_debug(1, "%p -- Condition for learning hasn't exited, so reject the frame.\n", rtp);
  1893. return &ast_null_frame;
  1894. }
  1895. ast_debug(1, "%p -- Probation Ended. Set strict_rtp_state to STRICT_RTP_CLOSED with address %s\n", rtp, ast_sockaddr_stringify(&addr));
  1896. rtp->strict_rtp_state = STRICT_RTP_CLOSED;
  1897. } else if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
  1898. if (ast_sockaddr_cmp(&rtp->strict_rtp_address, &addr)) {
  1899. /* Hmm, not the strict addres. Perhaps we're getting audio from the alternate? */
  1900. if (!ast_sockaddr_cmp(&rtp->alt_rtp_address, &addr)) {
  1901. /* ooh, we did! You're now the new expected address, son! */
  1902. ast_sockaddr_copy(&rtp->strict_rtp_address,
  1903. &addr);
  1904. } else {
  1905. const char *real_addr = ast_strdupa(ast_sockaddr_stringify(&addr));
  1906. const char *expected_addr = ast_strdupa(ast_sockaddr_stringify(&rtp->strict_rtp_address));
  1907. ast_debug(1, "Received RTP packet from %s, dropping due to strict RTP protection. Expected it to be from %s\n",
  1908. real_addr, expected_addr);
  1909. return &ast_null_frame;
  1910. }
  1911. }
  1912. }
  1913. /* If symmetric RTP is enabled see if the remote side is not what we expected and change where we are sending audio */
  1914. if (ast_rtp_instance_get_prop(instance, AST_RTP_PROPERTY_NAT)) {
  1915. if (ast_sockaddr_cmp(&remote_address, &addr)) {
  1916. ast_rtp_instance_set_remote_address(instance, &addr);
  1917. ast_sockaddr_copy(&remote_address, &addr);
  1918. if (rtp->rtcp) {
  1919. ast_sockaddr_copy(&rtp->rtcp->them, &addr);
  1920. ast_sockaddr_set_port(&rtp->rtcp->them, ast_sockaddr_port(&addr) + 1);
  1921. }
  1922. rtp->rxseqno = 0;
  1923. ast_set_flag(rtp, FLAG_NAT_ACTIVE);
  1924. if (rtpdebug)
  1925. ast_debug(0, "RTP NAT: Got audio from other end. Now sending to address %s\n",
  1926. ast_sockaddr_stringify(&remote_address));
  1927. }
  1928. }
  1929. /* If we are directly bridged to another instance send the audio directly out */
  1930. if (ast_rtp_instance_get_bridged(instance) && !bridge_p2p_rtp_write(instance, rtpheader, res, hdrlen)) {
  1931. return &ast_null_frame;
  1932. }
  1933. /* If the version is not what we expected by this point then just drop the packet */
  1934. if (version != 2) {
  1935. return &ast_null_frame;
  1936. }
  1937. /* Pull out the various other fields we will need */
  1938. payloadtype = (seqno & 0x7f0000) >> 16;
  1939. padding = seqno & (1 << 29);
  1940. mark = seqno & (1 << 23);
  1941. ext = seqno & (1 << 28);
  1942. cc = (seqno & 0xF000000) >> 24;
  1943. seqno &= 0xffff;
  1944. timestamp = ntohl(rtpheader[1]);
  1945. ssrc = ntohl(rtpheader[2]);
  1946. AST_LIST_HEAD_INIT_NOLOCK(&frames);
  1947. /* Force a marker bit and change SSRC if the SSRC changes */
  1948. if (rtp->rxssrc && rtp->rxssrc != ssrc) {
  1949. struct ast_frame *f, srcupdate = {
  1950. AST_FRAME_CONTROL,
  1951. .subclass.integer = AST_CONTROL_SRCCHANGE,
  1952. };
  1953. if (!mark) {
  1954. if (rtpdebug) {
  1955. ast_debug(1, "Forcing Marker bit, because SSRC has changed\n");
  1956. }
  1957. mark = 1;
  1958. }
  1959. f = ast_frisolate(&srcupdate);
  1960. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  1961. }
  1962. rtp->rxssrc = ssrc;
  1963. /* Remove any padding bytes that may be present */
  1964. if (padding) {
  1965. res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
  1966. }
  1967. /* Skip over any CSRC fields */
  1968. if (cc) {
  1969. hdrlen += cc * 4;
  1970. }
  1971. /* Look for any RTP extensions, currently we do not support any */
  1972. if (ext) {
  1973. hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
  1974. hdrlen += 4;
  1975. if (option_debug) {
  1976. int profile;
  1977. profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
  1978. if (profile == 0x505a)
  1979. ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
  1980. else
  1981. ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
  1982. }
  1983. }
  1984. /* Make sure after we potentially mucked with the header length that it is once again valid */
  1985. if (res < hdrlen) {
  1986. ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d\n", res, hdrlen);
  1987. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  1988. }
  1989. rtp->rxcount++;
  1990. if (rtp->rxcount == 1) {
  1991. rtp->seedrxseqno = seqno;
  1992. }
  1993. /* Do not schedule RR if RTCP isn't run */
  1994. if (rtp->rtcp && !ast_sockaddr_isnull(&rtp->rtcp->them) && rtp->rtcp->schedid < 1) {
  1995. /* Schedule transmission of Receiver Report */
  1996. ao2_ref(instance, +1);
  1997. rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, instance);
  1998. if (rtp->rtcp->schedid < 0) {
  1999. ao2_ref(instance, -1);
  2000. ast_log(LOG_WARNING, "scheduling RTCP transmission failed.\n");
  2001. }
  2002. }
  2003. if ((int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
  2004. rtp->cycles += RTP_SEQ_MOD;
  2005. prev_seqno = rtp->lastrxseqno;
  2006. rtp->lastrxseqno = seqno;
  2007. if (!rtp->themssrc) {
  2008. rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
  2009. }
  2010. if (rtp_debug_test_addr(&addr)) {
  2011. ast_verbose("Got RTP packet from %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  2012. ast_sockaddr_stringify(&addr),
  2013. payloadtype, seqno, timestamp,res - hdrlen);
  2014. }
  2015. payload = ast_rtp_codecs_payload_lookup(ast_rtp_instance_get_codecs(instance), payloadtype);
  2016. /* If the payload is not actually an Asterisk one but a special one pass it off to the respective handler */
  2017. if (!payload.asterisk_format) {
  2018. struct ast_frame *f = NULL;
  2019. if (payload.rtp_code == AST_RTP_DTMF) {
  2020. /* process_dtmf_rfc2833 may need to return multiple frames. We do this
  2021. * by passing the pointer to the frame list to it so that the method
  2022. * can append frames to the list as needed.
  2023. */
  2024. process_dtmf_rfc2833(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark, &frames);
  2025. } else if (payload.rtp_code == AST_RTP_CISCO_DTMF) {
  2026. f = process_dtmf_cisco(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
  2027. } else if (payload.rtp_code == AST_RTP_CN) {
  2028. f = process_cn_rfc3389(instance, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &addr, payloadtype, mark);
  2029. } else {
  2030. ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n",
  2031. payloadtype,
  2032. ast_sockaddr_stringify(&remote_address));
  2033. }
  2034. if (f) {
  2035. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  2036. }
  2037. /* Even if no frame was returned by one of the above methods,
  2038. * we may have a frame to return in our frame list
  2039. */
  2040. if (!AST_LIST_EMPTY(&frames)) {
  2041. return AST_LIST_FIRST(&frames);
  2042. }
  2043. return &ast_null_frame;
  2044. }
  2045. ast_format_copy(&rtp->lastrxformat, &payload.format);
  2046. ast_format_copy(&rtp->f.subclass.format, &payload.format);
  2047. rtp->f.frametype = (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_AUDIO) ? AST_FRAME_VOICE : (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_VIDEO) ? AST_FRAME_VIDEO : AST_FRAME_TEXT;
  2048. rtp->rxseqno = seqno;
  2049. if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
  2050. rtp->dtmf_timeout = 0;
  2051. if (rtp->resp) {
  2052. struct ast_frame *f;
  2053. f = create_dtmf_frame(instance, AST_FRAME_DTMF_END, 0);
  2054. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(&f->subclass.format)), ast_tv(0, 0));
  2055. rtp->resp = 0;
  2056. rtp->dtmf_timeout = rtp->dtmf_duration = 0;
  2057. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  2058. return AST_LIST_FIRST(&frames);
  2059. }
  2060. }
  2061. rtp->lastrxts = timestamp;
  2062. rtp->f.src = "RTP";
  2063. rtp->f.mallocd = 0;
  2064. rtp->f.datalen = res - hdrlen;
  2065. rtp->f.data.ptr = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
  2066. rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
  2067. rtp->f.seqno = seqno;
  2068. if (rtp->f.subclass.format.id == AST_FORMAT_T140 && (int)seqno - (prev_seqno+1) > 0 && (int)seqno - (prev_seqno+1) < 10) {
  2069. unsigned char *data = rtp->f.data.ptr;
  2070. memmove(rtp->f.data.ptr+3, rtp->f.data.ptr, rtp->f.datalen);
  2071. rtp->f.datalen +=3;
  2072. *data++ = 0xEF;
  2073. *data++ = 0xBF;
  2074. *data = 0xBD;
  2075. }
  2076. if (rtp->f.subclass.format.id == AST_FORMAT_T140RED) {
  2077. unsigned char *data = rtp->f.data.ptr;
  2078. unsigned char *header_end;
  2079. int num_generations;
  2080. int header_length;
  2081. int len;
  2082. int diff =(int)seqno - (prev_seqno+1); /* if diff = 0, no drop*/
  2083. int x;
  2084. ast_format_set(&rtp->f.subclass.format, AST_FORMAT_T140, 0);
  2085. header_end = memchr(data, ((*data) & 0x7f), rtp->f.datalen);
  2086. if (header_end == NULL) {
  2087. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  2088. }
  2089. header_end++;
  2090. header_length = header_end - data;
  2091. num_generations = header_length / 4;
  2092. len = header_length;
  2093. if (!diff) {
  2094. for (x = 0; x < num_generations; x++)
  2095. len += data[x * 4 + 3];
  2096. if (!(rtp->f.datalen - len))
  2097. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  2098. rtp->f.data.ptr += len;
  2099. rtp->f.datalen -= len;
  2100. } else if (diff > num_generations && diff < 10) {
  2101. len -= 3;
  2102. rtp->f.data.ptr += len;
  2103. rtp->f.datalen -= len;
  2104. data = rtp->f.data.ptr;
  2105. *data++ = 0xEF;
  2106. *data++ = 0xBF;
  2107. *data = 0xBD;
  2108. } else {
  2109. for ( x = 0; x < num_generations - diff; x++)
  2110. len += data[x * 4 + 3];
  2111. rtp->f.data.ptr += len;
  2112. rtp->f.datalen -= len;
  2113. }
  2114. }
  2115. if (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_AUDIO) {
  2116. rtp->f.samples = ast_codec_get_samples(&rtp->f);
  2117. if (ast_format_is_slinear(&rtp->f.subclass.format)) {
  2118. ast_frame_byteswap_be(&rtp->f);
  2119. }
  2120. calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
  2121. /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
  2122. ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
  2123. rtp->f.ts = timestamp / (rtp_get_rate(&rtp->f.subclass.format) / 1000);
  2124. rtp->f.len = rtp->f.samples / ((ast_format_rate(&rtp->f.subclass.format) / 1000));
  2125. } else if (AST_FORMAT_GET_TYPE(rtp->f.subclass.format.id) == AST_FORMAT_TYPE_VIDEO) {
  2126. /* Video -- samples is # of samples vs. 90000 */
  2127. if (!rtp->lastividtimestamp)
  2128. rtp->lastividtimestamp = timestamp;
  2129. rtp->f.samples = timestamp - rtp->lastividtimestamp;
  2130. rtp->lastividtimestamp = timestamp;
  2131. rtp->f.delivery.tv_sec = 0;
  2132. rtp->f.delivery.tv_usec = 0;
  2133. /* Pass the RTP marker bit as bit */
  2134. if (mark) {
  2135. ast_format_set_video_mark(&rtp->f.subclass.format);
  2136. }
  2137. } else {
  2138. /* TEXT -- samples is # of samples vs. 1000 */
  2139. if (!rtp->lastitexttimestamp)
  2140. rtp->lastitexttimestamp = timestamp;
  2141. rtp->f.samples = timestamp - rtp->lastitexttimestamp;
  2142. rtp->lastitexttimestamp = timestamp;
  2143. rtp->f.delivery.tv_sec = 0;
  2144. rtp->f.delivery.tv_usec = 0;
  2145. }
  2146. AST_LIST_INSERT_TAIL(&frames, &rtp->f, frame_list);
  2147. return AST_LIST_FIRST(&frames);
  2148. }
  2149. static void ast_rtp_prop_set(struct ast_rtp_instance *instance, enum ast_rtp_property property, int value)
  2150. {
  2151. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2152. if (property == AST_RTP_PROPERTY_RTCP) {
  2153. if (value) {
  2154. if (rtp->rtcp) {
  2155. ast_debug(1, "Ignoring duplicate RTCP property on RTP instance '%p'\n", instance);
  2156. return;
  2157. }
  2158. /* Setup RTCP to be activated on the next RTP write */
  2159. if (!(rtp->rtcp = ast_calloc(1, sizeof(*rtp->rtcp)))) {
  2160. return;
  2161. }
  2162. /* Grab the IP address and port we are going to use */
  2163. ast_rtp_instance_get_local_address(instance, &rtp->rtcp->us);
  2164. ast_sockaddr_set_port(&rtp->rtcp->us,
  2165. ast_sockaddr_port(&rtp->rtcp->us) + 1);
  2166. if ((rtp->rtcp->s =
  2167. create_new_socket("RTCP",
  2168. ast_sockaddr_is_ipv4(&rtp->rtcp->us) ?
  2169. AF_INET :
  2170. ast_sockaddr_is_ipv6(&rtp->rtcp->us) ?
  2171. AF_INET6 : -1)) < 0) {
  2172. ast_debug(1, "Failed to create a new socket for RTCP on instance '%p'\n", instance);
  2173. ast_free(rtp->rtcp);
  2174. rtp->rtcp = NULL;
  2175. return;
  2176. }
  2177. /* 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 */
  2178. if (ast_bind(rtp->rtcp->s, &rtp->rtcp->us)) {
  2179. ast_debug(1, "Failed to setup RTCP on RTP instance '%p'\n", instance);
  2180. close(rtp->rtcp->s);
  2181. ast_free(rtp->rtcp);
  2182. rtp->rtcp = NULL;
  2183. return;
  2184. }
  2185. ast_debug(1, "Setup RTCP on RTP instance '%p'\n", instance);
  2186. rtp->rtcp->schedid = -1;
  2187. return;
  2188. } else {
  2189. if (rtp->rtcp) {
  2190. if (rtp->rtcp->schedid > 0) {
  2191. if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
  2192. /* Successfully cancelled scheduler entry. */
  2193. ao2_ref(instance, -1);
  2194. } else {
  2195. /* Unable to cancel scheduler entry */
  2196. ast_debug(1, "Failed to tear down RTCP on RTP instance '%p'\n", instance);
  2197. return;
  2198. }
  2199. rtp->rtcp->schedid = -1;
  2200. }
  2201. close(rtp->rtcp->s);
  2202. ast_free(rtp->rtcp);
  2203. rtp->rtcp = NULL;
  2204. }
  2205. return;
  2206. }
  2207. }
  2208. return;
  2209. }
  2210. static int ast_rtp_fd(struct ast_rtp_instance *instance, int rtcp)
  2211. {
  2212. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2213. return rtcp ? (rtp->rtcp ? rtp->rtcp->s : -1) : rtp->s;
  2214. }
  2215. static void ast_rtp_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
  2216. {
  2217. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2218. if (rtp->rtcp) {
  2219. ast_debug(1, "Setting RTCP address on RTP instance '%p'\n", instance);
  2220. ast_sockaddr_copy(&rtp->rtcp->them, addr);
  2221. if (!ast_sockaddr_isnull(addr)) {
  2222. ast_sockaddr_set_port(&rtp->rtcp->them,
  2223. ast_sockaddr_port(addr) + 1);
  2224. }
  2225. }
  2226. rtp->rxseqno = 0;
  2227. if (strictrtp) {
  2228. rtp->strict_rtp_state = STRICT_RTP_LEARN;
  2229. rtp_learning_seq_init(rtp, rtp->seqno);
  2230. }
  2231. return;
  2232. }
  2233. static void ast_rtp_alt_remote_address_set(struct ast_rtp_instance *instance, struct ast_sockaddr *addr)
  2234. {
  2235. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2236. /* No need to futz with rtp->rtcp here because ast_rtcp_read is already able to adjust if receiving
  2237. * RTCP from an "unexpected" source
  2238. */
  2239. ast_sockaddr_copy(&rtp->alt_rtp_address, addr);
  2240. return;
  2241. }
  2242. /*! \brief Write t140 redundacy frame
  2243. * \param data primary data to be buffered
  2244. */
  2245. static int red_write(const void *data)
  2246. {
  2247. struct ast_rtp_instance *instance = (struct ast_rtp_instance*) data;
  2248. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2249. ast_rtp_write(instance, &rtp->red->t140);
  2250. return 1;
  2251. }
  2252. static int rtp_red_init(struct ast_rtp_instance *instance, int buffer_time, int *payloads, int generations)
  2253. {
  2254. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2255. int x;
  2256. if (!(rtp->red = ast_calloc(1, sizeof(*rtp->red)))) {
  2257. return -1;
  2258. }
  2259. rtp->red->t140.frametype = AST_FRAME_TEXT;
  2260. ast_format_set(&rtp->red->t140.subclass.format, AST_FORMAT_T140RED, 0);
  2261. rtp->red->t140.data.ptr = &rtp->red->buf_data;
  2262. rtp->red->t140.ts = 0;
  2263. rtp->red->t140red = rtp->red->t140;
  2264. rtp->red->t140red.data.ptr = &rtp->red->t140red_data;
  2265. rtp->red->t140red.datalen = 0;
  2266. rtp->red->ti = buffer_time;
  2267. rtp->red->num_gen = generations;
  2268. rtp->red->hdrlen = generations * 4 + 1;
  2269. rtp->red->prev_ts = 0;
  2270. for (x = 0; x < generations; x++) {
  2271. rtp->red->pt[x] = payloads[x];
  2272. rtp->red->pt[x] |= 1 << 7; /* mark redundant generations pt */
  2273. rtp->red->t140red_data[x*4] = rtp->red->pt[x];
  2274. }
  2275. rtp->red->t140red_data[x*4] = rtp->red->pt[x] = payloads[x]; /* primary pt */
  2276. rtp->red->schedid = ast_sched_add(rtp->sched, generations, red_write, instance);
  2277. rtp->red->t140.datalen = 0;
  2278. return 0;
  2279. }
  2280. static int rtp_red_buffer(struct ast_rtp_instance *instance, struct ast_frame *frame)
  2281. {
  2282. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2283. if (frame->datalen > -1) {
  2284. struct rtp_red *red = rtp->red;
  2285. memcpy(&red->buf_data[red->t140.datalen], frame->data.ptr, frame->datalen);
  2286. red->t140.datalen += frame->datalen;
  2287. red->t140.ts = frame->ts;
  2288. }
  2289. return 0;
  2290. }
  2291. static int ast_rtp_local_bridge(struct ast_rtp_instance *instance0, struct ast_rtp_instance *instance1)
  2292. {
  2293. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance0);
  2294. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  2295. return 0;
  2296. }
  2297. static int ast_rtp_get_stat(struct ast_rtp_instance *instance, struct ast_rtp_instance_stats *stats, enum ast_rtp_instance_stat stat)
  2298. {
  2299. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2300. if (!rtp->rtcp) {
  2301. return -1;
  2302. }
  2303. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXCOUNT, -1, stats->txcount, rtp->txcount);
  2304. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RXCOUNT, -1, stats->rxcount, rtp->rxcount);
  2305. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->txploss, rtp->rtcp->reported_lost);
  2306. 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);
  2307. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_maxrxploss, rtp->rtcp->reported_maxlost);
  2308. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_minrxploss, rtp->rtcp->reported_minlost);
  2309. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_normdevrxploss, rtp->rtcp->reported_normdev_lost);
  2310. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->remote_stdevrxploss, rtp->rtcp->reported_stdev_lost);
  2311. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_maxrxploss, rtp->rtcp->maxrxlost);
  2312. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_minrxploss, rtp->rtcp->minrxlost);
  2313. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_normdevrxploss, rtp->rtcp->normdev_rxlost);
  2314. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVRXPLOSS, AST_RTP_INSTANCE_STAT_COMBINED_LOSS, stats->local_stdevrxploss, rtp->rtcp->stdev_rxlost);
  2315. AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_LOSS);
  2316. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_TXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->txjitter, rtp->rxjitter);
  2317. 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);
  2318. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_maxjitter, rtp->rtcp->reported_maxjitter);
  2319. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_minjitter, rtp->rtcp->reported_minjitter);
  2320. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_normdevjitter, rtp->rtcp->reported_normdev_jitter);
  2321. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->remote_stdevjitter, rtp->rtcp->reported_stdev_jitter);
  2322. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MAXJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_maxjitter, rtp->rtcp->maxrxjitter);
  2323. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_MINJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_minjitter, rtp->rtcp->minrxjitter);
  2324. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_NORMDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_normdevjitter, rtp->rtcp->normdev_rxjitter);
  2325. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_STDEVJITTER, AST_RTP_INSTANCE_STAT_COMBINED_JITTER, stats->local_stdevjitter, rtp->rtcp->stdev_rxjitter);
  2326. AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_JITTER);
  2327. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->rtt, rtp->rtcp->rtt);
  2328. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MAX_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->maxrtt, rtp->rtcp->maxrtt);
  2329. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_MIN_RTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->minrtt, rtp->rtcp->minrtt);
  2330. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_NORMDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->normdevrtt, rtp->rtcp->normdevrtt);
  2331. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_STDEVRTT, AST_RTP_INSTANCE_STAT_COMBINED_RTT, stats->stdevrtt, rtp->rtcp->stdevrtt);
  2332. AST_RTP_STAT_TERMINATOR(AST_RTP_INSTANCE_STAT_COMBINED_RTT);
  2333. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_LOCAL_SSRC, -1, stats->local_ssrc, rtp->ssrc);
  2334. AST_RTP_STAT_SET(AST_RTP_INSTANCE_STAT_REMOTE_SSRC, -1, stats->remote_ssrc, rtp->themssrc);
  2335. return 0;
  2336. }
  2337. static int ast_rtp_dtmf_compatible(struct ast_channel *chan0, struct ast_rtp_instance *instance0, struct ast_channel *chan1, struct ast_rtp_instance *instance1)
  2338. {
  2339. /* If both sides are not using the same method of DTMF transmission
  2340. * (ie: one is RFC2833, other is INFO... then we can not do direct media.
  2341. * --------------------------------------------------
  2342. * | DTMF Mode | HAS_DTMF | Accepts Begin Frames |
  2343. * |-----------|------------|-----------------------|
  2344. * | Inband | False | True |
  2345. * | RFC2833 | True | True |
  2346. * | SIP INFO | False | False |
  2347. * --------------------------------------------------
  2348. */
  2349. return (((ast_rtp_instance_get_prop(instance0, AST_RTP_PROPERTY_DTMF) != ast_rtp_instance_get_prop(instance1, AST_RTP_PROPERTY_DTMF)) ||
  2350. (!chan0->tech->send_digit_begin != !chan1->tech->send_digit_begin)) ? 0 : 1);
  2351. }
  2352. static void ast_rtp_stun_request(struct ast_rtp_instance *instance, struct ast_sockaddr *suggestion, const char *username)
  2353. {
  2354. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2355. struct sockaddr_in suggestion_tmp;
  2356. ast_sockaddr_to_sin(suggestion, &suggestion_tmp);
  2357. ast_stun_request(rtp->s, &suggestion_tmp, username, NULL);
  2358. ast_sockaddr_from_sin(suggestion, &suggestion_tmp);
  2359. }
  2360. static void ast_rtp_stop(struct ast_rtp_instance *instance)
  2361. {
  2362. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2363. struct ast_sockaddr addr = { {0,} };
  2364. if (rtp->rtcp && rtp->rtcp->schedid > 0) {
  2365. if (!ast_sched_del(rtp->sched, rtp->rtcp->schedid)) {
  2366. /* successfully cancelled scheduler entry. */
  2367. ao2_ref(instance, -1);
  2368. }
  2369. rtp->rtcp->schedid = -1;
  2370. }
  2371. if (rtp->red) {
  2372. AST_SCHED_DEL(rtp->sched, rtp->red->schedid);
  2373. free(rtp->red);
  2374. rtp->red = NULL;
  2375. }
  2376. ast_rtp_instance_set_remote_address(instance, &addr);
  2377. if (rtp->rtcp) {
  2378. ast_sockaddr_setnull(&rtp->rtcp->them);
  2379. }
  2380. ast_set_flag(rtp, FLAG_NEED_MARKER_BIT);
  2381. }
  2382. static int ast_rtp_qos_set(struct ast_rtp_instance *instance, int tos, int cos, const char *desc)
  2383. {
  2384. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2385. return ast_set_qos(rtp->s, tos, cos, desc);
  2386. }
  2387. /*! \brief generate comfort noice (CNG) */
  2388. static int ast_rtp_sendcng(struct ast_rtp_instance *instance, int level)
  2389. {
  2390. unsigned int *rtpheader;
  2391. int hdrlen = 12;
  2392. int res;
  2393. int payload;
  2394. char data[256];
  2395. struct ast_rtp *rtp = ast_rtp_instance_get_data(instance);
  2396. struct ast_sockaddr remote_address = { {0,} };
  2397. ast_rtp_instance_get_remote_address(instance, &remote_address);
  2398. if (ast_sockaddr_isnull(&remote_address)) {
  2399. return -1;
  2400. }
  2401. payload = ast_rtp_codecs_payload_code(ast_rtp_instance_get_codecs(instance), 0, NULL, AST_RTP_CN);
  2402. level = 127 - (level & 0x7f);
  2403. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  2404. /* Get a pointer to the header */
  2405. rtpheader = (unsigned int *)data;
  2406. rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
  2407. rtpheader[1] = htonl(rtp->lastts);
  2408. rtpheader[2] = htonl(rtp->ssrc);
  2409. data[12] = level;
  2410. res = rtp_sendto(instance, (void *) rtpheader, hdrlen + 1, 0, &remote_address);
  2411. if (res < 0) {
  2412. ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s: %s\n", ast_sockaddr_stringify(&remote_address), strerror(errno));
  2413. } else if (rtp_debug_test_addr(&remote_address)) {
  2414. ast_verbose("Sent Comfort Noise RTP packet to %s (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  2415. ast_sockaddr_stringify(&remote_address),
  2416. AST_RTP_CN, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  2417. }
  2418. return res;
  2419. }
  2420. static char *rtp_do_debug_ip(struct ast_cli_args *a)
  2421. {
  2422. char *arg = ast_strdupa(a->argv[4]);
  2423. char *debughost = NULL;
  2424. char *debugport = NULL;
  2425. if (!ast_sockaddr_parse(&rtpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
  2426. ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
  2427. return CLI_FAILURE;
  2428. }
  2429. rtpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
  2430. ast_cli(a->fd, "RTP Debugging Enabled for address: %s\n",
  2431. ast_sockaddr_stringify(&rtpdebugaddr));
  2432. rtpdebug = 1;
  2433. return CLI_SUCCESS;
  2434. }
  2435. static char *rtcp_do_debug_ip(struct ast_cli_args *a)
  2436. {
  2437. char *arg = ast_strdupa(a->argv[4]);
  2438. char *debughost = NULL;
  2439. char *debugport = NULL;
  2440. if (!ast_sockaddr_parse(&rtcpdebugaddr, arg, 0) || !ast_sockaddr_split_hostport(arg, &debughost, &debugport, 0)) {
  2441. ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
  2442. return CLI_FAILURE;
  2443. }
  2444. rtcpdebugport = (!ast_strlen_zero(debugport) && debugport[0] != '0');
  2445. ast_cli(a->fd, "RTCP Debugging Enabled for address: %s\n",
  2446. ast_sockaddr_stringify(&rtcpdebugaddr));
  2447. rtcpdebug = 1;
  2448. return CLI_SUCCESS;
  2449. }
  2450. static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2451. {
  2452. switch (cmd) {
  2453. case CLI_INIT:
  2454. e->command = "rtp set debug {on|off|ip}";
  2455. e->usage =
  2456. "Usage: rtp set debug {on|off|ip host[:port]}\n"
  2457. " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
  2458. " specified, limit the dumped packets to those to and from\n"
  2459. " the specified 'host' with optional port.\n";
  2460. return NULL;
  2461. case CLI_GENERATE:
  2462. return NULL;
  2463. }
  2464. if (a->argc == e->args) { /* set on or off */
  2465. if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
  2466. rtpdebug = 1;
  2467. memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
  2468. ast_cli(a->fd, "RTP Debugging Enabled\n");
  2469. return CLI_SUCCESS;
  2470. } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
  2471. rtpdebug = 0;
  2472. ast_cli(a->fd, "RTP Debugging Disabled\n");
  2473. return CLI_SUCCESS;
  2474. }
  2475. } else if (a->argc == e->args +1) { /* ip */
  2476. return rtp_do_debug_ip(a);
  2477. }
  2478. return CLI_SHOWUSAGE; /* default, failure */
  2479. }
  2480. static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2481. {
  2482. switch (cmd) {
  2483. case CLI_INIT:
  2484. e->command = "rtcp set debug {on|off|ip}";
  2485. e->usage =
  2486. "Usage: rtcp set debug {on|off|ip host[:port]}\n"
  2487. " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
  2488. " specified, limit the dumped packets to those to and from\n"
  2489. " the specified 'host' with optional port.\n";
  2490. return NULL;
  2491. case CLI_GENERATE:
  2492. return NULL;
  2493. }
  2494. if (a->argc == e->args) { /* set on or off */
  2495. if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
  2496. rtcpdebug = 1;
  2497. memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
  2498. ast_cli(a->fd, "RTCP Debugging Enabled\n");
  2499. return CLI_SUCCESS;
  2500. } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
  2501. rtcpdebug = 0;
  2502. ast_cli(a->fd, "RTCP Debugging Disabled\n");
  2503. return CLI_SUCCESS;
  2504. }
  2505. } else if (a->argc == e->args +1) { /* ip */
  2506. return rtcp_do_debug_ip(a);
  2507. }
  2508. return CLI_SHOWUSAGE; /* default, failure */
  2509. }
  2510. static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  2511. {
  2512. switch (cmd) {
  2513. case CLI_INIT:
  2514. e->command = "rtcp set stats {on|off}";
  2515. e->usage =
  2516. "Usage: rtcp set stats {on|off}\n"
  2517. " Enable/Disable dumping of RTCP stats.\n";
  2518. return NULL;
  2519. case CLI_GENERATE:
  2520. return NULL;
  2521. }
  2522. if (a->argc != e->args)
  2523. return CLI_SHOWUSAGE;
  2524. if (!strncasecmp(a->argv[e->args-1], "on", 2))
  2525. rtcpstats = 1;
  2526. else if (!strncasecmp(a->argv[e->args-1], "off", 3))
  2527. rtcpstats = 0;
  2528. else
  2529. return CLI_SHOWUSAGE;
  2530. ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
  2531. return CLI_SUCCESS;
  2532. }
  2533. static struct ast_cli_entry cli_rtp[] = {
  2534. AST_CLI_DEFINE(handle_cli_rtp_set_debug, "Enable/Disable RTP debugging"),
  2535. AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging"),
  2536. AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats"),
  2537. };
  2538. static int rtp_reload(int reload)
  2539. {
  2540. struct ast_config *cfg;
  2541. const char *s;
  2542. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  2543. cfg = ast_config_load2("rtp.conf", "rtp", config_flags);
  2544. if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
  2545. return 0;
  2546. }
  2547. rtpstart = DEFAULT_RTP_START;
  2548. rtpend = DEFAULT_RTP_END;
  2549. dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  2550. strictrtp = STRICT_RTP_CLOSED;
  2551. learning_min_sequential = DEFAULT_LEARNING_MIN_SEQUENTIAL;
  2552. if (cfg) {
  2553. if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
  2554. rtpstart = atoi(s);
  2555. if (rtpstart < MINIMUM_RTP_PORT)
  2556. rtpstart = MINIMUM_RTP_PORT;
  2557. if (rtpstart > MAXIMUM_RTP_PORT)
  2558. rtpstart = MAXIMUM_RTP_PORT;
  2559. }
  2560. if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
  2561. rtpend = atoi(s);
  2562. if (rtpend < MINIMUM_RTP_PORT)
  2563. rtpend = MINIMUM_RTP_PORT;
  2564. if (rtpend > MAXIMUM_RTP_PORT)
  2565. rtpend = MAXIMUM_RTP_PORT;
  2566. }
  2567. if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
  2568. rtcpinterval = atoi(s);
  2569. if (rtcpinterval == 0)
  2570. rtcpinterval = 0; /* Just so we're clear... it's zero */
  2571. if (rtcpinterval < RTCP_MIN_INTERVALMS)
  2572. rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
  2573. if (rtcpinterval > RTCP_MAX_INTERVALMS)
  2574. rtcpinterval = RTCP_MAX_INTERVALMS;
  2575. }
  2576. if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
  2577. #ifdef SO_NO_CHECK
  2578. nochecksums = ast_false(s) ? 1 : 0;
  2579. #else
  2580. if (ast_false(s))
  2581. ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
  2582. #endif
  2583. }
  2584. if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
  2585. dtmftimeout = atoi(s);
  2586. if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
  2587. ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
  2588. dtmftimeout, DEFAULT_DTMF_TIMEOUT);
  2589. dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  2590. };
  2591. }
  2592. if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
  2593. strictrtp = ast_true(s);
  2594. }
  2595. if ((s = ast_variable_retrieve(cfg, "general", "probation"))) {
  2596. if ((sscanf(s, "%d", &learning_min_sequential) <= 0) || learning_min_sequential <= 0) {
  2597. ast_log(LOG_WARNING, "Value for 'probation' could not be read, using default of '%d' instead\n",
  2598. DEFAULT_LEARNING_MIN_SEQUENTIAL);
  2599. }
  2600. }
  2601. ast_config_destroy(cfg);
  2602. }
  2603. if (rtpstart >= rtpend) {
  2604. ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
  2605. rtpstart = DEFAULT_RTP_START;
  2606. rtpend = DEFAULT_RTP_END;
  2607. }
  2608. ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
  2609. return 0;
  2610. }
  2611. static int reload_module(void)
  2612. {
  2613. rtp_reload(1);
  2614. return 0;
  2615. }
  2616. static int load_module(void)
  2617. {
  2618. if (ast_rtp_engine_register(&asterisk_rtp_engine)) {
  2619. return AST_MODULE_LOAD_DECLINE;
  2620. }
  2621. if (ast_cli_register_multiple(cli_rtp, ARRAY_LEN(cli_rtp))) {
  2622. ast_rtp_engine_unregister(&asterisk_rtp_engine);
  2623. return AST_MODULE_LOAD_DECLINE;
  2624. }
  2625. rtp_reload(0);
  2626. return AST_MODULE_LOAD_SUCCESS;
  2627. }
  2628. static int unload_module(void)
  2629. {
  2630. ast_rtp_engine_unregister(&asterisk_rtp_engine);
  2631. ast_cli_unregister_multiple(cli_rtp, ARRAY_LEN(cli_rtp));
  2632. return 0;
  2633. }
  2634. AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Asterisk RTP Stack",
  2635. .load = load_module,
  2636. .unload = unload_module,
  2637. .reload = reload_module,
  2638. .load_pri = AST_MODPRI_CHANNEL_DEPEND,
  2639. );