rtp.c 145 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433
  1. /*
  2. * Asterisk -- An open source telephony toolkit.
  3. *
  4. * Copyright (C) 1999 - 2006, 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. #include "asterisk.h"
  28. ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
  29. #include <sys/time.h>
  30. #include <signal.h>
  31. #include <fcntl.h>
  32. #include "asterisk/rtp.h"
  33. #include "asterisk/frame.h"
  34. #include "asterisk/channel.h"
  35. #include "asterisk/acl.h"
  36. #include "asterisk/config.h"
  37. #include "asterisk/lock.h"
  38. #include "asterisk/utils.h"
  39. #include "asterisk/netsock.h"
  40. #include "asterisk/cli.h"
  41. #include "asterisk/manager.h"
  42. #include "asterisk/unaligned.h"
  43. #define MAX_TIMESTAMP_SKEW 640
  44. #define RTP_SEQ_MOD (1<<16) /*!< A sequence number can't be more than 16 bits */
  45. #define RTCP_DEFAULT_INTERVALMS 5000 /*!< Default milli-seconds between RTCP reports we send */
  46. #define RTCP_MIN_INTERVALMS 500 /*!< Min milli-seconds between RTCP reports we send */
  47. #define RTCP_MAX_INTERVALMS 60000 /*!< Max milli-seconds between RTCP reports we send */
  48. #define RTCP_PT_FUR 192
  49. #define RTCP_PT_SR 200
  50. #define RTCP_PT_RR 201
  51. #define RTCP_PT_SDES 202
  52. #define RTCP_PT_BYE 203
  53. #define RTCP_PT_APP 204
  54. #define RTP_MTU 1200
  55. #define DEFAULT_DTMF_TIMEOUT (150 * (8000 / 1000)) /*!< samples */
  56. static int dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  57. static int rtpstart = 5000; /*!< First port for RTP sessions (set in rtp.conf) */
  58. static int rtpend = 31000; /*!< Last port for RTP sessions (set in rtp.conf) */
  59. static int rtpdebug; /*!< Are we debugging? */
  60. static int rtcpdebug; /*!< Are we debugging RTCP? */
  61. static int rtcpstats; /*!< Are we debugging RTCP? */
  62. static int rtcpinterval = RTCP_DEFAULT_INTERVALMS; /*!< Time between rtcp reports in millisecs */
  63. static int stundebug; /*!< Are we debugging stun? */
  64. static struct sockaddr_in rtpdebugaddr; /*!< Debug packets to/from this host */
  65. static struct sockaddr_in rtcpdebugaddr; /*!< Debug RTCP packets to/from this host */
  66. #ifdef SO_NO_CHECK
  67. static int nochecksums;
  68. #endif
  69. static int strictrtp;
  70. enum strict_rtp_state {
  71. STRICT_RTP_OPEN = 0, /*! No RTP packets should be dropped, all sources accepted */
  72. STRICT_RTP_LEARN, /*! Accept next packet as source */
  73. STRICT_RTP_CLOSED, /*! Drop all RTP packets not coming from source that was learned */
  74. };
  75. /* Uncomment this to enable more intense native bridging, but note: this is currently buggy */
  76. /* #define P2P_INTENSE */
  77. /*!
  78. * \brief Structure representing a RTP session.
  79. *
  80. * RTP session is defined on page 9 of RFC 3550: "An association among a set of participants communicating with RTP. A participant may be involved in multiple RTP sessions at the same time [...]"
  81. *
  82. */
  83. /*! \brief The value of each payload format mapping: */
  84. struct rtpPayloadType {
  85. int isAstFormat; /*!< whether the following code is an AST_FORMAT */
  86. int code;
  87. };
  88. /*! \brief RTP session description */
  89. struct ast_rtp {
  90. int s;
  91. struct ast_frame f;
  92. unsigned char rawdata[8192 + AST_FRIENDLY_OFFSET];
  93. unsigned int ssrc; /*!< Synchronization source, RFC 3550, page 10. */
  94. unsigned int themssrc; /*!< Their SSRC */
  95. unsigned int rxssrc;
  96. unsigned int lastts;
  97. unsigned int lastrxts;
  98. unsigned int lastividtimestamp;
  99. unsigned int lastovidtimestamp;
  100. unsigned int lastitexttimestamp;
  101. unsigned int lastotexttimestamp;
  102. unsigned int lasteventseqn;
  103. int lastrxseqno; /*!< Last received sequence number */
  104. unsigned short seedrxseqno; /*!< What sequence number did they start with?*/
  105. unsigned int seedrxts; /*!< What RTP timestamp did they start with? */
  106. unsigned int rxcount; /*!< How many packets have we received? */
  107. unsigned int rxoctetcount; /*!< How many octets have we received? should be rxcount *160*/
  108. unsigned int txcount; /*!< How many packets have we sent? */
  109. unsigned int txoctetcount; /*!< How many octets have we sent? (txcount*160)*/
  110. unsigned int cycles; /*!< Shifted count of sequence number cycles */
  111. double rxjitter; /*!< Interarrival jitter at the moment */
  112. double rxtransit; /*!< Relative transit time for previous packet */
  113. int lasttxformat;
  114. int lastrxformat;
  115. int rtptimeout; /*!< RTP timeout time (negative or zero means disabled, negative value means temporarily disabled) */
  116. int rtpholdtimeout; /*!< RTP timeout when on hold (negative or zero means disabled, negative value means temporarily disabled). */
  117. int rtpkeepalive; /*!< Send RTP comfort noice packets for keepalive */
  118. /* DTMF Reception Variables */
  119. char resp;
  120. unsigned int lastevent;
  121. unsigned int dtmf_duration; /*!< Total duration in samples since the digit start event */
  122. unsigned int dtmf_timeout; /*!< When this timestamp is reached we consider END frame lost and forcibly abort digit */
  123. unsigned int dtmfsamples;
  124. /* DTMF Transmission Variables */
  125. unsigned int lastdigitts;
  126. char sending_digit; /*!< boolean - are we sending digits */
  127. char send_digit; /*!< digit we are sending */
  128. int send_payload;
  129. int send_duration;
  130. int nat;
  131. unsigned int flags;
  132. struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
  133. struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
  134. struct sockaddr_in altthem; /*!< Alternate source of remote media */
  135. struct timeval rxcore;
  136. struct timeval txcore;
  137. double drxcore; /*!< The double representation of the first received packet */
  138. struct timeval lastrx; /*!< timeval when we last received a packet */
  139. struct timeval dtmfmute;
  140. struct ast_smoother *smoother;
  141. int *ioid;
  142. unsigned short seqno; /*!< Sequence number, RFC 3550, page 13. */
  143. unsigned short rxseqno;
  144. struct sched_context *sched;
  145. struct io_context *io;
  146. void *data;
  147. ast_rtp_callback callback;
  148. #ifdef P2P_INTENSE
  149. ast_mutex_t bridge_lock;
  150. #endif
  151. struct rtpPayloadType current_RTP_PT[MAX_RTP_PT];
  152. int rtp_lookup_code_cache_isAstFormat; /*!< a cache for the result of rtp_lookup_code(): */
  153. int rtp_lookup_code_cache_code;
  154. int rtp_lookup_code_cache_result;
  155. struct ast_rtcp *rtcp;
  156. struct ast_codec_pref pref;
  157. struct ast_rtp *bridged; /*!< Who we are Packet bridged to */
  158. enum strict_rtp_state strict_rtp_state; /*!< Current state that strict RTP protection is in */
  159. struct sockaddr_in strict_rtp_address; /*!< Remote address information for strict RTP purposes */
  160. int set_marker_bit:1; /*!< Whether to set the marker bit or not */
  161. };
  162. AST_LIST_HEAD_NOLOCK(frame_list, ast_frame);
  163. /* Forward declarations */
  164. static int ast_rtcp_write(const void *data);
  165. static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw);
  166. static int ast_rtcp_write_sr(const void *data);
  167. static int ast_rtcp_write_rr(const void *data);
  168. static unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp);
  169. static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp);
  170. int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit);
  171. #define FLAG_3389_WARNING (1 << 0)
  172. #define FLAG_NAT_ACTIVE (3 << 1)
  173. #define FLAG_NAT_INACTIVE (0 << 1)
  174. #define FLAG_NAT_INACTIVE_NOWARN (1 << 1)
  175. #define FLAG_HAS_DTMF (1 << 3)
  176. #define FLAG_P2P_SENT_MARK (1 << 4)
  177. #define FLAG_P2P_NEED_DTMF (1 << 5)
  178. #define FLAG_CALLBACK_MODE (1 << 6)
  179. #define FLAG_DTMF_COMPENSATE (1 << 7)
  180. #define FLAG_HAS_STUN (1 << 8)
  181. /*!
  182. * \brief Structure defining an RTCP session.
  183. *
  184. * The concept "RTCP session" is not defined in RFC 3550, but since
  185. * this structure is analogous to ast_rtp, which tracks a RTP session,
  186. * it is logical to think of this as a RTCP session.
  187. *
  188. * RTCP packet is defined on page 9 of RFC 3550.
  189. *
  190. */
  191. struct ast_rtcp {
  192. int s; /*!< Socket */
  193. struct sockaddr_in us; /*!< Socket representation of the local endpoint. */
  194. struct sockaddr_in them; /*!< Socket representation of the remote endpoint. */
  195. struct sockaddr_in altthem; /*!< Alternate source for RTCP */
  196. unsigned int soc; /*!< What they told us */
  197. unsigned int spc; /*!< What they told us */
  198. unsigned int themrxlsr; /*!< The middle 32 bits of the NTP timestamp in the last received SR*/
  199. struct timeval rxlsr; /*!< Time when we got their last SR */
  200. struct timeval txlsr; /*!< Time when we sent or last SR*/
  201. unsigned int expected_prior; /*!< no. packets in previous interval */
  202. unsigned int received_prior; /*!< no. packets received in previous interval */
  203. int schedid; /*!< Schedid returned from ast_sched_add() to schedule RTCP-transmissions*/
  204. unsigned int rr_count; /*!< number of RRs we've sent, not including report blocks in SR's */
  205. unsigned int sr_count; /*!< number of SRs we've sent */
  206. unsigned int lastsrtxcount; /*!< Transmit packet count when last SR sent */
  207. double accumulated_transit; /*!< accumulated a-dlsr-lsr */
  208. double rtt; /*!< Last reported rtt */
  209. unsigned int reported_jitter; /*!< The contents of their last jitter entry in the RR */
  210. unsigned int reported_lost; /*!< Reported lost packets in their RR */
  211. char quality[AST_MAX_USER_FIELD];
  212. double maxrxjitter;
  213. double minrxjitter;
  214. double maxrtt;
  215. double minrtt;
  216. int sendfur;
  217. };
  218. /*!
  219. * \brief STUN support code
  220. *
  221. * This code provides some support for doing STUN transactions.
  222. * Eventually it should be moved elsewhere as other protocols
  223. * than RTP can benefit from it - e.g. SIP.
  224. * STUN is described in RFC3489 and it is based on the exchange
  225. * of UDP packets between a client and one or more servers to
  226. * determine the externally visible address (and port) of the client
  227. * once it has gone through the NAT boxes that connect it to the
  228. * outside.
  229. * The simplest request packet is just the header defined in
  230. * struct stun_header, and from the response we may just look at
  231. * one attribute, STUN_MAPPED_ADDRESS, that we find in the response.
  232. * By doing more transactions with different server addresses we
  233. * may determine more about the behaviour of the NAT boxes, of
  234. * course - the details are in the RFC.
  235. *
  236. * All STUN packets start with a simple header made of a type,
  237. * length (excluding the header) and a 16-byte random transaction id.
  238. * Following the header we may have zero or more attributes, each
  239. * structured as a type, length and a value (whose format depends
  240. * on the type, but often contains addresses).
  241. * Of course all fields are in network format.
  242. */
  243. typedef struct { unsigned int id[4]; } __attribute__((packed)) stun_trans_id;
  244. struct stun_header {
  245. unsigned short msgtype;
  246. unsigned short msglen;
  247. stun_trans_id id;
  248. unsigned char ies[0];
  249. } __attribute__((packed));
  250. struct stun_attr {
  251. unsigned short attr;
  252. unsigned short len;
  253. unsigned char value[0];
  254. } __attribute__((packed));
  255. /*
  256. * The format normally used for addresses carried by STUN messages.
  257. */
  258. struct stun_addr {
  259. unsigned char unused;
  260. unsigned char family;
  261. unsigned short port;
  262. unsigned int addr;
  263. } __attribute__((packed));
  264. #define STUN_IGNORE (0)
  265. #define STUN_ACCEPT (1)
  266. /*! \brief STUN message types
  267. * 'BIND' refers to transactions used to determine the externally
  268. * visible addresses. 'SEC' refers to transactions used to establish
  269. * a session key for subsequent requests.
  270. * 'SEC' functionality is not supported here.
  271. */
  272. #define STUN_BINDREQ 0x0001
  273. #define STUN_BINDRESP 0x0101
  274. #define STUN_BINDERR 0x0111
  275. #define STUN_SECREQ 0x0002
  276. #define STUN_SECRESP 0x0102
  277. #define STUN_SECERR 0x0112
  278. /*! \brief Basic attribute types in stun messages.
  279. * Messages can also contain custom attributes (codes above 0x7fff)
  280. */
  281. #define STUN_MAPPED_ADDRESS 0x0001
  282. #define STUN_RESPONSE_ADDRESS 0x0002
  283. #define STUN_CHANGE_REQUEST 0x0003
  284. #define STUN_SOURCE_ADDRESS 0x0004
  285. #define STUN_CHANGED_ADDRESS 0x0005
  286. #define STUN_USERNAME 0x0006
  287. #define STUN_PASSWORD 0x0007
  288. #define STUN_MESSAGE_INTEGRITY 0x0008
  289. #define STUN_ERROR_CODE 0x0009
  290. #define STUN_UNKNOWN_ATTRIBUTES 0x000a
  291. #define STUN_REFLECTED_FROM 0x000b
  292. /*! \brief helper function to print message names */
  293. static const char *stun_msg2str(int msg)
  294. {
  295. switch (msg) {
  296. case STUN_BINDREQ:
  297. return "Binding Request";
  298. case STUN_BINDRESP:
  299. return "Binding Response";
  300. case STUN_BINDERR:
  301. return "Binding Error Response";
  302. case STUN_SECREQ:
  303. return "Shared Secret Request";
  304. case STUN_SECRESP:
  305. return "Shared Secret Response";
  306. case STUN_SECERR:
  307. return "Shared Secret Error Response";
  308. }
  309. return "Non-RFC3489 Message";
  310. }
  311. /*! \brief helper function to print attribute names */
  312. static const char *stun_attr2str(int msg)
  313. {
  314. switch (msg) {
  315. case STUN_MAPPED_ADDRESS:
  316. return "Mapped Address";
  317. case STUN_RESPONSE_ADDRESS:
  318. return "Response Address";
  319. case STUN_CHANGE_REQUEST:
  320. return "Change Request";
  321. case STUN_SOURCE_ADDRESS:
  322. return "Source Address";
  323. case STUN_CHANGED_ADDRESS:
  324. return "Changed Address";
  325. case STUN_USERNAME:
  326. return "Username";
  327. case STUN_PASSWORD:
  328. return "Password";
  329. case STUN_MESSAGE_INTEGRITY:
  330. return "Message Integrity";
  331. case STUN_ERROR_CODE:
  332. return "Error Code";
  333. case STUN_UNKNOWN_ATTRIBUTES:
  334. return "Unknown Attributes";
  335. case STUN_REFLECTED_FROM:
  336. return "Reflected From";
  337. }
  338. return "Non-RFC3489 Attribute";
  339. }
  340. /*! \brief here we store credentials extracted from a message */
  341. struct stun_state {
  342. const char *username;
  343. const char *password;
  344. };
  345. static int stun_process_attr(struct stun_state *state, struct stun_attr *attr)
  346. {
  347. if (stundebug)
  348. ast_verbose("Found STUN Attribute %s (%04x), length %d\n",
  349. stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
  350. switch (ntohs(attr->attr)) {
  351. case STUN_USERNAME:
  352. state->username = (const char *) (attr->value);
  353. break;
  354. case STUN_PASSWORD:
  355. state->password = (const char *) (attr->value);
  356. break;
  357. default:
  358. if (stundebug)
  359. ast_verbose("Ignoring STUN attribute %s (%04x), length %d\n",
  360. stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr), ntohs(attr->len));
  361. }
  362. return 0;
  363. }
  364. /*! \brief append a string to an STUN message */
  365. static void append_attr_string(struct stun_attr **attr, int attrval, const char *s, int *len, int *left)
  366. {
  367. int size = sizeof(**attr) + strlen(s);
  368. if (*left > size) {
  369. (*attr)->attr = htons(attrval);
  370. (*attr)->len = htons(strlen(s));
  371. memcpy((*attr)->value, s, strlen(s));
  372. (*attr) = (struct stun_attr *)((*attr)->value + strlen(s));
  373. *len += size;
  374. *left -= size;
  375. }
  376. }
  377. /*! \brief append an address to an STUN message */
  378. static void append_attr_address(struct stun_attr **attr, int attrval, struct sockaddr_in *sin, int *len, int *left)
  379. {
  380. int size = sizeof(**attr) + 8;
  381. struct stun_addr *addr;
  382. if (*left > size) {
  383. (*attr)->attr = htons(attrval);
  384. (*attr)->len = htons(8);
  385. addr = (struct stun_addr *)((*attr)->value);
  386. addr->unused = 0;
  387. addr->family = 0x01;
  388. addr->port = sin->sin_port;
  389. addr->addr = sin->sin_addr.s_addr;
  390. (*attr) = (struct stun_attr *)((*attr)->value + 8);
  391. *len += size;
  392. *left -= size;
  393. }
  394. }
  395. /*! \brief wrapper to send an STUN message */
  396. static int stun_send(int s, struct sockaddr_in *dst, struct stun_header *resp)
  397. {
  398. return sendto(s, resp, ntohs(resp->msglen) + sizeof(*resp), 0,
  399. (struct sockaddr *)dst, sizeof(*dst));
  400. }
  401. /*! \brief helper function to generate a random request id */
  402. static void stun_req_id(struct stun_header *req)
  403. {
  404. int x;
  405. for (x = 0; x < 4; x++)
  406. req->id.id[x] = ast_random();
  407. }
  408. size_t ast_rtp_alloc_size(void)
  409. {
  410. return sizeof(struct ast_rtp);
  411. }
  412. /*! \brief callback type to be invoked on stun responses. */
  413. typedef int (stun_cb_f)(struct stun_attr *attr, void *arg);
  414. /*! \brief handle an incoming STUN message.
  415. *
  416. * Do some basic sanity checks on packet size and content,
  417. * try to extract a bit of information, and possibly reply.
  418. * At the moment this only processes BIND requests, and returns
  419. * the externally visible address of the request.
  420. * If a callback is specified, invoke it with the attribute.
  421. */
  422. static int stun_handle_packet(int s, struct sockaddr_in *src,
  423. unsigned char *data, size_t len, stun_cb_f *stun_cb, void *arg)
  424. {
  425. struct stun_header *hdr = (struct stun_header *)data;
  426. struct stun_attr *attr;
  427. struct stun_state st;
  428. int ret = STUN_IGNORE;
  429. int x;
  430. /* On entry, 'len' is the length of the udp payload. After the
  431. * initial checks it becomes the size of unprocessed options,
  432. * while 'data' is advanced accordingly.
  433. */
  434. if (len < sizeof(struct stun_header)) {
  435. ast_debug(1, "Runt STUN packet (only %d, wanting at least %d)\n", (int) len, (int) sizeof(struct stun_header));
  436. return -1;
  437. }
  438. len -= sizeof(struct stun_header);
  439. data += sizeof(struct stun_header);
  440. x = ntohs(hdr->msglen); /* len as advertised in the message */
  441. if (stundebug)
  442. ast_verbose("STUN Packet, msg %s (%04x), length: %d\n", stun_msg2str(ntohs(hdr->msgtype)), ntohs(hdr->msgtype), x);
  443. if (x > len) {
  444. ast_debug(1, "Scrambled STUN packet length (got %d, expecting %d)\n", x, (int)len);
  445. } else
  446. len = x;
  447. memset(&st, 0, sizeof(st));
  448. while (len) {
  449. if (len < sizeof(struct stun_attr)) {
  450. ast_debug(1, "Runt Attribute (got %d, expecting %d)\n", (int)len, (int) sizeof(struct stun_attr));
  451. break;
  452. }
  453. attr = (struct stun_attr *)data;
  454. /* compute total attribute length */
  455. x = ntohs(attr->len) + sizeof(struct stun_attr);
  456. if (x > len) {
  457. ast_debug(1, "Inconsistent Attribute (length %d exceeds remaining msg len %d)\n", x, (int)len);
  458. break;
  459. }
  460. if (stun_cb)
  461. stun_cb(attr, arg);
  462. if (stun_process_attr(&st, attr)) {
  463. ast_debug(1, "Failed to handle attribute %s (%04x)\n", stun_attr2str(ntohs(attr->attr)), ntohs(attr->attr));
  464. break;
  465. }
  466. /* Clear attribute id: in case previous entry was a string,
  467. * this will act as the terminator for the string.
  468. */
  469. attr->attr = 0;
  470. data += x;
  471. len -= x;
  472. }
  473. /* Null terminate any string.
  474. * XXX NOTE, we write past the size of the buffer passed by the
  475. * caller, so this is potentially dangerous. The only thing that
  476. * saves us is that usually we read the incoming message in a
  477. * much larger buffer in the struct ast_rtp
  478. */
  479. *data = '\0';
  480. /* Now prepare to generate a reply, which at the moment is done
  481. * only for properly formed (len == 0) STUN_BINDREQ messages.
  482. */
  483. if (len == 0) {
  484. unsigned char respdata[1024];
  485. struct stun_header *resp = (struct stun_header *)respdata;
  486. int resplen = 0; /* len excluding header */
  487. int respleft = sizeof(respdata) - sizeof(struct stun_header);
  488. resp->id = hdr->id;
  489. resp->msgtype = 0;
  490. resp->msglen = 0;
  491. attr = (struct stun_attr *)resp->ies;
  492. switch (ntohs(hdr->msgtype)) {
  493. case STUN_BINDREQ:
  494. if (stundebug)
  495. ast_verbose("STUN Bind Request, username: %s\n",
  496. st.username ? st.username : "<none>");
  497. if (st.username)
  498. append_attr_string(&attr, STUN_USERNAME, st.username, &resplen, &respleft);
  499. append_attr_address(&attr, STUN_MAPPED_ADDRESS, src, &resplen, &respleft);
  500. resp->msglen = htons(resplen);
  501. resp->msgtype = htons(STUN_BINDRESP);
  502. stun_send(s, src, resp);
  503. ret = STUN_ACCEPT;
  504. break;
  505. default:
  506. if (stundebug)
  507. ast_verbose("Dunno what to do with STUN message %04x (%s)\n", ntohs(hdr->msgtype), stun_msg2str(ntohs(hdr->msgtype)));
  508. }
  509. }
  510. return ret;
  511. }
  512. /*! \brief Extract the STUN_MAPPED_ADDRESS from the stun response.
  513. * This is used as a callback for stun_handle_response
  514. * when called from ast_stun_request.
  515. */
  516. static int stun_get_mapped(struct stun_attr *attr, void *arg)
  517. {
  518. struct stun_addr *addr = (struct stun_addr *)(attr + 1);
  519. struct sockaddr_in *sa = (struct sockaddr_in *)arg;
  520. if (ntohs(attr->attr) != STUN_MAPPED_ADDRESS || ntohs(attr->len) != 8)
  521. return 1; /* not us. */
  522. sa->sin_port = addr->port;
  523. sa->sin_addr.s_addr = addr->addr;
  524. return 0;
  525. }
  526. /*! \brief Generic STUN request
  527. * Send a generic stun request to the server specified,
  528. * possibly waiting for a reply and filling the 'reply' field with
  529. * the externally visible address. Note that in this case the request
  530. * will be blocking.
  531. * (Note, the interface may change slightly in the future).
  532. *
  533. * \param s the socket used to send the request
  534. * \param dst the address of the STUN server
  535. * \param username if non null, add the username in the request
  536. * \param answer if non null, the function waits for a response and
  537. * puts here the externally visible address.
  538. * \return 0 on success, other values on error.
  539. */
  540. int ast_stun_request(int s, struct sockaddr_in *dst,
  541. const char *username, struct sockaddr_in *answer)
  542. {
  543. struct stun_header *req;
  544. unsigned char reqdata[1024];
  545. int reqlen, reqleft;
  546. struct stun_attr *attr;
  547. int res = 0;
  548. int retry;
  549. req = (struct stun_header *)reqdata;
  550. stun_req_id(req);
  551. reqlen = 0;
  552. reqleft = sizeof(reqdata) - sizeof(struct stun_header);
  553. req->msgtype = 0;
  554. req->msglen = 0;
  555. attr = (struct stun_attr *)req->ies;
  556. if (username)
  557. append_attr_string(&attr, STUN_USERNAME, username, &reqlen, &reqleft);
  558. req->msglen = htons(reqlen);
  559. req->msgtype = htons(STUN_BINDREQ);
  560. for (retry = 0; retry < 3; retry++) { /* XXX make retries configurable */
  561. /* send request, possibly wait for reply */
  562. unsigned char reply_buf[1024];
  563. fd_set rfds;
  564. struct timeval to = { 3, 0 }; /* timeout, make it configurable */
  565. struct sockaddr_in src;
  566. socklen_t srclen;
  567. res = stun_send(s, dst, req);
  568. if (res < 0) {
  569. ast_log(LOG_WARNING, "ast_stun_request send #%d failed error %d, retry\n",
  570. retry, res);
  571. continue;
  572. }
  573. if (answer == NULL)
  574. break;
  575. FD_ZERO(&rfds);
  576. FD_SET(s, &rfds);
  577. res = ast_select(s + 1, &rfds, NULL, NULL, &to);
  578. if (res <= 0) /* timeout or error */
  579. continue;
  580. memset(&src, '\0', sizeof(src));
  581. srclen = sizeof(src);
  582. /* XXX pass -1 in the size, because stun_handle_packet might
  583. * write past the end of the buffer.
  584. */
  585. res = recvfrom(s, reply_buf, sizeof(reply_buf) - 1,
  586. 0, (struct sockaddr *)&src, &srclen);
  587. if (res < 0) {
  588. ast_log(LOG_WARNING, "ast_stun_request recvfrom #%d failed error %d, retry\n",
  589. retry, res);
  590. continue;
  591. }
  592. memset(answer, '\0', sizeof(struct sockaddr_in));
  593. stun_handle_packet(s, &src, reply_buf, res,
  594. stun_get_mapped, answer);
  595. res = 0; /* signal regular exit */
  596. break;
  597. }
  598. return res;
  599. }
  600. /*! \brief send a STUN BIND request to the given destination.
  601. * Optionally, add a username if specified.
  602. */
  603. void ast_rtp_stun_request(struct ast_rtp *rtp, struct sockaddr_in *suggestion, const char *username)
  604. {
  605. ast_stun_request(rtp->s, suggestion, username, NULL);
  606. }
  607. /*! \brief List of current sessions */
  608. static AST_RWLIST_HEAD_STATIC(protos, ast_rtp_protocol);
  609. static void timeval2ntp(struct timeval tv, unsigned int *msw, unsigned int *lsw)
  610. {
  611. unsigned int sec, usec, frac;
  612. sec = tv.tv_sec + 2208988800u; /* Sec between 1900 and 1970 */
  613. usec = tv.tv_usec;
  614. frac = (usec << 12) + (usec << 8) - ((usec * 3650) >> 6);
  615. *msw = sec;
  616. *lsw = frac;
  617. }
  618. int ast_rtp_fd(struct ast_rtp *rtp)
  619. {
  620. return rtp->s;
  621. }
  622. int ast_rtcp_fd(struct ast_rtp *rtp)
  623. {
  624. if (rtp->rtcp)
  625. return rtp->rtcp->s;
  626. return -1;
  627. }
  628. static int rtp_get_rate(int subclass)
  629. {
  630. return (subclass == AST_FORMAT_G722) ? 8000 : ast_format_rate(subclass);
  631. }
  632. unsigned int ast_rtcp_calc_interval(struct ast_rtp *rtp)
  633. {
  634. unsigned int interval;
  635. /*! \todo XXX Do a more reasonable calculation on this one
  636. * Look in RFC 3550 Section A.7 for an example*/
  637. interval = rtcpinterval;
  638. return interval;
  639. }
  640. /* \brief Put RTP timeout timers on hold during another transaction, like T.38 */
  641. void ast_rtp_set_rtptimers_onhold(struct ast_rtp *rtp)
  642. {
  643. rtp->rtptimeout = (-1) * rtp->rtptimeout;
  644. rtp->rtpholdtimeout = (-1) * rtp->rtpholdtimeout;
  645. }
  646. /*! \brief Set rtp timeout */
  647. void ast_rtp_set_rtptimeout(struct ast_rtp *rtp, int timeout)
  648. {
  649. rtp->rtptimeout = timeout;
  650. }
  651. /*! \brief Set rtp hold timeout */
  652. void ast_rtp_set_rtpholdtimeout(struct ast_rtp *rtp, int timeout)
  653. {
  654. rtp->rtpholdtimeout = timeout;
  655. }
  656. /*! \brief set RTP keepalive interval */
  657. void ast_rtp_set_rtpkeepalive(struct ast_rtp *rtp, int period)
  658. {
  659. rtp->rtpkeepalive = period;
  660. }
  661. /*! \brief Get rtp timeout */
  662. int ast_rtp_get_rtptimeout(struct ast_rtp *rtp)
  663. {
  664. if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
  665. return 0;
  666. return rtp->rtptimeout;
  667. }
  668. /*! \brief Get rtp hold timeout */
  669. int ast_rtp_get_rtpholdtimeout(struct ast_rtp *rtp)
  670. {
  671. if (rtp->rtptimeout < 0) /* We're not checking, but remembering the setting (during T.38 transmission) */
  672. return 0;
  673. return rtp->rtpholdtimeout;
  674. }
  675. /*! \brief Get RTP keepalive interval */
  676. int ast_rtp_get_rtpkeepalive(struct ast_rtp *rtp)
  677. {
  678. return rtp->rtpkeepalive;
  679. }
  680. void ast_rtp_set_data(struct ast_rtp *rtp, void *data)
  681. {
  682. rtp->data = data;
  683. }
  684. void ast_rtp_set_callback(struct ast_rtp *rtp, ast_rtp_callback callback)
  685. {
  686. rtp->callback = callback;
  687. }
  688. void ast_rtp_setnat(struct ast_rtp *rtp, int nat)
  689. {
  690. rtp->nat = nat;
  691. }
  692. int ast_rtp_getnat(struct ast_rtp *rtp)
  693. {
  694. return ast_test_flag(rtp, FLAG_NAT_ACTIVE);
  695. }
  696. void ast_rtp_setdtmf(struct ast_rtp *rtp, int dtmf)
  697. {
  698. ast_set2_flag(rtp, dtmf ? 1 : 0, FLAG_HAS_DTMF);
  699. }
  700. void ast_rtp_setdtmfcompensate(struct ast_rtp *rtp, int compensate)
  701. {
  702. ast_set2_flag(rtp, compensate ? 1 : 0, FLAG_DTMF_COMPENSATE);
  703. }
  704. void ast_rtp_setstun(struct ast_rtp *rtp, int stun_enable)
  705. {
  706. ast_set2_flag(rtp, stun_enable ? 1 : 0, FLAG_HAS_STUN);
  707. }
  708. static void rtp_bridge_lock(struct ast_rtp *rtp)
  709. {
  710. #ifdef P2P_INTENSE
  711. ast_mutex_lock(&rtp->bridge_lock);
  712. #endif
  713. return;
  714. }
  715. static void rtp_bridge_unlock(struct ast_rtp *rtp)
  716. {
  717. #ifdef P2P_INTENSE
  718. ast_mutex_unlock(&rtp->bridge_lock);
  719. #endif
  720. return;
  721. }
  722. static struct ast_frame *create_dtmf_frame(struct ast_rtp *rtp, enum ast_frame_type type)
  723. {
  724. if (((ast_test_flag(rtp, FLAG_DTMF_COMPENSATE) && type == AST_FRAME_DTMF_END) ||
  725. (type == AST_FRAME_DTMF_BEGIN)) && ast_tvcmp(ast_tvnow(), rtp->dtmfmute) < 0) {
  726. ast_debug(1, "Ignore potential DTMF echo from '%s'\n", ast_inet_ntoa(rtp->them.sin_addr));
  727. rtp->resp = 0;
  728. rtp->dtmfsamples = 0;
  729. return &ast_null_frame;
  730. }
  731. ast_debug(1, "Sending dtmf: %d (%c), at %s\n", rtp->resp, rtp->resp, ast_inet_ntoa(rtp->them.sin_addr));
  732. if (rtp->resp == 'X') {
  733. rtp->f.frametype = AST_FRAME_CONTROL;
  734. rtp->f.subclass = AST_CONTROL_FLASH;
  735. } else {
  736. rtp->f.frametype = type;
  737. rtp->f.subclass = rtp->resp;
  738. }
  739. rtp->f.datalen = 0;
  740. rtp->f.samples = 0;
  741. rtp->f.mallocd = 0;
  742. rtp->f.src = "RTP";
  743. AST_LIST_NEXT(&rtp->f, frame_list) = NULL;
  744. return &rtp->f;
  745. }
  746. static inline int rtp_debug_test_addr(struct sockaddr_in *addr)
  747. {
  748. if (rtpdebug == 0)
  749. return 0;
  750. if (rtpdebugaddr.sin_addr.s_addr) {
  751. if (((ntohs(rtpdebugaddr.sin_port) != 0)
  752. && (rtpdebugaddr.sin_port != addr->sin_port))
  753. || (rtpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
  754. return 0;
  755. }
  756. return 1;
  757. }
  758. static inline int rtcp_debug_test_addr(struct sockaddr_in *addr)
  759. {
  760. if (rtcpdebug == 0)
  761. return 0;
  762. if (rtcpdebugaddr.sin_addr.s_addr) {
  763. if (((ntohs(rtcpdebugaddr.sin_port) != 0)
  764. && (rtcpdebugaddr.sin_port != addr->sin_port))
  765. || (rtcpdebugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
  766. return 0;
  767. }
  768. return 1;
  769. }
  770. static struct ast_frame *process_cisco_dtmf(struct ast_rtp *rtp, unsigned char *data, int len)
  771. {
  772. unsigned int event;
  773. char resp = 0;
  774. struct ast_frame *f = NULL;
  775. unsigned char seq;
  776. unsigned int flags;
  777. unsigned int power;
  778. /* We should have at least 4 bytes in RTP data */
  779. if (len < 4)
  780. return f;
  781. /* The format of Cisco RTP DTMF packet looks like next:
  782. +0 - sequence number of DTMF RTP packet (begins from 1,
  783. wrapped to 0)
  784. +1 - set of flags
  785. +1 (bit 0) - flaps by different DTMF digits delimited by audio
  786. or repeated digit without audio???
  787. +2 (+4,+6,...) - power level? (rises from 0 to 32 at begin of tone
  788. then falls to 0 at its end)
  789. +3 (+5,+7,...) - detected DTMF digit (0..9,*,#,A-D,...)
  790. Repeated DTMF information (bytes 4/5, 6/7) is history shifted right
  791. by each new packet and thus provides some redudancy.
  792. Sample of Cisco RTP DTMF packet is (all data in hex):
  793. 19 07 00 02 12 02 20 02
  794. showing end of DTMF digit '2'.
  795. The packets
  796. 27 07 00 02 0A 02 20 02
  797. 28 06 20 02 00 02 0A 02
  798. shows begin of new digit '2' with very short pause (20 ms) after
  799. previous digit '2'. Bit +1.0 flips at begin of new digit.
  800. Cisco RTP DTMF packets comes as replacement of audio RTP packets
  801. so its uses the same sequencing and timestamping rules as replaced
  802. audio packets. Repeat interval of DTMF packets is 20 ms and not rely
  803. on audio framing parameters. Marker bit isn't used within stream of
  804. DTMFs nor audio stream coming immediately after DTMF stream. Timestamps
  805. are not sequential at borders between DTMF and audio streams,
  806. */
  807. seq = data[0];
  808. flags = data[1];
  809. power = data[2];
  810. event = data[3] & 0x1f;
  811. if (option_debug > 2 || rtpdebug)
  812. 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);
  813. if (event < 10) {
  814. resp = '0' + event;
  815. } else if (event < 11) {
  816. resp = '*';
  817. } else if (event < 12) {
  818. resp = '#';
  819. } else if (event < 16) {
  820. resp = 'A' + (event - 12);
  821. } else if (event < 17) {
  822. resp = 'X';
  823. }
  824. if ((!rtp->resp && power) || (rtp->resp && (rtp->resp != resp))) {
  825. rtp->resp = resp;
  826. /* Why we should care on DTMF compensation at reception? */
  827. if (!ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
  828. f = create_dtmf_frame(rtp, AST_FRAME_DTMF_BEGIN);
  829. rtp->dtmfsamples = 0;
  830. }
  831. } else if ((rtp->resp == resp) && !power) {
  832. f = create_dtmf_frame(rtp, AST_FRAME_DTMF_END);
  833. f->samples = rtp->dtmfsamples * (rtp_get_rate(f->subclass) / 1000);
  834. rtp->resp = 0;
  835. } else if (rtp->resp == resp)
  836. rtp->dtmfsamples += 20 * (rtp_get_rate(f->subclass) / 1000);
  837. rtp->dtmf_timeout = dtmftimeout;
  838. return f;
  839. }
  840. /*!
  841. * \brief Process RTP DTMF and events according to RFC 2833.
  842. *
  843. * RFC 2833 is "RTP Payload for DTMF Digits, Telephony Tones and Telephony Signals".
  844. *
  845. * \param rtp
  846. * \param data
  847. * \param len
  848. * \param seqno
  849. * \param timestamp
  850. * \returns
  851. */
  852. static void process_rfc2833(struct ast_rtp *rtp, unsigned char *data, int len, unsigned int seqno, unsigned int timestamp, struct frame_list *frames)
  853. {
  854. unsigned int event;
  855. unsigned int event_end;
  856. unsigned int samples;
  857. char resp = 0;
  858. struct ast_frame *f = NULL;
  859. /* Figure out event, event end, and samples */
  860. event = ntohl(*((unsigned int *)(data)));
  861. event >>= 24;
  862. event_end = ntohl(*((unsigned int *)(data)));
  863. event_end <<= 8;
  864. event_end >>= 24;
  865. samples = ntohl(*((unsigned int *)(data)));
  866. samples &= 0xFFFF;
  867. /* Print out debug if turned on */
  868. if (rtpdebug || option_debug > 2)
  869. ast_debug(0, "- RTP 2833 Event: %08x (len = %d)\n", event, len);
  870. /* Figure out what digit was pressed */
  871. if (event < 10) {
  872. resp = '0' + event;
  873. } else if (event < 11) {
  874. resp = '*';
  875. } else if (event < 12) {
  876. resp = '#';
  877. } else if (event < 16) {
  878. resp = 'A' + (event - 12);
  879. } else if (event < 17) { /* Event 16: Hook flash */
  880. resp = 'X';
  881. } else {
  882. /* Not a supported event */
  883. ast_log(LOG_DEBUG, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
  884. return;
  885. }
  886. if (ast_test_flag(rtp, FLAG_DTMF_COMPENSATE)) {
  887. if ((rtp->lastevent != timestamp) || (rtp->resp && rtp->resp != resp)) {
  888. rtp->resp = resp;
  889. rtp->dtmf_timeout = 0;
  890. f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_END));
  891. f->len = 0;
  892. rtp->lastevent = timestamp;
  893. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  894. }
  895. } else {
  896. /* The duration parameter measures the complete
  897. duration of the event (from the beginning) - RFC2833.
  898. Account for the fact that duration is only 16 bits long
  899. (about 8 seconds at 8000 Hz) and can wrap is digit
  900. is hold for too long. */
  901. unsigned int new_duration = rtp->dtmf_duration;
  902. unsigned int last_duration = new_duration & 0xFFFF;
  903. if (last_duration > 64000 && samples < last_duration)
  904. new_duration += 0xFFFF + 1;
  905. new_duration = (new_duration & ~0xFFFF) | samples;
  906. if (rtp->lastevent > seqno) {
  907. /* Out of order frame. Processing this can cause us to
  908. * improperly duplicate incoming DTMF, so just drop
  909. * this.
  910. */
  911. return;
  912. }
  913. if (event_end & 0x80) {
  914. /* End event */
  915. if ((rtp->lastevent != seqno) && rtp->resp) {
  916. rtp->dtmf_duration = new_duration;
  917. f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_END));
  918. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
  919. rtp->resp = 0;
  920. rtp->dtmf_duration = rtp->dtmf_timeout = 0;
  921. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  922. }
  923. } else {
  924. /* Begin/continuation */
  925. if (rtp->resp && rtp->resp != resp) {
  926. /* Another digit already began. End it */
  927. f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_END));
  928. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
  929. rtp->resp = 0;
  930. rtp->dtmf_duration = rtp->dtmf_timeout = 0;
  931. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  932. }
  933. if (rtp->resp) {
  934. /* Digit continues */
  935. rtp->dtmf_duration = new_duration;
  936. } else {
  937. /* New digit began */
  938. rtp->resp = resp;
  939. f = ast_frdup(create_dtmf_frame(rtp, AST_FRAME_DTMF_BEGIN));
  940. rtp->dtmf_duration = samples;
  941. AST_LIST_INSERT_TAIL(frames, f, frame_list);
  942. }
  943. rtp->dtmf_timeout = timestamp + rtp->dtmf_duration + dtmftimeout;
  944. }
  945. rtp->lastevent = seqno;
  946. }
  947. rtp->dtmfsamples = samples;
  948. }
  949. /*!
  950. * \brief Process Comfort Noise RTP.
  951. *
  952. * This is incomplete at the moment.
  953. *
  954. */
  955. static struct ast_frame *process_rfc3389(struct ast_rtp *rtp, unsigned char *data, int len)
  956. {
  957. struct ast_frame *f = NULL;
  958. /* Convert comfort noise into audio with various codecs. Unfortunately this doesn't
  959. totally help us out becuase we don't have an engine to keep it going and we are not
  960. guaranteed to have it every 20ms or anything */
  961. if (rtpdebug)
  962. ast_debug(0, "- RTP 3389 Comfort noise event: Level %d (len = %d)\n", rtp->lastrxformat, len);
  963. if (!(ast_test_flag(rtp, FLAG_3389_WARNING))) {
  964. ast_log(LOG_NOTICE, "Comfort noise support incomplete in Asterisk (RFC 3389). Please turn off on client if possible. Client IP: %s\n",
  965. ast_inet_ntoa(rtp->them.sin_addr));
  966. ast_set_flag(rtp, FLAG_3389_WARNING);
  967. }
  968. /* Must have at least one byte */
  969. if (!len)
  970. return NULL;
  971. if (len < 24) {
  972. rtp->f.data = rtp->rawdata + AST_FRIENDLY_OFFSET;
  973. rtp->f.datalen = len - 1;
  974. rtp->f.offset = AST_FRIENDLY_OFFSET;
  975. memcpy(rtp->f.data, data + 1, len - 1);
  976. } else {
  977. rtp->f.data = NULL;
  978. rtp->f.offset = 0;
  979. rtp->f.datalen = 0;
  980. }
  981. rtp->f.frametype = AST_FRAME_CNG;
  982. rtp->f.subclass = data[0] & 0x7f;
  983. rtp->f.samples = 0;
  984. rtp->f.delivery.tv_usec = rtp->f.delivery.tv_sec = 0;
  985. f = &rtp->f;
  986. return f;
  987. }
  988. static int rtpread(int *id, int fd, short events, void *cbdata)
  989. {
  990. struct ast_rtp *rtp = cbdata;
  991. struct ast_frame *f;
  992. f = ast_rtp_read(rtp);
  993. if (f) {
  994. if (rtp->callback)
  995. rtp->callback(rtp, f, rtp->data);
  996. }
  997. return 1;
  998. }
  999. struct ast_frame *ast_rtcp_read(struct ast_rtp *rtp)
  1000. {
  1001. socklen_t len;
  1002. int position, i, packetwords;
  1003. int res;
  1004. struct sockaddr_in sin;
  1005. unsigned int rtcpdata[8192 + AST_FRIENDLY_OFFSET];
  1006. unsigned int *rtcpheader;
  1007. int pt;
  1008. struct timeval now;
  1009. unsigned int length;
  1010. int rc;
  1011. double rttsec;
  1012. uint64_t rtt = 0;
  1013. unsigned int dlsr;
  1014. unsigned int lsr;
  1015. unsigned int msw;
  1016. unsigned int lsw;
  1017. unsigned int comp;
  1018. struct ast_frame *f = &ast_null_frame;
  1019. if (!rtp || !rtp->rtcp)
  1020. return &ast_null_frame;
  1021. len = sizeof(sin);
  1022. res = recvfrom(rtp->rtcp->s, rtcpdata + AST_FRIENDLY_OFFSET, sizeof(rtcpdata) - sizeof(unsigned int) * AST_FRIENDLY_OFFSET,
  1023. 0, (struct sockaddr *)&sin, &len);
  1024. rtcpheader = (unsigned int *)(rtcpdata + AST_FRIENDLY_OFFSET);
  1025. if (res < 0) {
  1026. ast_assert(errno != EBADF);
  1027. if (errno != EAGAIN) {
  1028. ast_log(LOG_WARNING, "RTCP Read error: %s. Hanging up.\n", strerror(errno));
  1029. return NULL;
  1030. }
  1031. return &ast_null_frame;
  1032. }
  1033. packetwords = res / 4;
  1034. if (rtp->nat) {
  1035. /* Send to whoever sent to us */
  1036. if (((rtp->rtcp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
  1037. (rtp->rtcp->them.sin_port != sin.sin_port)) &&
  1038. ((rtp->rtcp->altthem.sin_addr.s_addr != sin.sin_addr.s_addr) ||
  1039. (rtp->rtcp->altthem.sin_port != sin.sin_port))) {
  1040. memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
  1041. if (option_debug || rtpdebug)
  1042. ast_debug(0, "RTCP NAT: Got RTCP from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
  1043. }
  1044. }
  1045. ast_debug(1, "Got RTCP report of %d bytes\n", res);
  1046. /* Process a compound packet */
  1047. position = 0;
  1048. while (position < packetwords) {
  1049. i = position;
  1050. length = ntohl(rtcpheader[i]);
  1051. pt = (length & 0xff0000) >> 16;
  1052. rc = (length & 0x1f000000) >> 24;
  1053. length &= 0xffff;
  1054. if ((i + length) > packetwords) {
  1055. if (option_debug || rtpdebug)
  1056. ast_log(LOG_DEBUG, "RTCP Read too short\n");
  1057. return &ast_null_frame;
  1058. }
  1059. if (rtcp_debug_test_addr(&sin)) {
  1060. ast_verbose("\n\nGot RTCP from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
  1061. ast_verbose("PT: %d(%s)\n", pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown");
  1062. ast_verbose("Reception reports: %d\n", rc);
  1063. ast_verbose("SSRC of sender: %u\n", rtcpheader[i + 1]);
  1064. }
  1065. i += 2; /* Advance past header and ssrc */
  1066. switch (pt) {
  1067. case RTCP_PT_SR:
  1068. gettimeofday(&rtp->rtcp->rxlsr,NULL); /* To be able to populate the dlsr */
  1069. rtp->rtcp->spc = ntohl(rtcpheader[i+3]);
  1070. rtp->rtcp->soc = ntohl(rtcpheader[i + 4]);
  1071. rtp->rtcp->themrxlsr = ((ntohl(rtcpheader[i]) & 0x0000ffff) << 16) | ((ntohl(rtcpheader[i + 1]) & 0xffff0000) >> 16); /* Going to LSR in RR*/
  1072. if (rtcp_debug_test_addr(&sin)) {
  1073. ast_verbose("NTP timestamp: %lu.%010lu\n", (unsigned long) ntohl(rtcpheader[i]), (unsigned long) ntohl(rtcpheader[i + 1]) * 4096);
  1074. ast_verbose("RTP timestamp: %lu\n", (unsigned long) ntohl(rtcpheader[i + 2]));
  1075. ast_verbose("SPC: %lu\tSOC: %lu\n", (unsigned long) ntohl(rtcpheader[i + 3]), (unsigned long) ntohl(rtcpheader[i + 4]));
  1076. }
  1077. i += 5;
  1078. if (rc < 1)
  1079. break;
  1080. /* Intentional fall through */
  1081. case RTCP_PT_RR:
  1082. /* Don't handle multiple reception reports (rc > 1) yet */
  1083. /* Calculate RTT per RFC */
  1084. gettimeofday(&now, NULL);
  1085. timeval2ntp(now, &msw, &lsw);
  1086. if (ntohl(rtcpheader[i + 4]) && ntohl(rtcpheader[i + 5])) { /* We must have the LSR && DLSR */
  1087. comp = ((msw & 0xffff) << 16) | ((lsw & 0xffff0000) >> 16);
  1088. lsr = ntohl(rtcpheader[i + 4]);
  1089. dlsr = ntohl(rtcpheader[i + 5]);
  1090. rtt = comp - lsr - dlsr;
  1091. /* Convert end to end delay to usec (keeping the calculation in 64bit space)
  1092. sess->ee_delay = (eedelay * 1000) / 65536; */
  1093. if (rtt < 4294) {
  1094. rtt = (rtt * 1000000) >> 16;
  1095. } else {
  1096. rtt = (rtt * 1000) >> 16;
  1097. rtt *= 1000;
  1098. }
  1099. rtt = rtt / 1000.;
  1100. rttsec = rtt / 1000.;
  1101. if (comp - dlsr >= lsr) {
  1102. rtp->rtcp->accumulated_transit += rttsec;
  1103. rtp->rtcp->rtt = rttsec;
  1104. if (rtp->rtcp->maxrtt<rttsec)
  1105. rtp->rtcp->maxrtt = rttsec;
  1106. if (rtp->rtcp->minrtt>rttsec)
  1107. rtp->rtcp->minrtt = rttsec;
  1108. } else if (rtcp_debug_test_addr(&sin)) {
  1109. ast_verbose("Internal RTCP NTP clock skew detected: "
  1110. "lsr=%u, now=%u, dlsr=%u (%d:%03dms), "
  1111. "diff=%d\n",
  1112. lsr, comp, dlsr, dlsr / 65536,
  1113. (dlsr % 65536) * 1000 / 65536,
  1114. dlsr - (comp - lsr));
  1115. }
  1116. }
  1117. rtp->rtcp->reported_jitter = ntohl(rtcpheader[i + 3]);
  1118. rtp->rtcp->reported_lost = ntohl(rtcpheader[i + 1]) & 0xffffff;
  1119. if (rtcp_debug_test_addr(&sin)) {
  1120. ast_verbose(" Fraction lost: %ld\n", (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24));
  1121. ast_verbose(" Packets lost so far: %d\n", rtp->rtcp->reported_lost);
  1122. ast_verbose(" Highest sequence number: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff));
  1123. ast_verbose(" Sequence number cycles: %ld\n", (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16);
  1124. ast_verbose(" Interarrival jitter: %u\n", rtp->rtcp->reported_jitter);
  1125. ast_verbose(" Last SR(our NTP): %lu.%010lu\n",(unsigned long) ntohl(rtcpheader[i + 4]) >> 16,((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096);
  1126. ast_verbose(" DLSR: %4.4f (sec)\n",ntohl(rtcpheader[i + 5])/65536.0);
  1127. if (rtt)
  1128. ast_verbose(" RTT: %lu(sec)\n", (unsigned long) rtt);
  1129. }
  1130. if (rtt) {
  1131. manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s:%d\r\n"
  1132. "PT: %d(%s)\r\n"
  1133. "ReceptionReports: %d\r\n"
  1134. "SenderSSRC: %u\r\n"
  1135. "FractionLost: %ld\r\n"
  1136. "PacketsLost: %d\r\n"
  1137. "HighestSequence: %ld\r\n"
  1138. "SequenceNumberCycles: %ld\r\n"
  1139. "IAJitter: %u\r\n"
  1140. "LastSR: %lu.%010lu\r\n"
  1141. "DLSR: %4.4f(sec)\r\n"
  1142. "RTT: %llu(sec)\r\n",
  1143. ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
  1144. pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
  1145. rc,
  1146. rtcpheader[i + 1],
  1147. (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
  1148. rtp->rtcp->reported_lost,
  1149. (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
  1150. (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
  1151. rtp->rtcp->reported_jitter,
  1152. (unsigned long) ntohl(rtcpheader[i + 4]) >> 16, ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
  1153. ntohl(rtcpheader[i + 5])/65536.0,
  1154. (unsigned long long)rtt);
  1155. } else {
  1156. manager_event(EVENT_FLAG_REPORTING, "RTCPReceived", "From: %s:%d\r\n"
  1157. "PT: %d(%s)\r\n"
  1158. "ReceptionReports: %d\r\n"
  1159. "SenderSSRC: %u\r\n"
  1160. "FractionLost: %ld\r\n"
  1161. "PacketsLost: %d\r\n"
  1162. "HighestSequence: %ld\r\n"
  1163. "SequenceNumberCycles: %ld\r\n"
  1164. "IAJitter: %u\r\n"
  1165. "LastSR: %lu.%010lu\r\n"
  1166. "DLSR: %4.4f(sec)\r\n",
  1167. ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port),
  1168. pt, (pt == 200) ? "Sender Report" : (pt == 201) ? "Receiver Report" : (pt == 192) ? "H.261 FUR" : "Unknown",
  1169. rc,
  1170. rtcpheader[i + 1],
  1171. (((long) ntohl(rtcpheader[i + 1]) & 0xff000000) >> 24),
  1172. rtp->rtcp->reported_lost,
  1173. (long) (ntohl(rtcpheader[i + 2]) & 0xffff),
  1174. (long) (ntohl(rtcpheader[i + 2]) & 0xffff) >> 16,
  1175. rtp->rtcp->reported_jitter,
  1176. (unsigned long) ntohl(rtcpheader[i + 4]) >> 16,
  1177. ((unsigned long) ntohl(rtcpheader[i + 4]) << 16) * 4096,
  1178. ntohl(rtcpheader[i + 5])/65536.0);
  1179. }
  1180. break;
  1181. case RTCP_PT_FUR:
  1182. if (rtcp_debug_test_addr(&sin))
  1183. ast_verbose("Received an RTCP Fast Update Request\n");
  1184. rtp->f.frametype = AST_FRAME_CONTROL;
  1185. rtp->f.subclass = AST_CONTROL_VIDUPDATE;
  1186. rtp->f.datalen = 0;
  1187. rtp->f.samples = 0;
  1188. rtp->f.mallocd = 0;
  1189. rtp->f.src = "RTP";
  1190. f = &rtp->f;
  1191. break;
  1192. case RTCP_PT_SDES:
  1193. if (rtcp_debug_test_addr(&sin))
  1194. ast_verbose("Received an SDES from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
  1195. break;
  1196. case RTCP_PT_BYE:
  1197. if (rtcp_debug_test_addr(&sin))
  1198. ast_verbose("Received a BYE from %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
  1199. break;
  1200. default:
  1201. ast_debug(1, "Unknown RTCP packet (pt=%d) received from %s:%d\n", pt, ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
  1202. break;
  1203. }
  1204. position += (length + 1);
  1205. }
  1206. return f;
  1207. }
  1208. static void calc_rxstamp(struct timeval *tv, struct ast_rtp *rtp, unsigned int timestamp, int mark)
  1209. {
  1210. struct timeval now;
  1211. struct timeval tmp;
  1212. double transit;
  1213. double current_time;
  1214. double d;
  1215. double dtv;
  1216. double prog;
  1217. int rate = rtp_get_rate(rtp->f.subclass);
  1218. if ((!rtp->rxcore.tv_sec && !rtp->rxcore.tv_usec) || mark) {
  1219. gettimeofday(&rtp->rxcore, NULL);
  1220. rtp->drxcore = (double) rtp->rxcore.tv_sec + (double) rtp->rxcore.tv_usec / 1000000;
  1221. /* map timestamp to a real time */
  1222. rtp->seedrxts = timestamp; /* Their RTP timestamp started with this */
  1223. tmp = ast_samp2tv(timestamp, rate);
  1224. rtp->rxcore = ast_tvsub(rtp->rxcore, tmp);
  1225. /* Round to 0.1ms for nice, pretty timestamps */
  1226. rtp->rxcore.tv_usec -= rtp->rxcore.tv_usec % 100;
  1227. }
  1228. gettimeofday(&now,NULL);
  1229. /* rxcore is the mapping between the RTP timestamp and _our_ real time from gettimeofday() */
  1230. tmp = ast_samp2tv(timestamp, rate);
  1231. *tv = ast_tvadd(rtp->rxcore, tmp);
  1232. prog = (double)((timestamp-rtp->seedrxts)/(float)(rate));
  1233. dtv = (double)rtp->drxcore + (double)(prog);
  1234. current_time = (double)now.tv_sec + (double)now.tv_usec/1000000;
  1235. transit = current_time - dtv;
  1236. d = transit - rtp->rxtransit;
  1237. rtp->rxtransit = transit;
  1238. if (d<0)
  1239. d=-d;
  1240. rtp->rxjitter += (1./16.) * (d - rtp->rxjitter);
  1241. if (rtp->rtcp && rtp->rxjitter > rtp->rtcp->maxrxjitter)
  1242. rtp->rtcp->maxrxjitter = rtp->rxjitter;
  1243. if (rtp->rtcp && rtp->rxjitter < rtp->rtcp->minrxjitter)
  1244. rtp->rtcp->minrxjitter = rtp->rxjitter;
  1245. }
  1246. /*! \brief Perform a Packet2Packet RTP write */
  1247. static int bridge_p2p_rtp_write(struct ast_rtp *rtp, struct ast_rtp *bridged, unsigned int *rtpheader, int len, int hdrlen)
  1248. {
  1249. int res = 0, payload = 0, bridged_payload = 0, mark;
  1250. struct rtpPayloadType rtpPT;
  1251. int reconstruct = ntohl(rtpheader[0]);
  1252. /* Get fields from packet */
  1253. payload = (reconstruct & 0x7f0000) >> 16;
  1254. mark = (((reconstruct & 0x800000) >> 23) != 0);
  1255. /* Check what the payload value should be */
  1256. rtpPT = ast_rtp_lookup_pt(rtp, payload);
  1257. /* If the payload is DTMF, and we are listening for DTMF - then feed it into the core */
  1258. if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) && !rtpPT.isAstFormat && rtpPT.code == AST_RTP_DTMF)
  1259. return -1;
  1260. /* Otherwise adjust bridged payload to match */
  1261. bridged_payload = ast_rtp_lookup_code(bridged, rtpPT.isAstFormat, rtpPT.code);
  1262. /* 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 */
  1263. if (!bridged->current_RTP_PT[bridged_payload].code)
  1264. return -1;
  1265. /* If the mark bit has not been sent yet... do it now */
  1266. if (!ast_test_flag(rtp, FLAG_P2P_SENT_MARK)) {
  1267. mark = 1;
  1268. ast_set_flag(rtp, FLAG_P2P_SENT_MARK);
  1269. }
  1270. /* Reconstruct part of the packet */
  1271. reconstruct &= 0xFF80FFFF;
  1272. reconstruct |= (bridged_payload << 16);
  1273. reconstruct |= (mark << 23);
  1274. rtpheader[0] = htonl(reconstruct);
  1275. /* Send the packet back out */
  1276. res = sendto(bridged->s, (void *)rtpheader, len, 0, (struct sockaddr *)&bridged->them, sizeof(bridged->them));
  1277. if (res < 0) {
  1278. if (!bridged->nat || (bridged->nat && (ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
  1279. ast_debug(1, "RTP Transmission error of packet to %s:%d: %s\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), strerror(errno));
  1280. } else if (((ast_test_flag(bridged, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(bridged, FLAG_NAT_INACTIVE_NOWARN)) {
  1281. if (option_debug || rtpdebug)
  1282. ast_debug(0, "RTP NAT: Can't write RTP to private address %s:%d, waiting for other end to send audio...\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port));
  1283. ast_set_flag(bridged, FLAG_NAT_INACTIVE_NOWARN);
  1284. }
  1285. return 0;
  1286. } else if (rtp_debug_test_addr(&bridged->them))
  1287. ast_verbose("Sent RTP P2P packet to %s:%u (type %-2.2d, len %-6.6u)\n", ast_inet_ntoa(bridged->them.sin_addr), ntohs(bridged->them.sin_port), bridged_payload, len - hdrlen);
  1288. return 0;
  1289. }
  1290. struct ast_frame *ast_rtp_read(struct ast_rtp *rtp)
  1291. {
  1292. int res;
  1293. struct sockaddr_in sin;
  1294. socklen_t len;
  1295. unsigned int seqno;
  1296. int version;
  1297. int payloadtype;
  1298. int hdrlen = 12;
  1299. int padding;
  1300. int mark;
  1301. int ext;
  1302. int cc;
  1303. unsigned int ssrc;
  1304. unsigned int timestamp;
  1305. unsigned int *rtpheader;
  1306. struct rtpPayloadType rtpPT;
  1307. struct ast_rtp *bridged = NULL;
  1308. struct frame_list frames;
  1309. /* If time is up, kill it */
  1310. if (rtp->sending_digit)
  1311. ast_rtp_senddigit_continuation(rtp);
  1312. len = sizeof(sin);
  1313. /* Cache where the header will go */
  1314. res = recvfrom(rtp->s, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET,
  1315. 0, (struct sockaddr *)&sin, &len);
  1316. /* If strict RTP protection is enabled see if we need to learn this address or if the packet should be dropped */
  1317. if (rtp->strict_rtp_state == STRICT_RTP_LEARN) {
  1318. /* Copy over address that this packet was received on */
  1319. memcpy(&rtp->strict_rtp_address, &sin, sizeof(rtp->strict_rtp_address));
  1320. /* Now move over to actually protecting the RTP port */
  1321. rtp->strict_rtp_state = STRICT_RTP_CLOSED;
  1322. ast_debug(1, "Learned remote address is %s:%d for strict RTP purposes, now protecting the port.\n", ast_inet_ntoa(rtp->strict_rtp_address.sin_addr), ntohs(rtp->strict_rtp_address.sin_port));
  1323. } else if (rtp->strict_rtp_state == STRICT_RTP_CLOSED) {
  1324. /* If the address we previously learned doesn't match the address this packet came in on simply drop it */
  1325. if ((rtp->strict_rtp_address.sin_addr.s_addr != sin.sin_addr.s_addr) || (rtp->strict_rtp_address.sin_port != sin.sin_port)) {
  1326. ast_debug(1, "Received RTP packet from %s:%d, dropping due to strict RTP protection. Expected it to be from %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), ast_inet_ntoa(rtp->strict_rtp_address.sin_addr), ntohs(rtp->strict_rtp_address.sin_port));
  1327. return &ast_null_frame;
  1328. }
  1329. }
  1330. rtpheader = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
  1331. if (res < 0) {
  1332. ast_assert(errno != EBADF);
  1333. if (errno != EAGAIN) {
  1334. ast_log(LOG_WARNING, "RTP Read error: %s. Hanging up.\n", strerror(errno));
  1335. return NULL;
  1336. }
  1337. return &ast_null_frame;
  1338. }
  1339. if (res < hdrlen) {
  1340. ast_log(LOG_WARNING, "RTP Read too short\n");
  1341. return &ast_null_frame;
  1342. }
  1343. /* Get fields */
  1344. seqno = ntohl(rtpheader[0]);
  1345. /* Check RTP version */
  1346. version = (seqno & 0xC0000000) >> 30;
  1347. if (!version) {
  1348. /* If the two high bits are 0, this might be a
  1349. * STUN message, so process it. stun_handle_packet()
  1350. * answers to requests, and it returns STUN_ACCEPT
  1351. * if the request is valid.
  1352. */
  1353. if ((stun_handle_packet(rtp->s, &sin, rtp->rawdata + AST_FRIENDLY_OFFSET, res, NULL, NULL) == STUN_ACCEPT) &&
  1354. (!rtp->them.sin_port && !rtp->them.sin_addr.s_addr)) {
  1355. memcpy(&rtp->them, &sin, sizeof(rtp->them));
  1356. }
  1357. return &ast_null_frame;
  1358. }
  1359. #if 0 /* Allow to receive RTP stream with closed transmission path */
  1360. /* If we don't have the other side's address, then ignore this */
  1361. if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
  1362. return &ast_null_frame;
  1363. #endif
  1364. /* Send to whoever send to us if NAT is turned on */
  1365. if (rtp->nat) {
  1366. if (((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
  1367. (rtp->them.sin_port != sin.sin_port)) &&
  1368. ((rtp->altthem.sin_addr.s_addr != sin.sin_addr.s_addr) ||
  1369. (rtp->altthem.sin_port != sin.sin_port))) {
  1370. rtp->them = sin;
  1371. if (rtp->rtcp) {
  1372. memcpy(&rtp->rtcp->them, &sin, sizeof(rtp->rtcp->them));
  1373. rtp->rtcp->them.sin_port = htons(ntohs(rtp->them.sin_port)+1);
  1374. }
  1375. rtp->rxseqno = 0;
  1376. ast_set_flag(rtp, FLAG_NAT_ACTIVE);
  1377. if (option_debug || rtpdebug)
  1378. ast_debug(0, "RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
  1379. }
  1380. }
  1381. /* If we are bridged to another RTP stream, send direct */
  1382. if ((bridged = ast_rtp_get_bridged(rtp)) && !bridge_p2p_rtp_write(rtp, bridged, rtpheader, res, hdrlen))
  1383. return &ast_null_frame;
  1384. if (version != 2)
  1385. return &ast_null_frame;
  1386. payloadtype = (seqno & 0x7f0000) >> 16;
  1387. padding = seqno & (1 << 29);
  1388. mark = seqno & (1 << 23);
  1389. ext = seqno & (1 << 28);
  1390. cc = (seqno & 0xF000000) >> 24;
  1391. seqno &= 0xffff;
  1392. timestamp = ntohl(rtpheader[1]);
  1393. ssrc = ntohl(rtpheader[2]);
  1394. AST_LIST_HEAD_INIT_NOLOCK(&frames);
  1395. /* Force a marker bit and change SSRC if the SSRC changes */
  1396. if (rtp->rxssrc && rtp->rxssrc != ssrc) {
  1397. struct ast_frame *f, srcupdate = {
  1398. AST_FRAME_CONTROL,
  1399. .subclass = AST_CONTROL_SRCCHANGE,
  1400. };
  1401. if (!mark) {
  1402. if (option_debug || rtpdebug) {
  1403. ast_debug(0, "Forcing Marker bit, because SSRC has changed\n");
  1404. }
  1405. mark = 1;
  1406. }
  1407. f = ast_frisolate(&srcupdate);
  1408. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  1409. }
  1410. rtp->rxssrc = ssrc;
  1411. if (padding) {
  1412. /* Remove padding bytes */
  1413. res -= rtp->rawdata[AST_FRIENDLY_OFFSET + res - 1];
  1414. }
  1415. if (cc) {
  1416. /* CSRC fields present */
  1417. hdrlen += cc*4;
  1418. }
  1419. if (ext) {
  1420. /* RTP Extension present */
  1421. hdrlen += (ntohl(rtpheader[hdrlen/4]) & 0xffff) << 2;
  1422. hdrlen += 4;
  1423. if (option_debug) {
  1424. int profile;
  1425. profile = (ntohl(rtpheader[3]) & 0xffff0000) >> 16;
  1426. if (profile == 0x505a)
  1427. ast_debug(1, "Found Zfone extension in RTP stream - zrtp - not supported.\n");
  1428. else
  1429. ast_debug(1, "Found unknown RTP Extensions %x\n", profile);
  1430. }
  1431. }
  1432. if (res < hdrlen) {
  1433. ast_log(LOG_WARNING, "RTP Read too short (%d, expecting %d)\n", res, hdrlen);
  1434. return AST_LIST_FIRST(&frames) ? AST_LIST_FIRST(&frames) : &ast_null_frame;
  1435. }
  1436. rtp->rxcount++; /* Only count reasonably valid packets, this'll make the rtcp stats more accurate */
  1437. if (rtp->rxcount==1) {
  1438. /* This is the first RTP packet successfully received from source */
  1439. rtp->seedrxseqno = seqno;
  1440. }
  1441. /* Do not schedule RR if RTCP isn't run */
  1442. if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
  1443. /* Schedule transmission of Receiver Report */
  1444. rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
  1445. }
  1446. if ( (int)rtp->lastrxseqno - (int)seqno > 100) /* if so it would indicate that the sender cycled; allow for misordering */
  1447. rtp->cycles += RTP_SEQ_MOD;
  1448. rtp->lastrxseqno = seqno;
  1449. if (!rtp->themssrc)
  1450. rtp->themssrc = ntohl(rtpheader[2]); /* Record their SSRC to put in future RR */
  1451. if (rtp_debug_test_addr(&sin))
  1452. ast_verbose("Got RTP packet from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  1453. ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp,res - hdrlen);
  1454. rtpPT = ast_rtp_lookup_pt(rtp, payloadtype);
  1455. if (!rtpPT.isAstFormat) {
  1456. struct ast_frame *f = NULL;
  1457. /* This is special in-band data that's not one of our codecs */
  1458. if (rtpPT.code == AST_RTP_DTMF) {
  1459. /* It's special -- rfc2833 process it */
  1460. if (rtp_debug_test_addr(&sin)) {
  1461. unsigned char *data;
  1462. unsigned int event;
  1463. unsigned int event_end;
  1464. unsigned int duration;
  1465. data = rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen;
  1466. event = ntohl(*((unsigned int *)(data)));
  1467. event >>= 24;
  1468. event_end = ntohl(*((unsigned int *)(data)));
  1469. event_end <<= 8;
  1470. event_end >>= 24;
  1471. duration = ntohl(*((unsigned int *)(data)));
  1472. duration &= 0xFFFF;
  1473. ast_verbose("Got RTP RFC2833 from %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), payloadtype, seqno, timestamp, res - hdrlen, (mark?1:0), event, ((event_end & 0x80)?1:0), duration);
  1474. }
  1475. /* process_rfc2833 may need to return multiple frames. We do this
  1476. * by passing the pointer to the frame list to it so that the method
  1477. * can append frames to the list as needed
  1478. */
  1479. process_rfc2833(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen, seqno, timestamp, &frames);
  1480. } else if (rtpPT.code == AST_RTP_CISCO_DTMF) {
  1481. /* It's really special -- process it the Cisco way */
  1482. if (rtp->lastevent <= seqno || (rtp->lastevent >= 65530 && seqno <= 6)) {
  1483. f = process_cisco_dtmf(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
  1484. rtp->lastevent = seqno;
  1485. }
  1486. } else if (rtpPT.code == AST_RTP_CN) {
  1487. /* Comfort Noise */
  1488. f = process_rfc3389(rtp, rtp->rawdata + AST_FRIENDLY_OFFSET + hdrlen, res - hdrlen);
  1489. } else {
  1490. ast_log(LOG_NOTICE, "Unknown RTP codec %d received from '%s'\n", payloadtype, ast_inet_ntoa(rtp->them.sin_addr));
  1491. }
  1492. if (f) {
  1493. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  1494. }
  1495. /* Even if no frame was returned by one of the above methods,
  1496. * we may have a frame to return in our frame list
  1497. */
  1498. if (!AST_LIST_EMPTY(&frames)) {
  1499. return AST_LIST_FIRST(&frames);
  1500. }
  1501. return &ast_null_frame;
  1502. }
  1503. rtp->lastrxformat = rtp->f.subclass = rtpPT.code;
  1504. rtp->f.frametype = (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) ? AST_FRAME_VOICE : (rtp->f.subclass & AST_FORMAT_VIDEO_MASK) ? AST_FRAME_VIDEO : AST_FRAME_TEXT;
  1505. rtp->rxseqno = seqno;
  1506. if (rtp->dtmf_timeout && rtp->dtmf_timeout < timestamp) {
  1507. rtp->dtmf_timeout = 0;
  1508. if (rtp->resp) {
  1509. struct ast_frame *f;
  1510. f = create_dtmf_frame(rtp, AST_FRAME_DTMF_END);
  1511. f->len = ast_tvdiff_ms(ast_samp2tv(rtp->dtmf_duration, rtp_get_rate(f->subclass)), ast_tv(0, 0));
  1512. rtp->resp = 0;
  1513. rtp->dtmf_timeout = rtp->dtmf_duration = 0;
  1514. AST_LIST_INSERT_TAIL(&frames, f, frame_list);
  1515. return AST_LIST_FIRST(&frames);
  1516. }
  1517. }
  1518. /* Record received timestamp as last received now */
  1519. rtp->lastrxts = timestamp;
  1520. rtp->f.mallocd = 0;
  1521. rtp->f.datalen = res - hdrlen;
  1522. rtp->f.data = rtp->rawdata + hdrlen + AST_FRIENDLY_OFFSET;
  1523. rtp->f.offset = hdrlen + AST_FRIENDLY_OFFSET;
  1524. rtp->f.seqno = seqno;
  1525. if (rtp->f.subclass & AST_FORMAT_AUDIO_MASK) {
  1526. rtp->f.samples = ast_codec_get_samples(&rtp->f);
  1527. if (rtp->f.subclass == AST_FORMAT_SLINEAR)
  1528. ast_frame_byteswap_be(&rtp->f);
  1529. calc_rxstamp(&rtp->f.delivery, rtp, timestamp, mark);
  1530. /* Add timing data to let ast_generic_bridge() put the frame into a jitterbuf */
  1531. ast_set_flag(&rtp->f, AST_FRFLAG_HAS_TIMING_INFO);
  1532. rtp->f.ts = timestamp / (rtp_get_rate(rtp->f.subclass) / 1000);
  1533. rtp->f.len = rtp->f.samples / ( (ast_format_rate(rtp->f.subclass) == 16000) ? 16 : 8 );
  1534. } else if(rtp->f.subclass & AST_FORMAT_VIDEO_MASK) {
  1535. /* Video -- samples is # of samples vs. 90000 */
  1536. if (!rtp->lastividtimestamp)
  1537. rtp->lastividtimestamp = timestamp;
  1538. rtp->f.samples = timestamp - rtp->lastividtimestamp;
  1539. rtp->lastividtimestamp = timestamp;
  1540. rtp->f.delivery.tv_sec = 0;
  1541. rtp->f.delivery.tv_usec = 0;
  1542. /* Pass the RTP marker bit as bit 0 in the subclass field.
  1543. * This is ok because subclass is actually a bitmask, and
  1544. * the low bits represent audio formats, that are not
  1545. * involved here since we deal with video.
  1546. */
  1547. if (mark)
  1548. rtp->f.subclass |= 0x1;
  1549. } else {
  1550. /* TEXT -- samples is # of samples vs. 1000 */
  1551. if (!rtp->lastitexttimestamp)
  1552. rtp->lastitexttimestamp = timestamp;
  1553. rtp->f.samples = timestamp - rtp->lastitexttimestamp;
  1554. rtp->lastitexttimestamp = timestamp;
  1555. rtp->f.delivery.tv_sec = 0;
  1556. rtp->f.delivery.tv_usec = 0;
  1557. }
  1558. rtp->f.src = "RTP";
  1559. AST_LIST_INSERT_TAIL(&frames, &rtp->f, frame_list);
  1560. return AST_LIST_FIRST(&frames);
  1561. }
  1562. /* The following array defines the MIME Media type (and subtype) for each
  1563. of our codecs, or RTP-specific data type. */
  1564. static struct {
  1565. struct rtpPayloadType payloadType;
  1566. char* type;
  1567. char* subtype;
  1568. } mimeTypes[] = {
  1569. {{1, AST_FORMAT_G723_1}, "audio", "G723"},
  1570. {{1, AST_FORMAT_GSM}, "audio", "GSM"},
  1571. {{1, AST_FORMAT_ULAW}, "audio", "PCMU"},
  1572. {{1, AST_FORMAT_ULAW}, "audio", "G711U"},
  1573. {{1, AST_FORMAT_ALAW}, "audio", "PCMA"},
  1574. {{1, AST_FORMAT_ALAW}, "audio", "G711A"},
  1575. {{1, AST_FORMAT_G726}, "audio", "G726-32"},
  1576. {{1, AST_FORMAT_ADPCM}, "audio", "DVI4"},
  1577. {{1, AST_FORMAT_SLINEAR}, "audio", "L16"},
  1578. {{1, AST_FORMAT_LPC10}, "audio", "LPC"},
  1579. {{1, AST_FORMAT_G729A}, "audio", "G729"},
  1580. {{1, AST_FORMAT_G729A}, "audio", "G729A"},
  1581. {{1, AST_FORMAT_SPEEX}, "audio", "speex"},
  1582. {{1, AST_FORMAT_ILBC}, "audio", "iLBC"},
  1583. {{1, AST_FORMAT_G722}, "audio", "G722"},
  1584. {{1, AST_FORMAT_G726_AAL2}, "audio", "AAL2-G726-32"},
  1585. {{0, AST_RTP_DTMF}, "audio", "telephone-event"},
  1586. {{0, AST_RTP_CISCO_DTMF}, "audio", "cisco-telephone-event"},
  1587. {{0, AST_RTP_CN}, "audio", "CN"},
  1588. {{1, AST_FORMAT_JPEG}, "video", "JPEG"},
  1589. {{1, AST_FORMAT_PNG}, "video", "PNG"},
  1590. {{1, AST_FORMAT_H261}, "video", "H261"},
  1591. {{1, AST_FORMAT_H263}, "video", "H263"},
  1592. {{1, AST_FORMAT_H263_PLUS}, "video", "h263-1998"},
  1593. {{1, AST_FORMAT_H264}, "video", "H264"},
  1594. {{1, AST_FORMAT_MP4_VIDEO}, "video", "MP4V-ES"},
  1595. {{1, AST_FORMAT_T140}, "text", "T140"},
  1596. };
  1597. /*!
  1598. * \brief Mapping between Asterisk codecs and rtp payload types
  1599. *
  1600. * Static (i.e., well-known) RTP payload types for our "AST_FORMAT..."s:
  1601. * also, our own choices for dynamic payload types. This is our master
  1602. * table for transmission
  1603. *
  1604. * See http://www.iana.org/assignments/rtp-parameters for a list of
  1605. * assigned values
  1606. */
  1607. static struct rtpPayloadType static_RTP_PT[MAX_RTP_PT] = {
  1608. [0] = {1, AST_FORMAT_ULAW},
  1609. #ifdef USE_DEPRECATED_G726
  1610. [2] = {1, AST_FORMAT_G726}, /* Technically this is G.721, but if Cisco can do it, so can we... */
  1611. #endif
  1612. [3] = {1, AST_FORMAT_GSM},
  1613. [4] = {1, AST_FORMAT_G723_1},
  1614. [5] = {1, AST_FORMAT_ADPCM}, /* 8 kHz */
  1615. [6] = {1, AST_FORMAT_ADPCM}, /* 16 kHz */
  1616. [7] = {1, AST_FORMAT_LPC10},
  1617. [8] = {1, AST_FORMAT_ALAW},
  1618. [9] = {1, AST_FORMAT_G722},
  1619. [10] = {1, AST_FORMAT_SLINEAR}, /* 2 channels */
  1620. [11] = {1, AST_FORMAT_SLINEAR}, /* 1 channel */
  1621. [13] = {0, AST_RTP_CN},
  1622. [16] = {1, AST_FORMAT_ADPCM}, /* 11.025 kHz */
  1623. [17] = {1, AST_FORMAT_ADPCM}, /* 22.050 kHz */
  1624. [18] = {1, AST_FORMAT_G729A},
  1625. [19] = {0, AST_RTP_CN}, /* Also used for CN */
  1626. [26] = {1, AST_FORMAT_JPEG},
  1627. [31] = {1, AST_FORMAT_H261},
  1628. [34] = {1, AST_FORMAT_H263},
  1629. [97] = {1, AST_FORMAT_ILBC},
  1630. [98] = {1, AST_FORMAT_H263_PLUS},
  1631. [99] = {1, AST_FORMAT_H264},
  1632. [101] = {0, AST_RTP_DTMF},
  1633. [102] = {1, AST_FORMAT_T140}, /* Real time text chat */
  1634. [103] = {1, AST_FORMAT_H263_PLUS},
  1635. [104] = {1, AST_FORMAT_MP4_VIDEO},
  1636. [110] = {1, AST_FORMAT_SPEEX},
  1637. [111] = {1, AST_FORMAT_G726},
  1638. [112] = {1, AST_FORMAT_G726_AAL2},
  1639. [121] = {0, AST_RTP_CISCO_DTMF}, /* Must be type 121 */
  1640. };
  1641. void ast_rtp_pt_clear(struct ast_rtp* rtp)
  1642. {
  1643. int i;
  1644. if (!rtp)
  1645. return;
  1646. rtp_bridge_lock(rtp);
  1647. for (i = 0; i < MAX_RTP_PT; ++i) {
  1648. rtp->current_RTP_PT[i].isAstFormat = 0;
  1649. rtp->current_RTP_PT[i].code = 0;
  1650. }
  1651. rtp->rtp_lookup_code_cache_isAstFormat = 0;
  1652. rtp->rtp_lookup_code_cache_code = 0;
  1653. rtp->rtp_lookup_code_cache_result = 0;
  1654. rtp_bridge_unlock(rtp);
  1655. }
  1656. void ast_rtp_pt_default(struct ast_rtp* rtp)
  1657. {
  1658. int i;
  1659. rtp_bridge_lock(rtp);
  1660. /* Initialize to default payload types */
  1661. for (i = 0; i < MAX_RTP_PT; ++i) {
  1662. rtp->current_RTP_PT[i].isAstFormat = static_RTP_PT[i].isAstFormat;
  1663. rtp->current_RTP_PT[i].code = static_RTP_PT[i].code;
  1664. }
  1665. rtp->rtp_lookup_code_cache_isAstFormat = 0;
  1666. rtp->rtp_lookup_code_cache_code = 0;
  1667. rtp->rtp_lookup_code_cache_result = 0;
  1668. rtp_bridge_unlock(rtp);
  1669. }
  1670. void ast_rtp_pt_copy(struct ast_rtp *dest, struct ast_rtp *src)
  1671. {
  1672. unsigned int i;
  1673. rtp_bridge_lock(dest);
  1674. rtp_bridge_lock(src);
  1675. for (i = 0; i < MAX_RTP_PT; ++i) {
  1676. dest->current_RTP_PT[i].isAstFormat =
  1677. src->current_RTP_PT[i].isAstFormat;
  1678. dest->current_RTP_PT[i].code =
  1679. src->current_RTP_PT[i].code;
  1680. }
  1681. dest->rtp_lookup_code_cache_isAstFormat = 0;
  1682. dest->rtp_lookup_code_cache_code = 0;
  1683. dest->rtp_lookup_code_cache_result = 0;
  1684. rtp_bridge_unlock(src);
  1685. rtp_bridge_unlock(dest);
  1686. }
  1687. /*! \brief Get channel driver interface structure */
  1688. static struct ast_rtp_protocol *get_proto(struct ast_channel *chan)
  1689. {
  1690. struct ast_rtp_protocol *cur = NULL;
  1691. AST_RWLIST_RDLOCK(&protos);
  1692. AST_RWLIST_TRAVERSE(&protos, cur, list) {
  1693. if (cur->type == chan->tech->type)
  1694. break;
  1695. }
  1696. AST_RWLIST_UNLOCK(&protos);
  1697. return cur;
  1698. }
  1699. int ast_rtp_early_bridge(struct ast_channel *c0, struct ast_channel *c1)
  1700. {
  1701. struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
  1702. struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
  1703. struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
  1704. struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
  1705. enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED, text_dest_res = AST_RTP_GET_FAILED;
  1706. enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED, text_src_res = AST_RTP_GET_FAILED;
  1707. int srccodec, destcodec, nat_active = 0;
  1708. /* Lock channels */
  1709. ast_channel_lock(c0);
  1710. if (c1) {
  1711. while (ast_channel_trylock(c1)) {
  1712. ast_channel_unlock(c0);
  1713. usleep(1);
  1714. ast_channel_lock(c0);
  1715. }
  1716. }
  1717. /* Find channel driver interfaces */
  1718. destpr = get_proto(c0);
  1719. if (c1)
  1720. srcpr = get_proto(c1);
  1721. if (!destpr) {
  1722. ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c0->name);
  1723. ast_channel_unlock(c0);
  1724. if (c1)
  1725. ast_channel_unlock(c1);
  1726. return -1;
  1727. }
  1728. if (!srcpr) {
  1729. ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", c1 ? c1->name : "<unspecified>");
  1730. ast_channel_unlock(c0);
  1731. if (c1)
  1732. ast_channel_unlock(c1);
  1733. return -1;
  1734. }
  1735. /* Get audio, video and text interface (if native bridge is possible) */
  1736. audio_dest_res = destpr->get_rtp_info(c0, &destp);
  1737. video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(c0, &vdestp) : AST_RTP_GET_FAILED;
  1738. text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(c0, &tdestp) : AST_RTP_GET_FAILED;
  1739. if (srcpr) {
  1740. audio_src_res = srcpr->get_rtp_info(c1, &srcp);
  1741. video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(c1, &vsrcp) : AST_RTP_GET_FAILED;
  1742. text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(c1, &tsrcp) : AST_RTP_GET_FAILED;
  1743. }
  1744. /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
  1745. if (audio_dest_res != AST_RTP_TRY_NATIVE || (video_dest_res != AST_RTP_GET_FAILED && video_dest_res != AST_RTP_TRY_NATIVE)) {
  1746. /* Somebody doesn't want to play... */
  1747. ast_channel_unlock(c0);
  1748. if (c1)
  1749. ast_channel_unlock(c1);
  1750. return -1;
  1751. }
  1752. if (audio_src_res == AST_RTP_TRY_NATIVE && (video_src_res == AST_RTP_GET_FAILED || video_src_res == AST_RTP_TRY_NATIVE) && srcpr->get_codec)
  1753. srccodec = srcpr->get_codec(c1);
  1754. else
  1755. srccodec = 0;
  1756. if (audio_dest_res == AST_RTP_TRY_NATIVE && (video_dest_res == AST_RTP_GET_FAILED || video_dest_res == AST_RTP_TRY_NATIVE) && destpr->get_codec)
  1757. destcodec = destpr->get_codec(c0);
  1758. else
  1759. destcodec = 0;
  1760. /* Ensure we have at least one matching codec */
  1761. if (srcp && !(srccodec & destcodec)) {
  1762. ast_channel_unlock(c0);
  1763. ast_channel_unlock(c1);
  1764. return 0;
  1765. }
  1766. /* Consider empty media as non-existent */
  1767. if (audio_src_res == AST_RTP_TRY_NATIVE && !srcp->them.sin_addr.s_addr)
  1768. srcp = NULL;
  1769. if (srcp && (srcp->nat || ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
  1770. nat_active = 1;
  1771. /* Bridge media early */
  1772. if (destpr->set_rtp_peer(c0, srcp, vsrcp, tsrcp, srccodec, nat_active))
  1773. ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
  1774. ast_channel_unlock(c0);
  1775. if (c1)
  1776. ast_channel_unlock(c1);
  1777. ast_debug(1, "Setting early bridge SDP of '%s' with that of '%s'\n", c0->name, c1 ? c1->name : "<unspecified>");
  1778. return 0;
  1779. }
  1780. int ast_rtp_make_compatible(struct ast_channel *dest, struct ast_channel *src, int media)
  1781. {
  1782. struct ast_rtp *destp = NULL, *srcp = NULL; /* Audio RTP Channels */
  1783. struct ast_rtp *vdestp = NULL, *vsrcp = NULL; /* Video RTP channels */
  1784. struct ast_rtp *tdestp = NULL, *tsrcp = NULL; /* Text RTP channels */
  1785. struct ast_rtp_protocol *destpr = NULL, *srcpr = NULL;
  1786. enum ast_rtp_get_result audio_dest_res = AST_RTP_GET_FAILED, video_dest_res = AST_RTP_GET_FAILED, text_dest_res = AST_RTP_GET_FAILED;
  1787. enum ast_rtp_get_result audio_src_res = AST_RTP_GET_FAILED, video_src_res = AST_RTP_GET_FAILED, text_src_res = AST_RTP_GET_FAILED;
  1788. int srccodec, destcodec;
  1789. /* Lock channels */
  1790. ast_channel_lock(dest);
  1791. while (ast_channel_trylock(src)) {
  1792. ast_channel_unlock(dest);
  1793. usleep(1);
  1794. ast_channel_lock(dest);
  1795. }
  1796. /* Find channel driver interfaces */
  1797. if (!(destpr = get_proto(dest))) {
  1798. ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", dest->name);
  1799. ast_channel_unlock(dest);
  1800. ast_channel_unlock(src);
  1801. return 0;
  1802. }
  1803. if (!(srcpr = get_proto(src))) {
  1804. ast_debug(1, "Channel '%s' has no RTP, not doing anything\n", src->name);
  1805. ast_channel_unlock(dest);
  1806. ast_channel_unlock(src);
  1807. return 0;
  1808. }
  1809. /* Get audio and video interface (if native bridge is possible) */
  1810. audio_dest_res = destpr->get_rtp_info(dest, &destp);
  1811. video_dest_res = destpr->get_vrtp_info ? destpr->get_vrtp_info(dest, &vdestp) : AST_RTP_GET_FAILED;
  1812. text_dest_res = destpr->get_trtp_info ? destpr->get_trtp_info(dest, &tdestp) : AST_RTP_GET_FAILED;
  1813. audio_src_res = srcpr->get_rtp_info(src, &srcp);
  1814. video_src_res = srcpr->get_vrtp_info ? srcpr->get_vrtp_info(src, &vsrcp) : AST_RTP_GET_FAILED;
  1815. text_src_res = srcpr->get_trtp_info ? srcpr->get_trtp_info(src, &tsrcp) : AST_RTP_GET_FAILED;
  1816. /* Ensure we have at least one matching codec */
  1817. if (srcpr->get_codec)
  1818. srccodec = srcpr->get_codec(src);
  1819. else
  1820. srccodec = 0;
  1821. if (destpr->get_codec)
  1822. destcodec = destpr->get_codec(dest);
  1823. else
  1824. destcodec = 0;
  1825. /* Check if bridge is still possible (In SIP canreinvite=no stops this, like NAT) */
  1826. if (audio_dest_res != AST_RTP_TRY_NATIVE || (video_dest_res != AST_RTP_GET_FAILED && video_dest_res != AST_RTP_TRY_NATIVE) || audio_src_res != AST_RTP_TRY_NATIVE || (video_src_res != AST_RTP_GET_FAILED && video_src_res != AST_RTP_TRY_NATIVE) || !(srccodec & destcodec)) {
  1827. /* Somebody doesn't want to play... */
  1828. ast_channel_unlock(dest);
  1829. ast_channel_unlock(src);
  1830. return 0;
  1831. }
  1832. ast_rtp_pt_copy(destp, srcp);
  1833. if (vdestp && vsrcp)
  1834. ast_rtp_pt_copy(vdestp, vsrcp);
  1835. if (tdestp && tsrcp)
  1836. ast_rtp_pt_copy(tdestp, tsrcp);
  1837. if (media) {
  1838. /* Bridge early */
  1839. if (destpr->set_rtp_peer(dest, srcp, vsrcp, tsrcp, srccodec, ast_test_flag(srcp, FLAG_NAT_ACTIVE)))
  1840. ast_log(LOG_WARNING, "Channel '%s' failed to setup early bridge to '%s'\n", dest->name, src->name);
  1841. }
  1842. ast_channel_unlock(dest);
  1843. ast_channel_unlock(src);
  1844. ast_debug(1, "Seeded SDP of '%s' with that of '%s'\n", dest->name, src->name);
  1845. return 1;
  1846. }
  1847. /*! \brief Make a note of a RTP payload type that was seen in a SDP "m=" line.
  1848. * By default, use the well-known value for this type (although it may
  1849. * still be set to a different value by a subsequent "a=rtpmap:" line)
  1850. */
  1851. void ast_rtp_set_m_type(struct ast_rtp* rtp, int pt)
  1852. {
  1853. if (pt < 0 || pt >= MAX_RTP_PT || static_RTP_PT[pt].code == 0)
  1854. return; /* bogus payload type */
  1855. rtp_bridge_lock(rtp);
  1856. rtp->current_RTP_PT[pt] = static_RTP_PT[pt];
  1857. rtp_bridge_unlock(rtp);
  1858. }
  1859. /*! \brief remove setting from payload type list if the rtpmap header indicates
  1860. an unknown media type */
  1861. void ast_rtp_unset_m_type(struct ast_rtp* rtp, int pt)
  1862. {
  1863. if (pt < 0 || pt >= MAX_RTP_PT)
  1864. return; /* bogus payload type */
  1865. rtp_bridge_lock(rtp);
  1866. rtp->current_RTP_PT[pt].isAstFormat = 0;
  1867. rtp->current_RTP_PT[pt].code = 0;
  1868. rtp_bridge_unlock(rtp);
  1869. }
  1870. /*! \brief Make a note of a RTP payload type (with MIME type) that was seen in
  1871. * an SDP "a=rtpmap:" line.
  1872. * \return 0 if the MIME type was found and set, -1 if it wasn't found
  1873. */
  1874. int ast_rtp_set_rtpmap_type(struct ast_rtp *rtp, int pt,
  1875. char *mimeType, char *mimeSubtype,
  1876. enum ast_rtp_options options)
  1877. {
  1878. unsigned int i;
  1879. int found = 0;
  1880. if (pt < 0 || pt >= MAX_RTP_PT)
  1881. return -1; /* bogus payload type */
  1882. rtp_bridge_lock(rtp);
  1883. for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
  1884. if (strcasecmp(mimeSubtype, mimeTypes[i].subtype) == 0 &&
  1885. strcasecmp(mimeType, mimeTypes[i].type) == 0) {
  1886. found = 1;
  1887. rtp->current_RTP_PT[pt] = mimeTypes[i].payloadType;
  1888. if ((mimeTypes[i].payloadType.code == AST_FORMAT_G726) &&
  1889. mimeTypes[i].payloadType.isAstFormat &&
  1890. (options & AST_RTP_OPT_G726_NONSTANDARD))
  1891. rtp->current_RTP_PT[pt].code = AST_FORMAT_G726_AAL2;
  1892. break;
  1893. }
  1894. }
  1895. rtp_bridge_unlock(rtp);
  1896. return (found ? 0 : -1);
  1897. }
  1898. /*! \brief Return the union of all of the codecs that were set by rtp_set...() calls
  1899. * They're returned as two distinct sets: AST_FORMATs, and AST_RTPs */
  1900. void ast_rtp_get_current_formats(struct ast_rtp* rtp,
  1901. int* astFormats, int* nonAstFormats)
  1902. {
  1903. int pt;
  1904. rtp_bridge_lock(rtp);
  1905. *astFormats = *nonAstFormats = 0;
  1906. for (pt = 0; pt < MAX_RTP_PT; ++pt) {
  1907. if (rtp->current_RTP_PT[pt].isAstFormat) {
  1908. *astFormats |= rtp->current_RTP_PT[pt].code;
  1909. } else {
  1910. *nonAstFormats |= rtp->current_RTP_PT[pt].code;
  1911. }
  1912. }
  1913. rtp_bridge_unlock(rtp);
  1914. }
  1915. struct rtpPayloadType ast_rtp_lookup_pt(struct ast_rtp* rtp, int pt)
  1916. {
  1917. struct rtpPayloadType result;
  1918. result.isAstFormat = result.code = 0;
  1919. if (pt < 0 || pt >= MAX_RTP_PT)
  1920. return result; /* bogus payload type */
  1921. /* Start with negotiated codecs */
  1922. rtp_bridge_lock(rtp);
  1923. result = rtp->current_RTP_PT[pt];
  1924. rtp_bridge_unlock(rtp);
  1925. /* If it doesn't exist, check our static RTP type list, just in case */
  1926. if (!result.code)
  1927. result = static_RTP_PT[pt];
  1928. return result;
  1929. }
  1930. /*! \brief Looks up an RTP code out of our *static* outbound list */
  1931. int ast_rtp_lookup_code(struct ast_rtp* rtp, const int isAstFormat, const int code)
  1932. {
  1933. int pt = 0;
  1934. rtp_bridge_lock(rtp);
  1935. if (isAstFormat == rtp->rtp_lookup_code_cache_isAstFormat &&
  1936. code == rtp->rtp_lookup_code_cache_code) {
  1937. /* Use our cached mapping, to avoid the overhead of the loop below */
  1938. pt = rtp->rtp_lookup_code_cache_result;
  1939. rtp_bridge_unlock(rtp);
  1940. return pt;
  1941. }
  1942. /* Check the dynamic list first */
  1943. for (pt = 0; pt < MAX_RTP_PT; ++pt) {
  1944. if (rtp->current_RTP_PT[pt].code == code && rtp->current_RTP_PT[pt].isAstFormat == isAstFormat) {
  1945. rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
  1946. rtp->rtp_lookup_code_cache_code = code;
  1947. rtp->rtp_lookup_code_cache_result = pt;
  1948. rtp_bridge_unlock(rtp);
  1949. return pt;
  1950. }
  1951. }
  1952. /* Then the static list */
  1953. for (pt = 0; pt < MAX_RTP_PT; ++pt) {
  1954. if (static_RTP_PT[pt].code == code && static_RTP_PT[pt].isAstFormat == isAstFormat) {
  1955. rtp->rtp_lookup_code_cache_isAstFormat = isAstFormat;
  1956. rtp->rtp_lookup_code_cache_code = code;
  1957. rtp->rtp_lookup_code_cache_result = pt;
  1958. rtp_bridge_unlock(rtp);
  1959. return pt;
  1960. }
  1961. }
  1962. rtp_bridge_unlock(rtp);
  1963. return -1;
  1964. }
  1965. const char *ast_rtp_lookup_mime_subtype(const int isAstFormat, const int code,
  1966. enum ast_rtp_options options)
  1967. {
  1968. unsigned int i;
  1969. for (i = 0; i < ARRAY_LEN(mimeTypes); ++i) {
  1970. if ((mimeTypes[i].payloadType.code == code) && (mimeTypes[i].payloadType.isAstFormat == isAstFormat)) {
  1971. if (isAstFormat &&
  1972. (code == AST_FORMAT_G726_AAL2) &&
  1973. (options & AST_RTP_OPT_G726_NONSTANDARD))
  1974. return "G726-32";
  1975. else
  1976. return mimeTypes[i].subtype;
  1977. }
  1978. }
  1979. return "";
  1980. }
  1981. char *ast_rtp_lookup_mime_multiple(char *buf, size_t size, const int capability,
  1982. const int isAstFormat, enum ast_rtp_options options)
  1983. {
  1984. int format;
  1985. unsigned len;
  1986. char *end = buf;
  1987. char *start = buf;
  1988. if (!buf || !size)
  1989. return NULL;
  1990. snprintf(end, size, "0x%x (", capability);
  1991. len = strlen(end);
  1992. end += len;
  1993. size -= len;
  1994. start = end;
  1995. for (format = 1; format < AST_RTP_MAX; format <<= 1) {
  1996. if (capability & format) {
  1997. const char *name = ast_rtp_lookup_mime_subtype(isAstFormat, format, options);
  1998. snprintf(end, size, "%s|", name);
  1999. len = strlen(end);
  2000. end += len;
  2001. size -= len;
  2002. }
  2003. }
  2004. if (start == end)
  2005. ast_copy_string(start, "nothing)", size);
  2006. else if (size > 1)
  2007. *(end -1) = ')';
  2008. return buf;
  2009. }
  2010. /*! \brief Open RTP or RTCP socket for a session.
  2011. * Print a message on failure.
  2012. */
  2013. static int rtp_socket(const char *type)
  2014. {
  2015. int s = socket(AF_INET, SOCK_DGRAM, 0);
  2016. if (s < 0) {
  2017. if (type == NULL)
  2018. type = "RTP/RTCP";
  2019. ast_log(LOG_WARNING, "Unable to allocate %s socket: %s\n", type, strerror(errno));
  2020. } else {
  2021. long flags = fcntl(s, F_GETFL);
  2022. fcntl(s, F_SETFL, flags | O_NONBLOCK);
  2023. #ifdef SO_NO_CHECK
  2024. if (nochecksums)
  2025. setsockopt(s, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
  2026. #endif
  2027. }
  2028. return s;
  2029. }
  2030. /*!
  2031. * \brief Initialize a new RTCP session.
  2032. *
  2033. * \returns The newly initialized RTCP session.
  2034. */
  2035. static struct ast_rtcp *ast_rtcp_new(void)
  2036. {
  2037. struct ast_rtcp *rtcp;
  2038. if (!(rtcp = ast_calloc(1, sizeof(*rtcp))))
  2039. return NULL;
  2040. rtcp->s = rtp_socket("RTCP");
  2041. rtcp->us.sin_family = AF_INET;
  2042. rtcp->them.sin_family = AF_INET;
  2043. rtcp->schedid = -1;
  2044. if (rtcp->s < 0) {
  2045. ast_free(rtcp);
  2046. return NULL;
  2047. }
  2048. return rtcp;
  2049. }
  2050. /*!
  2051. * \brief Initialize a new RTP structure.
  2052. *
  2053. */
  2054. void ast_rtp_new_init(struct ast_rtp *rtp)
  2055. {
  2056. #ifdef P2P_INTENSE
  2057. ast_mutex_init(&rtp->bridge_lock);
  2058. #endif
  2059. rtp->them.sin_family = AF_INET;
  2060. rtp->us.sin_family = AF_INET;
  2061. rtp->ssrc = ast_random();
  2062. rtp->seqno = ast_random() & 0xffff;
  2063. ast_set_flag(rtp, FLAG_HAS_DTMF);
  2064. rtp->strict_rtp_state = (strictrtp ? STRICT_RTP_LEARN : STRICT_RTP_OPEN);
  2065. }
  2066. struct ast_rtp *ast_rtp_new_with_bindaddr(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode, struct in_addr addr)
  2067. {
  2068. struct ast_rtp *rtp;
  2069. int x;
  2070. int startplace;
  2071. if (!(rtp = ast_calloc(1, sizeof(*rtp))))
  2072. return NULL;
  2073. ast_rtp_new_init(rtp);
  2074. rtp->s = rtp_socket("RTP");
  2075. if (rtp->s < 0)
  2076. goto fail;
  2077. if (sched && rtcpenable) {
  2078. rtp->sched = sched;
  2079. rtp->rtcp = ast_rtcp_new();
  2080. }
  2081. /*
  2082. * Try to bind the RTP port, x, and possibly the RTCP port, x+1 as well.
  2083. * Start from a random (even, by RTP spec) port number, and
  2084. * iterate until success or no ports are available.
  2085. * Note that the requirement of RTP port being even, or RTCP being the
  2086. * next one, cannot be enforced in presence of a NAT box because the
  2087. * mapping is not under our control.
  2088. */
  2089. x = (rtpend == rtpstart) ? rtpstart : (ast_random() % (rtpend - rtpstart)) + rtpstart;
  2090. x = x & ~1; /* make it an even number */
  2091. startplace = x; /* remember the starting point */
  2092. /* this is constant across the loop */
  2093. rtp->us.sin_addr = addr;
  2094. if (rtp->rtcp)
  2095. rtp->rtcp->us.sin_addr = addr;
  2096. for (;;) {
  2097. rtp->us.sin_port = htons(x);
  2098. if (!bind(rtp->s, (struct sockaddr *)&rtp->us, sizeof(rtp->us))) {
  2099. /* bind succeeded, if no rtcp then we are done */
  2100. if (!rtp->rtcp)
  2101. break;
  2102. /* have rtcp, try to bind it */
  2103. rtp->rtcp->us.sin_port = htons(x + 1);
  2104. if (!bind(rtp->rtcp->s, (struct sockaddr *)&rtp->rtcp->us, sizeof(rtp->rtcp->us)))
  2105. break; /* success again, we are really done */
  2106. /*
  2107. * RTCP bind failed, so close and recreate the
  2108. * already bound RTP socket for the next round.
  2109. */
  2110. close(rtp->s);
  2111. rtp->s = rtp_socket("RTP");
  2112. if (rtp->s < 0)
  2113. goto fail;
  2114. }
  2115. /*
  2116. * If we get here, there was an error in one of the bind()
  2117. * calls, so make sure it is nothing unexpected.
  2118. */
  2119. if (errno != EADDRINUSE) {
  2120. /* We got an error that wasn't expected, abort! */
  2121. ast_log(LOG_ERROR, "Unexpected bind error: %s\n", strerror(errno));
  2122. goto fail;
  2123. }
  2124. /*
  2125. * One of the ports is in use. For the next iteration,
  2126. * increment by two and handle wraparound.
  2127. * If we reach the starting point, then declare failure.
  2128. */
  2129. x += 2;
  2130. if (x > rtpend)
  2131. x = (rtpstart + 1) & ~1;
  2132. if (x == startplace) {
  2133. ast_log(LOG_ERROR, "No RTP ports remaining. Can't setup media stream for this call.\n");
  2134. goto fail;
  2135. }
  2136. }
  2137. rtp->sched = sched;
  2138. rtp->io = io;
  2139. if (callbackmode) {
  2140. rtp->ioid = ast_io_add(rtp->io, rtp->s, rtpread, AST_IO_IN, rtp);
  2141. ast_set_flag(rtp, FLAG_CALLBACK_MODE);
  2142. }
  2143. ast_rtp_pt_default(rtp);
  2144. return rtp;
  2145. fail:
  2146. if (rtp->s >= 0)
  2147. close(rtp->s);
  2148. if (rtp->rtcp) {
  2149. close(rtp->rtcp->s);
  2150. ast_free(rtp->rtcp);
  2151. }
  2152. ast_free(rtp);
  2153. return NULL;
  2154. }
  2155. struct ast_rtp *ast_rtp_new(struct sched_context *sched, struct io_context *io, int rtcpenable, int callbackmode)
  2156. {
  2157. struct in_addr ia;
  2158. memset(&ia, 0, sizeof(ia));
  2159. return ast_rtp_new_with_bindaddr(sched, io, rtcpenable, callbackmode, ia);
  2160. }
  2161. int ast_rtp_setqos(struct ast_rtp *rtp, int tos, int cos, char *desc)
  2162. {
  2163. return ast_netsock_set_qos(rtp->s, tos, cos, desc);
  2164. }
  2165. void ast_rtp_new_source(struct ast_rtp *rtp)
  2166. {
  2167. if (rtp) {
  2168. rtp->set_marker_bit = 1;
  2169. ast_debug(3, "Setting the marker bit due to a source update\n");
  2170. }
  2171. }
  2172. void ast_rtp_change_source(struct ast_rtp *rtp)
  2173. {
  2174. if (rtp) {
  2175. unsigned int ssrc = ast_random();
  2176. rtp->set_marker_bit = 1;
  2177. ast_debug(3, "Changing ssrc from %u to %u due to a source change\n", rtp->ssrc, ssrc);
  2178. rtp->ssrc = ssrc;
  2179. }
  2180. }
  2181. void ast_rtp_set_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
  2182. {
  2183. rtp->them.sin_port = them->sin_port;
  2184. rtp->them.sin_addr = them->sin_addr;
  2185. if (rtp->rtcp) {
  2186. rtp->rtcp->them.sin_port = htons(ntohs(them->sin_port) + 1);
  2187. rtp->rtcp->them.sin_addr = them->sin_addr;
  2188. }
  2189. rtp->rxseqno = 0;
  2190. /* If strict RTP protection is enabled switch back to the learn state so we don't drop packets from above */
  2191. if (strictrtp)
  2192. rtp->strict_rtp_state = STRICT_RTP_LEARN;
  2193. }
  2194. void ast_rtp_set_alt_peer(struct ast_rtp *rtp, struct sockaddr_in *alt)
  2195. {
  2196. rtp->altthem.sin_port = alt->sin_port;
  2197. rtp->altthem.sin_addr = alt->sin_addr;
  2198. if (rtp->rtcp) {
  2199. rtp->rtcp->altthem.sin_port = htons(ntohs(alt->sin_port) + 1);
  2200. rtp->rtcp->altthem.sin_addr = alt->sin_addr;
  2201. }
  2202. }
  2203. int ast_rtp_get_peer(struct ast_rtp *rtp, struct sockaddr_in *them)
  2204. {
  2205. if ((them->sin_family != AF_INET) ||
  2206. (them->sin_port != rtp->them.sin_port) ||
  2207. (them->sin_addr.s_addr != rtp->them.sin_addr.s_addr)) {
  2208. them->sin_family = AF_INET;
  2209. them->sin_port = rtp->them.sin_port;
  2210. them->sin_addr = rtp->them.sin_addr;
  2211. return 1;
  2212. }
  2213. return 0;
  2214. }
  2215. void ast_rtp_get_us(struct ast_rtp *rtp, struct sockaddr_in *us)
  2216. {
  2217. *us = rtp->us;
  2218. }
  2219. struct ast_rtp *ast_rtp_get_bridged(struct ast_rtp *rtp)
  2220. {
  2221. struct ast_rtp *bridged = NULL;
  2222. rtp_bridge_lock(rtp);
  2223. bridged = rtp->bridged;
  2224. rtp_bridge_unlock(rtp);
  2225. return bridged;
  2226. }
  2227. void ast_rtp_stop(struct ast_rtp *rtp)
  2228. {
  2229. if (rtp->rtcp) {
  2230. AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
  2231. }
  2232. memset(&rtp->them.sin_addr, 0, sizeof(rtp->them.sin_addr));
  2233. memset(&rtp->them.sin_port, 0, sizeof(rtp->them.sin_port));
  2234. if (rtp->rtcp) {
  2235. memset(&rtp->rtcp->them.sin_addr, 0, sizeof(rtp->rtcp->them.sin_addr));
  2236. memset(&rtp->rtcp->them.sin_port, 0, sizeof(rtp->rtcp->them.sin_port));
  2237. }
  2238. ast_clear_flag(rtp, FLAG_P2P_SENT_MARK);
  2239. }
  2240. void ast_rtp_reset(struct ast_rtp *rtp)
  2241. {
  2242. memset(&rtp->rxcore, 0, sizeof(rtp->rxcore));
  2243. memset(&rtp->txcore, 0, sizeof(rtp->txcore));
  2244. memset(&rtp->dtmfmute, 0, sizeof(rtp->dtmfmute));
  2245. rtp->lastts = 0;
  2246. rtp->lastdigitts = 0;
  2247. rtp->lastrxts = 0;
  2248. rtp->lastividtimestamp = 0;
  2249. rtp->lastovidtimestamp = 0;
  2250. rtp->lastitexttimestamp = 0;
  2251. rtp->lastotexttimestamp = 0;
  2252. rtp->lasteventseqn = 0;
  2253. rtp->lastevent = 0;
  2254. rtp->lasttxformat = 0;
  2255. rtp->lastrxformat = 0;
  2256. rtp->dtmf_timeout = 0;
  2257. rtp->dtmfsamples = 0;
  2258. rtp->seqno = 0;
  2259. rtp->rxseqno = 0;
  2260. }
  2261. char *ast_rtp_get_quality(struct ast_rtp *rtp, struct ast_rtp_quality *qual)
  2262. {
  2263. /*
  2264. *ssrc our ssrc
  2265. *themssrc their ssrc
  2266. *lp lost packets
  2267. *rxjitter our calculated jitter(rx)
  2268. *rxcount no. received packets
  2269. *txjitter reported jitter of the other end
  2270. *txcount transmitted packets
  2271. *rlp remote lost packets
  2272. *rtt round trip time
  2273. */
  2274. if (qual && rtp) {
  2275. qual->local_ssrc = rtp->ssrc;
  2276. qual->local_jitter = rtp->rxjitter;
  2277. qual->local_count = rtp->rxcount;
  2278. qual->remote_ssrc = rtp->themssrc;
  2279. qual->remote_count = rtp->txcount;
  2280. if (rtp->rtcp) {
  2281. qual->local_lostpackets = rtp->rtcp->expected_prior - rtp->rtcp->received_prior;
  2282. qual->remote_lostpackets = rtp->rtcp->reported_lost;
  2283. qual->remote_jitter = rtp->rtcp->reported_jitter / 65536.0;
  2284. qual->rtt = rtp->rtcp->rtt;
  2285. }
  2286. }
  2287. if (rtp->rtcp) {
  2288. snprintf(rtp->rtcp->quality, sizeof(rtp->rtcp->quality),
  2289. "ssrc=%u;themssrc=%u;lp=%u;rxjitter=%f;rxcount=%u;txjitter=%f;txcount=%u;rlp=%u;rtt=%f",
  2290. rtp->ssrc,
  2291. rtp->themssrc,
  2292. rtp->rtcp->expected_prior - rtp->rtcp->received_prior,
  2293. rtp->rxjitter,
  2294. rtp->rxcount,
  2295. (double)rtp->rtcp->reported_jitter / 65536.0,
  2296. rtp->txcount,
  2297. rtp->rtcp->reported_lost,
  2298. rtp->rtcp->rtt);
  2299. return rtp->rtcp->quality;
  2300. } else
  2301. return "<Unknown> - RTP/RTCP has already been destroyed";
  2302. }
  2303. void ast_rtp_destroy(struct ast_rtp *rtp)
  2304. {
  2305. if (rtcp_debug_test_addr(&rtp->them) || rtcpstats) {
  2306. /*Print some info on the call here */
  2307. ast_verbose(" RTP-stats\n");
  2308. ast_verbose("* Our Receiver:\n");
  2309. ast_verbose(" SSRC: %u\n", rtp->themssrc);
  2310. ast_verbose(" Received packets: %u\n", rtp->rxcount);
  2311. ast_verbose(" Lost packets: %u\n", rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0);
  2312. ast_verbose(" Jitter: %.4f\n", rtp->rxjitter);
  2313. ast_verbose(" Transit: %.4f\n", rtp->rxtransit);
  2314. ast_verbose(" RR-count: %u\n", rtp->rtcp ? rtp->rtcp->rr_count : 0);
  2315. ast_verbose("* Our Sender:\n");
  2316. ast_verbose(" SSRC: %u\n", rtp->ssrc);
  2317. ast_verbose(" Sent packets: %u\n", rtp->txcount);
  2318. ast_verbose(" Lost packets: %u\n", rtp->rtcp ? rtp->rtcp->reported_lost : 0);
  2319. ast_verbose(" Jitter: %u\n", rtp->rtcp ? (rtp->rtcp->reported_jitter / (unsigned int)65536.0) : 0);
  2320. ast_verbose(" SR-count: %u\n", rtp->rtcp ? rtp->rtcp->sr_count : 0);
  2321. ast_verbose(" RTT: %f\n", rtp->rtcp ? rtp->rtcp->rtt : 0);
  2322. }
  2323. manager_event(EVENT_FLAG_REPORTING, "RTPReceiverStat", "SSRC: %u\r\n"
  2324. "ReceivedPackets: %u\r\n"
  2325. "LostPackets: %u\r\n"
  2326. "Jitter: %.4f\r\n"
  2327. "Transit: %.4f\r\n"
  2328. "RRCount: %u\r\n",
  2329. rtp->themssrc,
  2330. rtp->rxcount,
  2331. rtp->rtcp ? (rtp->rtcp->expected_prior - rtp->rtcp->received_prior) : 0,
  2332. rtp->rxjitter,
  2333. rtp->rxtransit,
  2334. rtp->rtcp ? rtp->rtcp->rr_count : 0);
  2335. manager_event(EVENT_FLAG_REPORTING, "RTPSenderStat", "SSRC: %u\r\n"
  2336. "SentPackets: %u\r\n"
  2337. "LostPackets: %u\r\n"
  2338. "Jitter: %u\r\n"
  2339. "SRCount: %u\r\n"
  2340. "RTT: %f\r\n",
  2341. rtp->ssrc,
  2342. rtp->txcount,
  2343. rtp->rtcp ? rtp->rtcp->reported_lost : 0,
  2344. rtp->rtcp ? rtp->rtcp->reported_jitter : 0,
  2345. rtp->rtcp ? rtp->rtcp->sr_count : 0,
  2346. rtp->rtcp ? rtp->rtcp->rtt : 0);
  2347. if (rtp->smoother)
  2348. ast_smoother_free(rtp->smoother);
  2349. if (rtp->ioid)
  2350. ast_io_remove(rtp->io, rtp->ioid);
  2351. if (rtp->s > -1)
  2352. close(rtp->s);
  2353. if (rtp->rtcp) {
  2354. AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
  2355. close(rtp->rtcp->s);
  2356. ast_free(rtp->rtcp);
  2357. rtp->rtcp=NULL;
  2358. }
  2359. #ifdef P2P_INTENSE
  2360. ast_mutex_destroy(&rtp->bridge_lock);
  2361. #endif
  2362. ast_free(rtp);
  2363. }
  2364. static unsigned int calc_txstamp(struct ast_rtp *rtp, struct timeval *delivery)
  2365. {
  2366. struct timeval t;
  2367. long ms;
  2368. if (ast_tvzero(rtp->txcore)) {
  2369. rtp->txcore = ast_tvnow();
  2370. /* Round to 20ms for nice, pretty timestamps */
  2371. rtp->txcore.tv_usec -= rtp->txcore.tv_usec % 20000;
  2372. }
  2373. /* Use previous txcore if available */
  2374. t = (delivery && !ast_tvzero(*delivery)) ? *delivery : ast_tvnow();
  2375. ms = ast_tvdiff_ms(t, rtp->txcore);
  2376. if (ms < 0)
  2377. ms = 0;
  2378. /* Use what we just got for next time */
  2379. rtp->txcore = t;
  2380. return (unsigned int) ms;
  2381. }
  2382. /*! \brief Send begin frames for DTMF */
  2383. int ast_rtp_senddigit_begin(struct ast_rtp *rtp, char digit)
  2384. {
  2385. unsigned int *rtpheader;
  2386. int hdrlen = 12, res = 0, i = 0, payload = 0;
  2387. char data[256];
  2388. if ((digit <= '9') && (digit >= '0'))
  2389. digit -= '0';
  2390. else if (digit == '*')
  2391. digit = 10;
  2392. else if (digit == '#')
  2393. digit = 11;
  2394. else if ((digit >= 'A') && (digit <= 'D'))
  2395. digit = digit - 'A' + 12;
  2396. else if ((digit >= 'a') && (digit <= 'd'))
  2397. digit = digit - 'a' + 12;
  2398. else {
  2399. ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
  2400. return 0;
  2401. }
  2402. /* If we have no peer, return immediately */
  2403. if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
  2404. return 0;
  2405. payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_DTMF);
  2406. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  2407. rtp->send_duration = 160;
  2408. rtp->lastdigitts = rtp->lastts + rtp->send_duration;
  2409. /* Get a pointer to the header */
  2410. rtpheader = (unsigned int *)data;
  2411. rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno));
  2412. rtpheader[1] = htonl(rtp->lastdigitts);
  2413. rtpheader[2] = htonl(rtp->ssrc);
  2414. for (i = 0; i < 2; i++) {
  2415. rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
  2416. res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
  2417. if (res < 0)
  2418. ast_log(LOG_ERROR, "RTP Transmission error to %s:%u: %s\n",
  2419. ast_inet_ntoa(rtp->them.sin_addr),
  2420. ntohs(rtp->them.sin_port), strerror(errno));
  2421. if (rtp_debug_test_addr(&rtp->them))
  2422. ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  2423. ast_inet_ntoa(rtp->them.sin_addr),
  2424. ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  2425. /* Increment sequence number */
  2426. rtp->seqno++;
  2427. /* Increment duration */
  2428. rtp->send_duration += 160;
  2429. /* Clear marker bit and set seqno */
  2430. rtpheader[0] = htonl((2 << 30) | (payload << 16) | (rtp->seqno));
  2431. }
  2432. /* Since we received a begin, we can safely store the digit and disable any compensation */
  2433. rtp->sending_digit = 1;
  2434. rtp->send_digit = digit;
  2435. rtp->send_payload = payload;
  2436. return 0;
  2437. }
  2438. /*! \brief Send continuation frame for DTMF */
  2439. static int ast_rtp_senddigit_continuation(struct ast_rtp *rtp)
  2440. {
  2441. unsigned int *rtpheader;
  2442. int hdrlen = 12, res = 0;
  2443. char data[256];
  2444. if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
  2445. return 0;
  2446. /* Setup packet to send */
  2447. rtpheader = (unsigned int *)data;
  2448. rtpheader[0] = htonl((2 << 30) | (1 << 23) | (rtp->send_payload << 16) | (rtp->seqno));
  2449. rtpheader[1] = htonl(rtp->lastdigitts);
  2450. rtpheader[2] = htonl(rtp->ssrc);
  2451. rtpheader[3] = htonl((rtp->send_digit << 24) | (0xa << 16) | (rtp->send_duration));
  2452. rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
  2453. /* Transmit */
  2454. res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
  2455. if (res < 0)
  2456. ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
  2457. ast_inet_ntoa(rtp->them.sin_addr),
  2458. ntohs(rtp->them.sin_port), strerror(errno));
  2459. if (rtp_debug_test_addr(&rtp->them))
  2460. ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  2461. ast_inet_ntoa(rtp->them.sin_addr),
  2462. ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  2463. /* Increment sequence number */
  2464. rtp->seqno++;
  2465. /* Increment duration */
  2466. rtp->send_duration += 160;
  2467. return 0;
  2468. }
  2469. /*! \brief Send end packets for DTMF */
  2470. int ast_rtp_senddigit_end(struct ast_rtp *rtp, char digit)
  2471. {
  2472. unsigned int *rtpheader;
  2473. int hdrlen = 12, res = 0, i = 0;
  2474. char data[256];
  2475. /* If no address, then bail out */
  2476. if (!rtp->them.sin_addr.s_addr || !rtp->them.sin_port)
  2477. return 0;
  2478. if ((digit <= '9') && (digit >= '0'))
  2479. digit -= '0';
  2480. else if (digit == '*')
  2481. digit = 10;
  2482. else if (digit == '#')
  2483. digit = 11;
  2484. else if ((digit >= 'A') && (digit <= 'D'))
  2485. digit = digit - 'A' + 12;
  2486. else if ((digit >= 'a') && (digit <= 'd'))
  2487. digit = digit - 'a' + 12;
  2488. else {
  2489. ast_log(LOG_WARNING, "Don't know how to represent '%c'\n", digit);
  2490. return 0;
  2491. }
  2492. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  2493. rtpheader = (unsigned int *)data;
  2494. rtpheader[1] = htonl(rtp->lastdigitts);
  2495. rtpheader[2] = htonl(rtp->ssrc);
  2496. rtpheader[3] = htonl((digit << 24) | (0xa << 16) | (rtp->send_duration));
  2497. /* Set end bit */
  2498. rtpheader[3] |= htonl((1 << 23));
  2499. /* Send 3 termination packets */
  2500. for (i = 0; i < 3; i++) {
  2501. rtpheader[0] = htonl((2 << 30) | (rtp->send_payload << 16) | (rtp->seqno));
  2502. res = sendto(rtp->s, (void *) rtpheader, hdrlen + 4, 0, (struct sockaddr *) &rtp->them, sizeof(rtp->them));
  2503. rtp->seqno++;
  2504. if (res < 0)
  2505. ast_log(LOG_ERROR, "RTP Transmission error to %s:%d: %s\n",
  2506. ast_inet_ntoa(rtp->them.sin_addr),
  2507. ntohs(rtp->them.sin_port), strerror(errno));
  2508. if (rtp_debug_test_addr(&rtp->them))
  2509. ast_verbose("Sent RTP DTMF packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  2510. ast_inet_ntoa(rtp->them.sin_addr),
  2511. ntohs(rtp->them.sin_port), rtp->send_payload, rtp->seqno, rtp->lastdigitts, res - hdrlen);
  2512. }
  2513. rtp->lastts += rtp->send_duration;
  2514. rtp->sending_digit = 0;
  2515. rtp->send_digit = 0;
  2516. return res;
  2517. }
  2518. /*! \brief Public function: Send an H.261 fast update request, some devices need this rather than SIP XML */
  2519. int ast_rtcp_send_h261fur(void *data)
  2520. {
  2521. struct ast_rtp *rtp = data;
  2522. int res;
  2523. rtp->rtcp->sendfur = 1;
  2524. res = ast_rtcp_write(data);
  2525. return res;
  2526. }
  2527. /*! \brief Send RTCP sender's report */
  2528. static int ast_rtcp_write_sr(const void *data)
  2529. {
  2530. struct ast_rtp *rtp = (struct ast_rtp *)data;
  2531. int res;
  2532. int len = 0;
  2533. struct timeval now;
  2534. unsigned int now_lsw;
  2535. unsigned int now_msw;
  2536. unsigned int *rtcpheader;
  2537. unsigned int lost;
  2538. unsigned int extended;
  2539. unsigned int expected;
  2540. unsigned int expected_interval;
  2541. unsigned int received_interval;
  2542. int lost_interval;
  2543. int fraction;
  2544. struct timeval dlsr;
  2545. char bdata[512];
  2546. /* Commented condition is always not NULL if rtp->rtcp is not NULL */
  2547. if (!rtp || !rtp->rtcp/* || (&rtp->rtcp->them.sin_addr == 0)*/)
  2548. return 0;
  2549. if (!rtp->rtcp->them.sin_addr.s_addr) { /* This'll stop rtcp for this rtp session */
  2550. ast_verbose("RTCP SR transmission error, rtcp halted\n");
  2551. AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
  2552. return 0;
  2553. }
  2554. gettimeofday(&now, NULL);
  2555. timeval2ntp(now, &now_msw, &now_lsw); /* fill thses ones in from utils.c*/
  2556. rtcpheader = (unsigned int *)bdata;
  2557. rtcpheader[1] = htonl(rtp->ssrc); /* Our SSRC */
  2558. rtcpheader[2] = htonl(now_msw); /* now, MSW. gettimeofday() + SEC_BETWEEN_1900_AND_1970*/
  2559. rtcpheader[3] = htonl(now_lsw); /* now, LSW */
  2560. rtcpheader[4] = htonl(rtp->lastts); /* FIXME shouldn't be that, it should be now */
  2561. rtcpheader[5] = htonl(rtp->txcount); /* No. packets sent */
  2562. rtcpheader[6] = htonl(rtp->txoctetcount); /* No. bytes sent */
  2563. len += 28;
  2564. extended = rtp->cycles + rtp->lastrxseqno;
  2565. expected = extended - rtp->seedrxseqno + 1;
  2566. if (rtp->rxcount > expected)
  2567. expected += rtp->rxcount - expected;
  2568. lost = expected - rtp->rxcount;
  2569. expected_interval = expected - rtp->rtcp->expected_prior;
  2570. rtp->rtcp->expected_prior = expected;
  2571. received_interval = rtp->rxcount - rtp->rtcp->received_prior;
  2572. rtp->rtcp->received_prior = rtp->rxcount;
  2573. lost_interval = expected_interval - received_interval;
  2574. if (expected_interval == 0 || lost_interval <= 0)
  2575. fraction = 0;
  2576. else
  2577. fraction = (lost_interval << 8) / expected_interval;
  2578. timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
  2579. rtcpheader[7] = htonl(rtp->themssrc);
  2580. rtcpheader[8] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
  2581. rtcpheader[9] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
  2582. rtcpheader[10] = htonl((unsigned int)(rtp->rxjitter * 65536.));
  2583. rtcpheader[11] = htonl(rtp->rtcp->themrxlsr);
  2584. rtcpheader[12] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
  2585. len += 24;
  2586. rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SR << 16) | ((len/4)-1));
  2587. if (rtp->rtcp->sendfur) {
  2588. rtcpheader[13] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1);
  2589. rtcpheader[14] = htonl(rtp->ssrc); /* Our SSRC */
  2590. len += 8;
  2591. rtp->rtcp->sendfur = 0;
  2592. }
  2593. /* Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos */
  2594. /* it can change mid call, and SDES can't) */
  2595. rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
  2596. rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
  2597. rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
  2598. len += 12;
  2599. res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
  2600. if (res < 0) {
  2601. ast_log(LOG_ERROR, "RTCP SR transmission error to %s:%d, rtcp halted %s\n",ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port), strerror(errno));
  2602. AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
  2603. return 0;
  2604. }
  2605. /* FIXME Don't need to get a new one */
  2606. gettimeofday(&rtp->rtcp->txlsr, NULL);
  2607. rtp->rtcp->sr_count++;
  2608. rtp->rtcp->lastsrtxcount = rtp->txcount;
  2609. if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
  2610. ast_verbose("* Sent RTCP SR to %s:%d\n", ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port));
  2611. ast_verbose(" Our SSRC: %u\n", rtp->ssrc);
  2612. ast_verbose(" Sent(NTP): %u.%010u\n", (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096);
  2613. ast_verbose(" Sent(RTP): %u\n", rtp->lastts);
  2614. ast_verbose(" Sent packets: %u\n", rtp->txcount);
  2615. ast_verbose(" Sent octets: %u\n", rtp->txoctetcount);
  2616. ast_verbose(" Report block:\n");
  2617. ast_verbose(" Fraction lost: %u\n", fraction);
  2618. ast_verbose(" Cumulative loss: %u\n", lost);
  2619. ast_verbose(" IA jitter: %.4f\n", rtp->rxjitter);
  2620. ast_verbose(" Their last SR: %u\n", rtp->rtcp->themrxlsr);
  2621. ast_verbose(" DLSR: %4.4f (sec)\n\n", (double)(ntohl(rtcpheader[12])/65536.0));
  2622. }
  2623. manager_event(EVENT_FLAG_REPORTING, "RTCPSent", "To: %s:%d\r\n"
  2624. "OurSSRC: %u\r\n"
  2625. "SentNTP: %u.%010u\r\n"
  2626. "SentRTP: %u\r\n"
  2627. "SentPackets: %u\r\n"
  2628. "SentOctets: %u\r\n"
  2629. "ReportBlock:\r\n"
  2630. "FractionLost: %u\r\n"
  2631. "CumulativeLoss: %u\r\n"
  2632. "IAJitter: %.4f\r\n"
  2633. "TheirLastSR: %u\r\n"
  2634. "DLSR: %4.4f (sec)\r\n",
  2635. ast_inet_ntoa(rtp->rtcp->them.sin_addr), ntohs(rtp->rtcp->them.sin_port),
  2636. rtp->ssrc,
  2637. (unsigned int)now.tv_sec, (unsigned int)now.tv_usec*4096,
  2638. rtp->lastts,
  2639. rtp->txcount,
  2640. rtp->txoctetcount,
  2641. fraction,
  2642. lost,
  2643. rtp->rxjitter,
  2644. rtp->rtcp->themrxlsr,
  2645. (double)(ntohl(rtcpheader[12])/65536.0));
  2646. return res;
  2647. }
  2648. /*! \brief Send RTCP recipient's report */
  2649. static int ast_rtcp_write_rr(const void *data)
  2650. {
  2651. struct ast_rtp *rtp = (struct ast_rtp *)data;
  2652. int res;
  2653. int len = 32;
  2654. unsigned int lost;
  2655. unsigned int extended;
  2656. unsigned int expected;
  2657. unsigned int expected_interval;
  2658. unsigned int received_interval;
  2659. int lost_interval;
  2660. struct timeval now;
  2661. unsigned int *rtcpheader;
  2662. char bdata[1024];
  2663. struct timeval dlsr;
  2664. int fraction;
  2665. if (!rtp || !rtp->rtcp || (&rtp->rtcp->them.sin_addr == 0))
  2666. return 0;
  2667. if (!rtp->rtcp->them.sin_addr.s_addr) {
  2668. ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted\n");
  2669. AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
  2670. return 0;
  2671. }
  2672. extended = rtp->cycles + rtp->lastrxseqno;
  2673. expected = extended - rtp->seedrxseqno + 1;
  2674. lost = expected - rtp->rxcount;
  2675. expected_interval = expected - rtp->rtcp->expected_prior;
  2676. rtp->rtcp->expected_prior = expected;
  2677. received_interval = rtp->rxcount - rtp->rtcp->received_prior;
  2678. rtp->rtcp->received_prior = rtp->rxcount;
  2679. lost_interval = expected_interval - received_interval;
  2680. if (expected_interval == 0 || lost_interval <= 0)
  2681. fraction = 0;
  2682. else
  2683. fraction = (lost_interval << 8) / expected_interval;
  2684. gettimeofday(&now, NULL);
  2685. timersub(&now, &rtp->rtcp->rxlsr, &dlsr);
  2686. rtcpheader = (unsigned int *)bdata;
  2687. rtcpheader[0] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_RR << 16) | ((len/4)-1));
  2688. rtcpheader[1] = htonl(rtp->ssrc);
  2689. rtcpheader[2] = htonl(rtp->themssrc);
  2690. rtcpheader[3] = htonl(((fraction & 0xff) << 24) | (lost & 0xffffff));
  2691. rtcpheader[4] = htonl((rtp->cycles) | ((rtp->lastrxseqno & 0xffff)));
  2692. rtcpheader[5] = htonl((unsigned int)(rtp->rxjitter * 65536.));
  2693. rtcpheader[6] = htonl(rtp->rtcp->themrxlsr);
  2694. rtcpheader[7] = htonl((((dlsr.tv_sec * 1000) + (dlsr.tv_usec / 1000)) * 65536) / 1000);
  2695. if (rtp->rtcp->sendfur) {
  2696. rtcpheader[8] = htonl((2 << 30) | (0 << 24) | (RTCP_PT_FUR << 16) | 1); /* Header from page 36 in RFC 3550 */
  2697. rtcpheader[9] = htonl(rtp->ssrc); /* Our SSRC */
  2698. len += 8;
  2699. rtp->rtcp->sendfur = 0;
  2700. }
  2701. /*! \note Insert SDES here. Probably should make SDES text equal to mimetypes[code].type (not subtype 'cos
  2702. it can change mid call, and SDES can't) */
  2703. rtcpheader[len/4] = htonl((2 << 30) | (1 << 24) | (RTCP_PT_SDES << 16) | 2);
  2704. rtcpheader[(len/4)+1] = htonl(rtp->ssrc); /* Our SSRC */
  2705. rtcpheader[(len/4)+2] = htonl(0x01 << 24); /* Empty for the moment */
  2706. len += 12;
  2707. res = sendto(rtp->rtcp->s, (unsigned int *)rtcpheader, len, 0, (struct sockaddr *)&rtp->rtcp->them, sizeof(rtp->rtcp->them));
  2708. if (res < 0) {
  2709. ast_log(LOG_ERROR, "RTCP RR transmission error, rtcp halted: %s\n",strerror(errno));
  2710. /* Remove the scheduler */
  2711. AST_SCHED_DEL(rtp->sched, rtp->rtcp->schedid);
  2712. return 0;
  2713. }
  2714. rtp->rtcp->rr_count++;
  2715. if (rtcp_debug_test_addr(&rtp->rtcp->them)) {
  2716. ast_verbose("\n* Sending RTCP RR to %s:%d\n"
  2717. " Our SSRC: %u\nTheir SSRC: %u\niFraction lost: %d\nCumulative loss: %u\n"
  2718. " IA jitter: %.4f\n"
  2719. " Their last SR: %u\n"
  2720. " DLSR: %4.4f (sec)\n\n",
  2721. ast_inet_ntoa(rtp->rtcp->them.sin_addr),
  2722. ntohs(rtp->rtcp->them.sin_port),
  2723. rtp->ssrc, rtp->themssrc, fraction, lost,
  2724. rtp->rxjitter,
  2725. rtp->rtcp->themrxlsr,
  2726. (double)(ntohl(rtcpheader[7])/65536.0));
  2727. }
  2728. return res;
  2729. }
  2730. /*! \brief Write and RTCP packet to the far end
  2731. * \note Decide if we are going to send an SR (with Reception Block) or RR
  2732. * RR is sent if we have not sent any rtp packets in the previous interval */
  2733. static int ast_rtcp_write(const void *data)
  2734. {
  2735. struct ast_rtp *rtp = (struct ast_rtp *)data;
  2736. int res;
  2737. if (!rtp || !rtp->rtcp)
  2738. return 0;
  2739. if (rtp->txcount > rtp->rtcp->lastsrtxcount)
  2740. res = ast_rtcp_write_sr(data);
  2741. else
  2742. res = ast_rtcp_write_rr(data);
  2743. return res;
  2744. }
  2745. /*! \brief generate comfort noice (CNG) */
  2746. int ast_rtp_sendcng(struct ast_rtp *rtp, int level)
  2747. {
  2748. unsigned int *rtpheader;
  2749. int hdrlen = 12;
  2750. int res;
  2751. int payload;
  2752. char data[256];
  2753. level = 127 - (level & 0x7f);
  2754. payload = ast_rtp_lookup_code(rtp, 0, AST_RTP_CN);
  2755. /* If we have no peer, return immediately */
  2756. if (!rtp->them.sin_addr.s_addr)
  2757. return 0;
  2758. rtp->dtmfmute = ast_tvadd(ast_tvnow(), ast_tv(0, 500000));
  2759. /* Get a pointer to the header */
  2760. rtpheader = (unsigned int *)data;
  2761. rtpheader[0] = htonl((2 << 30) | (1 << 23) | (payload << 16) | (rtp->seqno++));
  2762. rtpheader[1] = htonl(rtp->lastts);
  2763. rtpheader[2] = htonl(rtp->ssrc);
  2764. data[12] = level;
  2765. if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
  2766. res = sendto(rtp->s, (void *)rtpheader, hdrlen + 1, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
  2767. if (res <0)
  2768. ast_log(LOG_ERROR, "RTP Comfort Noise Transmission error to %s:%d: %s\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
  2769. if (rtp_debug_test_addr(&rtp->them))
  2770. ast_verbose("Sent Comfort Noise RTP packet to %s:%u (type %d, seq %u, ts %u, len %d)\n"
  2771. , ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), payload, rtp->seqno, rtp->lastts,res - hdrlen);
  2772. }
  2773. return 0;
  2774. }
  2775. /*! \brief Write RTP packet with audio or video media frames into UDP packet */
  2776. static int ast_rtp_raw_write(struct ast_rtp *rtp, struct ast_frame *f, int codec)
  2777. {
  2778. unsigned char *rtpheader;
  2779. int hdrlen = 12;
  2780. int res;
  2781. unsigned int ms;
  2782. int pred;
  2783. int mark = 0;
  2784. int rate = rtp_get_rate(f->subclass) / 1000;
  2785. if (f->subclass == AST_FORMAT_G722) {
  2786. f->samples /= 2;
  2787. }
  2788. if (rtp->sending_digit) {
  2789. return 0;
  2790. }
  2791. ms = calc_txstamp(rtp, &f->delivery);
  2792. /* Default prediction */
  2793. if (f->frametype == AST_FRAME_VOICE) {
  2794. pred = rtp->lastts + f->samples;
  2795. /* Re-calculate last TS */
  2796. rtp->lastts = rtp->lastts + ms * rate;
  2797. if (ast_tvzero(f->delivery)) {
  2798. /* If this isn't an absolute delivery time, Check if it is close to our prediction,
  2799. and if so, go with our prediction */
  2800. if (abs(rtp->lastts - pred) < MAX_TIMESTAMP_SKEW)
  2801. rtp->lastts = pred;
  2802. else {
  2803. ast_debug(3, "Difference is %d, ms is %d\n", abs(rtp->lastts - pred), ms);
  2804. mark = 1;
  2805. }
  2806. }
  2807. } else if (f->frametype == AST_FRAME_VIDEO) {
  2808. mark = f->subclass & 0x1;
  2809. pred = rtp->lastovidtimestamp + f->samples;
  2810. /* Re-calculate last TS */
  2811. rtp->lastts = rtp->lastts + ms * 90;
  2812. /* If it's close to our prediction, go for it */
  2813. if (ast_tvzero(f->delivery)) {
  2814. if (abs(rtp->lastts - pred) < 7200) {
  2815. rtp->lastts = pred;
  2816. rtp->lastovidtimestamp += f->samples;
  2817. } else {
  2818. ast_debug(3, "Difference is %d, ms is %d (%d), pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, ms * 90, rtp->lastts, pred, f->samples);
  2819. rtp->lastovidtimestamp = rtp->lastts;
  2820. }
  2821. }
  2822. } else {
  2823. pred = rtp->lastotexttimestamp + f->samples;
  2824. /* Re-calculate last TS */
  2825. rtp->lastts = rtp->lastts + ms;
  2826. /* If it's close to our prediction, go for it */
  2827. if (ast_tvzero(f->delivery)) {
  2828. if (abs(rtp->lastts - pred) < 7200) {
  2829. rtp->lastts = pred;
  2830. rtp->lastotexttimestamp += f->samples;
  2831. } else {
  2832. ast_debug(3, "Difference is %d, ms is %d, pred/ts/samples %d/%d/%d\n", abs(rtp->lastts - pred), ms, rtp->lastts, pred, f->samples);
  2833. rtp->lastotexttimestamp = rtp->lastts;
  2834. }
  2835. }
  2836. }
  2837. /* If we have been explicitly told to set the marker bit do so */
  2838. if (rtp->set_marker_bit) {
  2839. mark = 1;
  2840. rtp->set_marker_bit = 0;
  2841. }
  2842. /* If the timestamp for non-digit packets has moved beyond the timestamp
  2843. for digits, update the digit timestamp.
  2844. */
  2845. if (rtp->lastts > rtp->lastdigitts)
  2846. rtp->lastdigitts = rtp->lastts;
  2847. if (ast_test_flag(f, AST_FRFLAG_HAS_TIMING_INFO))
  2848. rtp->lastts = f->ts * rate;
  2849. /* Get a pointer to the header */
  2850. rtpheader = (unsigned char *)(f->data - hdrlen);
  2851. put_unaligned_uint32(rtpheader, htonl((2 << 30) | (codec << 16) | (rtp->seqno) | (mark << 23)));
  2852. put_unaligned_uint32(rtpheader + 4, htonl(rtp->lastts));
  2853. put_unaligned_uint32(rtpheader + 8, htonl(rtp->ssrc));
  2854. if (rtp->them.sin_port && rtp->them.sin_addr.s_addr) {
  2855. res = sendto(rtp->s, (void *)rtpheader, f->datalen + hdrlen, 0, (struct sockaddr *)&rtp->them, sizeof(rtp->them));
  2856. if (res < 0) {
  2857. if (!rtp->nat || (rtp->nat && (ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_ACTIVE))) {
  2858. ast_debug(1, "RTP Transmission error of packet %d to %s:%d: %s\n", rtp->seqno, ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), strerror(errno));
  2859. } else if (((ast_test_flag(rtp, FLAG_NAT_ACTIVE) == FLAG_NAT_INACTIVE) || rtpdebug) && !ast_test_flag(rtp, FLAG_NAT_INACTIVE_NOWARN)) {
  2860. /* Only give this error message once if we are not RTP debugging */
  2861. if (option_debug || rtpdebug)
  2862. ast_debug(0, "RTP NAT: Can't write RTP to private address %s:%d, waiting for other end to send audio...\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
  2863. ast_set_flag(rtp, FLAG_NAT_INACTIVE_NOWARN);
  2864. }
  2865. } else {
  2866. rtp->txcount++;
  2867. rtp->txoctetcount +=(res - hdrlen);
  2868. /* Do not schedule RR if RTCP isn't run */
  2869. if (rtp->rtcp && rtp->rtcp->them.sin_addr.s_addr && rtp->rtcp->schedid < 1) {
  2870. rtp->rtcp->schedid = ast_sched_add(rtp->sched, ast_rtcp_calc_interval(rtp), ast_rtcp_write, rtp);
  2871. }
  2872. }
  2873. if (rtp_debug_test_addr(&rtp->them))
  2874. ast_verbose("Sent RTP packet to %s:%u (type %-2.2d, seq %-6.6u, ts %-6.6u, len %-6.6u)\n",
  2875. ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port), codec, rtp->seqno, rtp->lastts,res - hdrlen);
  2876. }
  2877. rtp->seqno++;
  2878. return 0;
  2879. }
  2880. void ast_rtp_codec_setpref(struct ast_rtp *rtp, struct ast_codec_pref *prefs)
  2881. {
  2882. struct ast_format_list current_format_old, current_format_new;
  2883. /* if no packets have been sent through this session yet, then
  2884. * changing preferences does not require any extra work
  2885. */
  2886. if (rtp->lasttxformat == 0) {
  2887. rtp->pref = *prefs;
  2888. return;
  2889. }
  2890. current_format_old = ast_codec_pref_getsize(&rtp->pref, rtp->lasttxformat);
  2891. rtp->pref = *prefs;
  2892. current_format_new = ast_codec_pref_getsize(&rtp->pref, rtp->lasttxformat);
  2893. /* if the framing desired for the current format has changed, we may have to create
  2894. * or adjust the smoother for this session
  2895. */
  2896. if ((current_format_new.inc_ms != 0) &&
  2897. (current_format_new.cur_ms != current_format_old.cur_ms)) {
  2898. int new_size = (current_format_new.cur_ms * current_format_new.fr_len) / current_format_new.inc_ms;
  2899. if (rtp->smoother) {
  2900. ast_smoother_reconfigure(rtp->smoother, new_size);
  2901. if (option_debug) {
  2902. ast_log(LOG_DEBUG, "Adjusted smoother to %d ms and %d bytes\n", current_format_new.cur_ms, new_size);
  2903. }
  2904. } else {
  2905. if (!(rtp->smoother = ast_smoother_new(new_size))) {
  2906. ast_log(LOG_WARNING, "Unable to create smoother: format: %d ms: %d len: %d\n", rtp->lasttxformat, current_format_new.cur_ms, new_size);
  2907. return;
  2908. }
  2909. if (current_format_new.flags) {
  2910. ast_smoother_set_flags(rtp->smoother, current_format_new.flags);
  2911. }
  2912. if (option_debug) {
  2913. ast_log(LOG_DEBUG, "Created smoother: format: %d ms: %d len: %d\n", rtp->lasttxformat, current_format_new.cur_ms, new_size);
  2914. }
  2915. }
  2916. }
  2917. }
  2918. struct ast_codec_pref *ast_rtp_codec_getpref(struct ast_rtp *rtp)
  2919. {
  2920. return &rtp->pref;
  2921. }
  2922. int ast_rtp_codec_getformat(int pt)
  2923. {
  2924. if (pt < 0 || pt >= MAX_RTP_PT)
  2925. return 0; /* bogus payload type */
  2926. if (static_RTP_PT[pt].isAstFormat)
  2927. return static_RTP_PT[pt].code;
  2928. else
  2929. return 0;
  2930. }
  2931. int ast_rtp_write(struct ast_rtp *rtp, struct ast_frame *_f)
  2932. {
  2933. struct ast_frame *f;
  2934. int codec;
  2935. int hdrlen = 12;
  2936. int subclass;
  2937. /* If we have no peer, return immediately */
  2938. if (!rtp->them.sin_addr.s_addr)
  2939. return 0;
  2940. /* If there is no data length, return immediately */
  2941. if (!_f->datalen)
  2942. return 0;
  2943. /* Make sure we have enough space for RTP header */
  2944. if ((_f->frametype != AST_FRAME_VOICE) && (_f->frametype != AST_FRAME_VIDEO) && (_f->frametype != AST_FRAME_TEXT)) {
  2945. ast_log(LOG_WARNING, "RTP can only send voice, video and text\n");
  2946. return -1;
  2947. }
  2948. /* The bottom bit of a video subclass contains the marker bit */
  2949. subclass = _f->subclass;
  2950. if (_f->frametype == AST_FRAME_VIDEO)
  2951. subclass &= ~0x1;
  2952. codec = ast_rtp_lookup_code(rtp, 1, subclass);
  2953. if (codec < 0) {
  2954. ast_log(LOG_WARNING, "Don't know how to send format %s packets with RTP\n", ast_getformatname(_f->subclass));
  2955. return -1;
  2956. }
  2957. if (rtp->lasttxformat != subclass) {
  2958. /* New format, reset the smoother */
  2959. ast_debug(1, "Ooh, format changed from %s to %s\n", ast_getformatname(rtp->lasttxformat), ast_getformatname(subclass));
  2960. rtp->lasttxformat = subclass;
  2961. if (rtp->smoother)
  2962. ast_smoother_free(rtp->smoother);
  2963. rtp->smoother = NULL;
  2964. }
  2965. if (!rtp->smoother && subclass != AST_FORMAT_SPEEX && subclass != AST_FORMAT_G723_1) {
  2966. struct ast_format_list fmt = ast_codec_pref_getsize(&rtp->pref, subclass);
  2967. if (fmt.inc_ms) { /* if codec parameters is set / avoid division by zero */
  2968. if (!(rtp->smoother = ast_smoother_new((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms))) {
  2969. ast_log(LOG_WARNING, "Unable to create smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
  2970. return -1;
  2971. }
  2972. if (fmt.flags)
  2973. ast_smoother_set_flags(rtp->smoother, fmt.flags);
  2974. ast_debug(1, "Created smoother: format: %d ms: %d len: %d\n", subclass, fmt.cur_ms, ((fmt.cur_ms * fmt.fr_len) / fmt.inc_ms));
  2975. }
  2976. }
  2977. if (rtp->smoother) {
  2978. if (ast_smoother_test_flag(rtp->smoother, AST_SMOOTHER_FLAG_BE)) {
  2979. ast_smoother_feed_be(rtp->smoother, _f);
  2980. } else {
  2981. ast_smoother_feed(rtp->smoother, _f);
  2982. }
  2983. while ((f = ast_smoother_read(rtp->smoother)) && (f->data)) {
  2984. ast_rtp_raw_write(rtp, f, codec);
  2985. }
  2986. } else {
  2987. /* Don't buffer outgoing frames; send them one-per-packet: */
  2988. if (_f->offset < hdrlen)
  2989. f = ast_frdup(_f); /*! \bug XXX this might never be free'd. Why do we do this? */
  2990. else
  2991. f = _f;
  2992. if (f->data)
  2993. ast_rtp_raw_write(rtp, f, codec);
  2994. if (f != _f)
  2995. ast_frfree(f);
  2996. }
  2997. return 0;
  2998. }
  2999. /*! \brief Unregister interface to channel driver */
  3000. void ast_rtp_proto_unregister(struct ast_rtp_protocol *proto)
  3001. {
  3002. AST_RWLIST_WRLOCK(&protos);
  3003. AST_RWLIST_REMOVE(&protos, proto, list);
  3004. AST_RWLIST_UNLOCK(&protos);
  3005. }
  3006. /*! \brief Register interface to channel driver */
  3007. int ast_rtp_proto_register(struct ast_rtp_protocol *proto)
  3008. {
  3009. struct ast_rtp_protocol *cur;
  3010. AST_RWLIST_WRLOCK(&protos);
  3011. AST_RWLIST_TRAVERSE(&protos, cur, list) {
  3012. if (!strcmp(cur->type, proto->type)) {
  3013. ast_log(LOG_WARNING, "Tried to register same protocol '%s' twice\n", cur->type);
  3014. AST_RWLIST_UNLOCK(&protos);
  3015. return -1;
  3016. }
  3017. }
  3018. AST_RWLIST_INSERT_HEAD(&protos, proto, list);
  3019. AST_RWLIST_UNLOCK(&protos);
  3020. return 0;
  3021. }
  3022. /*! \brief Bridge loop for true native bridge (reinvite) */
  3023. static enum ast_bridge_result bridge_native_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp *p0, struct ast_rtp *p1, struct ast_rtp *vp0, struct ast_rtp *vp1, struct ast_rtp *tp0, struct ast_rtp *tp1, struct ast_rtp_protocol *pr0, struct ast_rtp_protocol *pr1, int codec0, int codec1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
  3024. {
  3025. struct ast_frame *fr = NULL;
  3026. struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
  3027. int oldcodec0 = codec0, oldcodec1 = codec1;
  3028. struct sockaddr_in ac1 = {0,}, vac1 = {0,}, tac1 = {0,}, ac0 = {0,}, vac0 = {0,}, tac0 = {0,};
  3029. struct sockaddr_in t1 = {0,}, vt1 = {0,}, tt1 = {0,}, t0 = {0,}, vt0 = {0,}, tt0 = {0,};
  3030. /* Set it up so audio goes directly between the two endpoints */
  3031. /* Test the first channel */
  3032. if (!(pr0->set_rtp_peer(c0, p1, vp1, tp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))) {
  3033. ast_rtp_get_peer(p1, &ac1);
  3034. if (vp1)
  3035. ast_rtp_get_peer(vp1, &vac1);
  3036. if (tp1)
  3037. ast_rtp_get_peer(tp1, &tac1);
  3038. } else
  3039. ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c0->name, c1->name);
  3040. /* Test the second channel */
  3041. if (!(pr1->set_rtp_peer(c1, p0, vp0, tp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))) {
  3042. ast_rtp_get_peer(p0, &ac0);
  3043. if (vp0)
  3044. ast_rtp_get_peer(vp0, &vac0);
  3045. if (tp0)
  3046. ast_rtp_get_peer(tp0, &tac0);
  3047. } else
  3048. ast_log(LOG_WARNING, "Channel '%s' failed to talk to '%s'\n", c1->name, c0->name);
  3049. /* Now we can unlock and move into our loop */
  3050. ast_channel_unlock(c0);
  3051. ast_channel_unlock(c1);
  3052. ast_poll_channel_add(c0, c1);
  3053. /* Throw our channels into the structure and enter the loop */
  3054. cs[0] = c0;
  3055. cs[1] = c1;
  3056. cs[2] = NULL;
  3057. for (;;) {
  3058. /* Check if anything changed */
  3059. if ((c0->tech_pvt != pvt0) ||
  3060. (c1->tech_pvt != pvt1) ||
  3061. (c0->masq || c0->masqr || c1->masq || c1->masqr) ||
  3062. (c0->monitor || c0->audiohooks || c1->monitor || c1->audiohooks)) {
  3063. ast_debug(1, "Oooh, something is weird, backing out\n");
  3064. if (c0->tech_pvt == pvt0)
  3065. if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
  3066. ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
  3067. if (c1->tech_pvt == pvt1)
  3068. if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
  3069. ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
  3070. ast_poll_channel_del(c0, c1);
  3071. return AST_BRIDGE_RETRY;
  3072. }
  3073. /* Check if they have changed their address */
  3074. ast_rtp_get_peer(p1, &t1);
  3075. if (vp1)
  3076. ast_rtp_get_peer(vp1, &vt1);
  3077. if (tp1)
  3078. ast_rtp_get_peer(tp1, &tt1);
  3079. if (pr1->get_codec)
  3080. codec1 = pr1->get_codec(c1);
  3081. ast_rtp_get_peer(p0, &t0);
  3082. if (vp0)
  3083. ast_rtp_get_peer(vp0, &vt0);
  3084. if (tp0)
  3085. ast_rtp_get_peer(tp0, &tt0);
  3086. if (pr0->get_codec)
  3087. codec0 = pr0->get_codec(c0);
  3088. if ((inaddrcmp(&t1, &ac1)) ||
  3089. (vp1 && inaddrcmp(&vt1, &vac1)) ||
  3090. (tp1 && inaddrcmp(&tt1, &tac1)) ||
  3091. (codec1 != oldcodec1)) {
  3092. ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
  3093. c1->name, ast_inet_ntoa(t1.sin_addr), ntohs(t1.sin_port), codec1);
  3094. ast_debug(2, "Oooh, '%s' changed end vaddress to %s:%d (format %d)\n",
  3095. c1->name, ast_inet_ntoa(vt1.sin_addr), ntohs(vt1.sin_port), codec1);
  3096. ast_debug(2, "Oooh, '%s' changed end taddress to %s:%d (format %d)\n",
  3097. c1->name, ast_inet_ntoa(tt1.sin_addr), ntohs(tt1.sin_port), codec1);
  3098. ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
  3099. c1->name, ast_inet_ntoa(ac1.sin_addr), ntohs(ac1.sin_port), oldcodec1);
  3100. ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
  3101. c1->name, ast_inet_ntoa(vac1.sin_addr), ntohs(vac1.sin_port), oldcodec1);
  3102. ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
  3103. c1->name, ast_inet_ntoa(tac1.sin_addr), ntohs(tac1.sin_port), oldcodec1);
  3104. if (pr0->set_rtp_peer(c0, t1.sin_addr.s_addr ? p1 : NULL, vt1.sin_addr.s_addr ? vp1 : NULL, tt1.sin_addr.s_addr ? tp1 : NULL, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE)))
  3105. ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c0->name, c1->name);
  3106. memcpy(&ac1, &t1, sizeof(ac1));
  3107. memcpy(&vac1, &vt1, sizeof(vac1));
  3108. memcpy(&tac1, &tt1, sizeof(tac1));
  3109. oldcodec1 = codec1;
  3110. }
  3111. if ((inaddrcmp(&t0, &ac0)) ||
  3112. (vp0 && inaddrcmp(&vt0, &vac0)) ||
  3113. (tp0 && inaddrcmp(&tt0, &tac0)) ||
  3114. (codec0 != oldcodec0)) {
  3115. ast_debug(2, "Oooh, '%s' changed end address to %s:%d (format %d)\n",
  3116. c0->name, ast_inet_ntoa(t0.sin_addr), ntohs(t0.sin_port), codec0);
  3117. ast_debug(2, "Oooh, '%s' was %s:%d/(format %d)\n",
  3118. c0->name, ast_inet_ntoa(ac0.sin_addr), ntohs(ac0.sin_port), oldcodec0);
  3119. if (pr1->set_rtp_peer(c1, t0.sin_addr.s_addr ? p0 : NULL, vt0.sin_addr.s_addr ? vp0 : NULL, tt0.sin_addr.s_addr ? tp0 : NULL, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE)))
  3120. ast_log(LOG_WARNING, "Channel '%s' failed to update to '%s'\n", c1->name, c0->name);
  3121. memcpy(&ac0, &t0, sizeof(ac0));
  3122. memcpy(&vac0, &vt0, sizeof(vac0));
  3123. memcpy(&tac0, &tt0, sizeof(tac0));
  3124. oldcodec0 = codec0;
  3125. }
  3126. /* Wait for frame to come in on the channels */
  3127. if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
  3128. if (!timeoutms) {
  3129. if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
  3130. ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
  3131. if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
  3132. ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
  3133. return AST_BRIDGE_RETRY;
  3134. }
  3135. ast_debug(1, "Ooh, empty read...\n");
  3136. if (ast_check_hangup(c0) || ast_check_hangup(c1))
  3137. break;
  3138. continue;
  3139. }
  3140. fr = ast_read(who);
  3141. other = (who == c0) ? c1 : c0;
  3142. if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
  3143. (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) ||
  3144. ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))))) {
  3145. /* Break out of bridge */
  3146. *fo = fr;
  3147. *rc = who;
  3148. ast_debug(1, "Oooh, got a %s\n", fr ? "digit" : "hangup");
  3149. if (c0->tech_pvt == pvt0)
  3150. if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
  3151. ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
  3152. if (c1->tech_pvt == pvt1)
  3153. if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
  3154. ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
  3155. ast_poll_channel_del(c0, c1);
  3156. return AST_BRIDGE_COMPLETE;
  3157. } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
  3158. if ((fr->subclass == AST_CONTROL_HOLD) ||
  3159. (fr->subclass == AST_CONTROL_UNHOLD) ||
  3160. (fr->subclass == AST_CONTROL_VIDUPDATE) ||
  3161. (fr->subclass == AST_CONTROL_SRCUPDATE) ||
  3162. (fr->subclass == AST_CONTROL_T38_PARAMETERS)) {
  3163. if (fr->subclass == AST_CONTROL_HOLD) {
  3164. /* If we someone went on hold we want the other side to reinvite back to us */
  3165. if (who == c0)
  3166. pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0);
  3167. else
  3168. pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0);
  3169. } else if (fr->subclass == AST_CONTROL_UNHOLD) {
  3170. /* If they went off hold they should go back to being direct */
  3171. if (who == c0)
  3172. pr1->set_rtp_peer(c1, p0, vp0, tp0, codec0, ast_test_flag(p0, FLAG_NAT_ACTIVE));
  3173. else
  3174. pr0->set_rtp_peer(c0, p1, vp1, tp1, codec1, ast_test_flag(p1, FLAG_NAT_ACTIVE));
  3175. }
  3176. /* Update local address information */
  3177. ast_rtp_get_peer(p0, &t0);
  3178. memcpy(&ac0, &t0, sizeof(ac0));
  3179. ast_rtp_get_peer(p1, &t1);
  3180. memcpy(&ac1, &t1, sizeof(ac1));
  3181. /* Update codec information */
  3182. if (pr0->get_codec && c0->tech_pvt)
  3183. oldcodec0 = codec0 = pr0->get_codec(c0);
  3184. if (pr1->get_codec && c1->tech_pvt)
  3185. oldcodec1 = codec1 = pr1->get_codec(c1);
  3186. ast_indicate_data(other, fr->subclass, fr->data, fr->datalen);
  3187. ast_frfree(fr);
  3188. } else {
  3189. *fo = fr;
  3190. *rc = who;
  3191. ast_debug(1, "Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
  3192. return AST_BRIDGE_COMPLETE;
  3193. }
  3194. } else {
  3195. if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
  3196. (fr->frametype == AST_FRAME_DTMF_END) ||
  3197. (fr->frametype == AST_FRAME_VOICE) ||
  3198. (fr->frametype == AST_FRAME_VIDEO) ||
  3199. (fr->frametype == AST_FRAME_IMAGE) ||
  3200. (fr->frametype == AST_FRAME_HTML) ||
  3201. (fr->frametype == AST_FRAME_MODEM) ||
  3202. (fr->frametype == AST_FRAME_TEXT)) {
  3203. ast_write(other, fr);
  3204. }
  3205. ast_frfree(fr);
  3206. }
  3207. /* Swap priority */
  3208. #ifndef HAVE_EPOLL
  3209. cs[2] = cs[0];
  3210. cs[0] = cs[1];
  3211. cs[1] = cs[2];
  3212. #endif
  3213. }
  3214. ast_poll_channel_del(c0, c1);
  3215. if (pr0->set_rtp_peer(c0, NULL, NULL, NULL, 0, 0))
  3216. ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c0->name);
  3217. if (pr1->set_rtp_peer(c1, NULL, NULL, NULL, 0, 0))
  3218. ast_log(LOG_WARNING, "Channel '%s' failed to break RTP bridge\n", c1->name);
  3219. return AST_BRIDGE_FAILED;
  3220. }
  3221. /*! \brief P2P RTP Callback */
  3222. #ifdef P2P_INTENSE
  3223. static int p2p_rtp_callback(int *id, int fd, short events, void *cbdata)
  3224. {
  3225. int res = 0, hdrlen = 12;
  3226. struct sockaddr_in sin;
  3227. socklen_t len;
  3228. unsigned int *header;
  3229. struct ast_rtp *rtp = cbdata, *bridged = NULL;
  3230. if (!rtp)
  3231. return 1;
  3232. len = sizeof(sin);
  3233. if ((res = recvfrom(fd, rtp->rawdata + AST_FRIENDLY_OFFSET, sizeof(rtp->rawdata) - AST_FRIENDLY_OFFSET, 0, (struct sockaddr *)&sin, &len)) < 0)
  3234. return 1;
  3235. header = (unsigned int *)(rtp->rawdata + AST_FRIENDLY_OFFSET);
  3236. /* If NAT support is turned on, then see if we need to change their address */
  3237. if ((rtp->nat) &&
  3238. ((rtp->them.sin_addr.s_addr != sin.sin_addr.s_addr) ||
  3239. (rtp->them.sin_port != sin.sin_port))) {
  3240. rtp->them = sin;
  3241. rtp->rxseqno = 0;
  3242. ast_set_flag(rtp, FLAG_NAT_ACTIVE);
  3243. if (option_debug || rtpdebug)
  3244. ast_debug(0, "P2P RTP NAT: Got audio from other end. Now sending to address %s:%d\n", ast_inet_ntoa(rtp->them.sin_addr), ntohs(rtp->them.sin_port));
  3245. }
  3246. /* Write directly out to other RTP stream if bridged */
  3247. if ((bridged = ast_rtp_get_bridged(rtp)))
  3248. bridge_p2p_rtp_write(rtp, bridged, header, res, hdrlen);
  3249. return 1;
  3250. }
  3251. /*! \brief Helper function to switch a channel and RTP stream into callback mode */
  3252. static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
  3253. {
  3254. /* If we need DTMF, are looking for STUN, or we have no IO structure then we can't do direct callback */
  3255. if (ast_test_flag(rtp, FLAG_P2P_NEED_DTMF) || ast_test_flag(rtp, FLAG_HAS_STUN) || !rtp->io)
  3256. return 0;
  3257. /* If the RTP structure is already in callback mode, remove it temporarily */
  3258. if (rtp->ioid) {
  3259. ast_io_remove(rtp->io, rtp->ioid);
  3260. rtp->ioid = NULL;
  3261. }
  3262. /* Steal the file descriptors from the channel */
  3263. chan->fds[0] = -1;
  3264. /* Now, fire up callback mode */
  3265. iod[0] = ast_io_add(rtp->io, ast_rtp_fd(rtp), p2p_rtp_callback, AST_IO_IN, rtp);
  3266. return 1;
  3267. }
  3268. #else
  3269. static int p2p_callback_enable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
  3270. {
  3271. return 0;
  3272. }
  3273. #endif
  3274. /*! \brief Helper function to switch a channel and RTP stream out of callback mode */
  3275. static int p2p_callback_disable(struct ast_channel *chan, struct ast_rtp *rtp, int **iod)
  3276. {
  3277. ast_channel_lock(chan);
  3278. /* Remove the callback from the IO context */
  3279. ast_io_remove(rtp->io, iod[0]);
  3280. /* Restore file descriptors */
  3281. chan->fds[0] = ast_rtp_fd(rtp);
  3282. ast_channel_unlock(chan);
  3283. /* Restore callback mode if previously used */
  3284. if (ast_test_flag(rtp, FLAG_CALLBACK_MODE))
  3285. rtp->ioid = ast_io_add(rtp->io, ast_rtp_fd(rtp), rtpread, AST_IO_IN, rtp);
  3286. return 0;
  3287. }
  3288. /*! \brief Helper function that sets what an RTP structure is bridged to */
  3289. static void p2p_set_bridge(struct ast_rtp *rtp0, struct ast_rtp *rtp1)
  3290. {
  3291. rtp_bridge_lock(rtp0);
  3292. rtp0->bridged = rtp1;
  3293. rtp_bridge_unlock(rtp0);
  3294. }
  3295. /*! \brief Bridge loop for partial native bridge (packet2packet)
  3296. In p2p mode, Asterisk is a very basic RTP proxy, just forwarding whatever
  3297. rtp/rtcp we get in to the channel.
  3298. \note this currently only works for Audio
  3299. */
  3300. static enum ast_bridge_result bridge_p2p_loop(struct ast_channel *c0, struct ast_channel *c1, struct ast_rtp *p0, struct ast_rtp *p1, int timeoutms, int flags, struct ast_frame **fo, struct ast_channel **rc, void *pvt0, void *pvt1)
  3301. {
  3302. struct ast_frame *fr = NULL;
  3303. struct ast_channel *who = NULL, *other = NULL, *cs[3] = {NULL, };
  3304. int *p0_iod[2] = {NULL, NULL}, *p1_iod[2] = {NULL, NULL};
  3305. int p0_callback = 0, p1_callback = 0;
  3306. enum ast_bridge_result res = AST_BRIDGE_FAILED;
  3307. /* Okay, setup each RTP structure to do P2P forwarding */
  3308. ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
  3309. p2p_set_bridge(p0, p1);
  3310. ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
  3311. p2p_set_bridge(p1, p0);
  3312. /* Activate callback modes if possible */
  3313. p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
  3314. p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
  3315. /* Now let go of the channel locks and be on our way */
  3316. ast_channel_unlock(c0);
  3317. ast_channel_unlock(c1);
  3318. ast_poll_channel_add(c0, c1);
  3319. /* Go into a loop forwarding frames until we don't need to anymore */
  3320. cs[0] = c0;
  3321. cs[1] = c1;
  3322. cs[2] = NULL;
  3323. for (;;) {
  3324. /* If the underlying formats have changed force this bridge to break */
  3325. if ((c0->rawreadformat != c1->rawwriteformat) || (c1->rawreadformat != c0->rawwriteformat)) {
  3326. ast_debug(3, "p2p-rtp-bridge: Oooh, formats changed, backing out\n");
  3327. res = AST_BRIDGE_FAILED_NOWARN;
  3328. break;
  3329. }
  3330. /* Check if anything changed */
  3331. if ((c0->tech_pvt != pvt0) ||
  3332. (c1->tech_pvt != pvt1) ||
  3333. (c0->masq || c0->masqr || c1->masq || c1->masqr) ||
  3334. (c0->monitor || c0->audiohooks || c1->monitor || c1->audiohooks)) {
  3335. ast_debug(3, "p2p-rtp-bridge: Oooh, something is weird, backing out\n");
  3336. /* If a masquerade needs to happen we have to try to read in a frame so that it actually happens. Without this we risk being called again and going into a loop */
  3337. if ((c0->masq || c0->masqr) && (fr = ast_read(c0)))
  3338. ast_frfree(fr);
  3339. if ((c1->masq || c1->masqr) && (fr = ast_read(c1)))
  3340. ast_frfree(fr);
  3341. res = AST_BRIDGE_RETRY;
  3342. break;
  3343. }
  3344. /* Wait on a channel to feed us a frame */
  3345. if (!(who = ast_waitfor_n(cs, 2, &timeoutms))) {
  3346. if (!timeoutms) {
  3347. res = AST_BRIDGE_RETRY;
  3348. break;
  3349. }
  3350. if (option_debug > 2)
  3351. ast_log(LOG_NOTICE, "p2p-rtp-bridge: Ooh, empty read...\n");
  3352. if (ast_check_hangup(c0) || ast_check_hangup(c1))
  3353. break;
  3354. continue;
  3355. }
  3356. /* Read in frame from channel */
  3357. fr = ast_read(who);
  3358. other = (who == c0) ? c1 : c0;
  3359. /* Depending on the frame we may need to break out of our bridge */
  3360. if (!fr || ((fr->frametype == AST_FRAME_DTMF_BEGIN || fr->frametype == AST_FRAME_DTMF_END) &&
  3361. ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) |
  3362. ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)))) {
  3363. /* Record received frame and who */
  3364. *fo = fr;
  3365. *rc = who;
  3366. ast_debug(3, "p2p-rtp-bridge: Ooh, got a %s\n", fr ? "digit" : "hangup");
  3367. res = AST_BRIDGE_COMPLETE;
  3368. break;
  3369. } else if ((fr->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
  3370. if ((fr->subclass == AST_CONTROL_HOLD) ||
  3371. (fr->subclass == AST_CONTROL_UNHOLD) ||
  3372. (fr->subclass == AST_CONTROL_VIDUPDATE) ||
  3373. (fr->subclass == AST_CONTROL_SRCUPDATE) ||
  3374. (fr->subclass == AST_CONTROL_T38_PARAMETERS)) {
  3375. /* If we are going on hold, then break callback mode and P2P bridging */
  3376. if (fr->subclass == AST_CONTROL_HOLD) {
  3377. if (p0_callback)
  3378. p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
  3379. if (p1_callback)
  3380. p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
  3381. p2p_set_bridge(p0, NULL);
  3382. p2p_set_bridge(p1, NULL);
  3383. } else if (fr->subclass == AST_CONTROL_UNHOLD) {
  3384. /* If we are off hold, then go back to callback mode and P2P bridging */
  3385. ast_clear_flag(p0, FLAG_P2P_SENT_MARK);
  3386. p2p_set_bridge(p0, p1);
  3387. ast_clear_flag(p1, FLAG_P2P_SENT_MARK);
  3388. p2p_set_bridge(p1, p0);
  3389. p0_callback = p2p_callback_enable(c0, p0, &p0_iod[0]);
  3390. p1_callback = p2p_callback_enable(c1, p1, &p1_iod[0]);
  3391. }
  3392. ast_indicate_data(other, fr->subclass, fr->data, fr->datalen);
  3393. ast_frfree(fr);
  3394. } else {
  3395. *fo = fr;
  3396. *rc = who;
  3397. ast_debug(3, "p2p-rtp-bridge: Got a FRAME_CONTROL (%d) frame on channel %s\n", fr->subclass, who->name);
  3398. res = AST_BRIDGE_COMPLETE;
  3399. break;
  3400. }
  3401. } else {
  3402. if ((fr->frametype == AST_FRAME_DTMF_BEGIN) ||
  3403. (fr->frametype == AST_FRAME_DTMF_END) ||
  3404. (fr->frametype == AST_FRAME_VOICE) ||
  3405. (fr->frametype == AST_FRAME_VIDEO) ||
  3406. (fr->frametype == AST_FRAME_IMAGE) ||
  3407. (fr->frametype == AST_FRAME_HTML) ||
  3408. (fr->frametype == AST_FRAME_MODEM) ||
  3409. (fr->frametype == AST_FRAME_TEXT)) {
  3410. ast_write(other, fr);
  3411. }
  3412. ast_frfree(fr);
  3413. }
  3414. /* Swap priority */
  3415. #ifndef HAVE_EPOLL
  3416. cs[2] = cs[0];
  3417. cs[0] = cs[1];
  3418. cs[1] = cs[2];
  3419. #endif
  3420. }
  3421. /* If we are totally avoiding the core, then restore our link to it */
  3422. if (p0_callback)
  3423. p0_callback = p2p_callback_disable(c0, p0, &p0_iod[0]);
  3424. if (p1_callback)
  3425. p1_callback = p2p_callback_disable(c1, p1, &p1_iod[0]);
  3426. /* Break out of the direct bridge */
  3427. p2p_set_bridge(p0, NULL);
  3428. p2p_set_bridge(p1, NULL);
  3429. ast_poll_channel_del(c0, c1);
  3430. return res;
  3431. }
  3432. /*! \page AstRTPbridge The Asterisk RTP bridge
  3433. The RTP bridge is called from the channel drivers that are using the RTP
  3434. subsystem in Asterisk - like SIP, H.323 and Jingle/Google Talk.
  3435. This bridge aims to offload the Asterisk server by setting up
  3436. the media stream directly between the endpoints, keeping the
  3437. signalling in Asterisk.
  3438. It checks with the channel driver, using a callback function, if
  3439. there are possibilities for a remote bridge.
  3440. If this fails, the bridge hands off to the core bridge. Reasons
  3441. can be NAT support needed, DTMF features in audio needed by
  3442. the PBX for transfers or spying/monitoring on channels.
  3443. If transcoding is needed - we can't do a remote bridge.
  3444. If only NAT support is needed, we're using Asterisk in
  3445. RTP proxy mode with the p2p RTP bridge, basically
  3446. forwarding incoming audio packets to the outbound
  3447. stream on a network level.
  3448. References:
  3449. - ast_rtp_bridge()
  3450. - ast_channel_early_bridge()
  3451. - ast_channel_bridge()
  3452. - rtp.c
  3453. - rtp.h
  3454. */
  3455. /*! \brief Bridge calls. If possible and allowed, initiate
  3456. re-invite so the peers exchange media directly outside
  3457. of Asterisk.
  3458. */
  3459. enum ast_bridge_result ast_rtp_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
  3460. {
  3461. struct ast_rtp *p0 = NULL, *p1 = NULL; /* Audio RTP Channels */
  3462. struct ast_rtp *vp0 = NULL, *vp1 = NULL; /* Video RTP channels */
  3463. struct ast_rtp *tp0 = NULL, *tp1 = NULL; /* Text RTP channels */
  3464. struct ast_rtp_protocol *pr0 = NULL, *pr1 = NULL;
  3465. enum ast_rtp_get_result audio_p0_res = AST_RTP_GET_FAILED, video_p0_res = AST_RTP_GET_FAILED, text_p0_res = AST_RTP_GET_FAILED;
  3466. enum ast_rtp_get_result audio_p1_res = AST_RTP_GET_FAILED, video_p1_res = AST_RTP_GET_FAILED, text_p1_res = AST_RTP_GET_FAILED;
  3467. enum ast_bridge_result res = AST_BRIDGE_FAILED;
  3468. int codec0 = 0, codec1 = 0;
  3469. void *pvt0 = NULL, *pvt1 = NULL;
  3470. /* Lock channels */
  3471. ast_channel_lock(c0);
  3472. while (ast_channel_trylock(c1)) {
  3473. ast_channel_unlock(c0);
  3474. usleep(1);
  3475. ast_channel_lock(c0);
  3476. }
  3477. /* Ensure neither channel got hungup during lock avoidance */
  3478. if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
  3479. ast_log(LOG_WARNING, "Got hangup while attempting to bridge '%s' and '%s'\n", c0->name, c1->name);
  3480. ast_channel_unlock(c0);
  3481. ast_channel_unlock(c1);
  3482. return AST_BRIDGE_FAILED;
  3483. }
  3484. /* Find channel driver interfaces */
  3485. if (!(pr0 = get_proto(c0))) {
  3486. ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c0->name);
  3487. ast_channel_unlock(c0);
  3488. ast_channel_unlock(c1);
  3489. return AST_BRIDGE_FAILED;
  3490. }
  3491. if (!(pr1 = get_proto(c1))) {
  3492. ast_log(LOG_WARNING, "Can't find native functions for channel '%s'\n", c1->name);
  3493. ast_channel_unlock(c0);
  3494. ast_channel_unlock(c1);
  3495. return AST_BRIDGE_FAILED;
  3496. }
  3497. /* Get channel specific interface structures */
  3498. pvt0 = c0->tech_pvt;
  3499. pvt1 = c1->tech_pvt;
  3500. /* Get audio and video interface (if native bridge is possible) */
  3501. audio_p0_res = pr0->get_rtp_info(c0, &p0);
  3502. video_p0_res = pr0->get_vrtp_info ? pr0->get_vrtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
  3503. text_p0_res = pr0->get_trtp_info ? pr0->get_trtp_info(c0, &vp0) : AST_RTP_GET_FAILED;
  3504. audio_p1_res = pr1->get_rtp_info(c1, &p1);
  3505. video_p1_res = pr1->get_vrtp_info ? pr1->get_vrtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
  3506. text_p1_res = pr1->get_trtp_info ? pr1->get_trtp_info(c1, &vp1) : AST_RTP_GET_FAILED;
  3507. /* If we are carrying video, and both sides are not reinviting... then fail the native bridge */
  3508. if (video_p0_res != AST_RTP_GET_FAILED && (audio_p0_res != AST_RTP_TRY_NATIVE || video_p0_res != AST_RTP_TRY_NATIVE))
  3509. audio_p0_res = AST_RTP_GET_FAILED;
  3510. if (video_p1_res != AST_RTP_GET_FAILED && (audio_p1_res != AST_RTP_TRY_NATIVE || video_p1_res != AST_RTP_TRY_NATIVE))
  3511. audio_p1_res = AST_RTP_GET_FAILED;
  3512. /* Check if a bridge is possible (partial/native) */
  3513. if (audio_p0_res == AST_RTP_GET_FAILED || audio_p1_res == AST_RTP_GET_FAILED) {
  3514. /* Somebody doesn't want to play... */
  3515. ast_channel_unlock(c0);
  3516. ast_channel_unlock(c1);
  3517. return AST_BRIDGE_FAILED_NOWARN;
  3518. }
  3519. /* If we need to feed DTMF frames into the core then only do a partial native bridge */
  3520. if (ast_test_flag(p0, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
  3521. ast_set_flag(p0, FLAG_P2P_NEED_DTMF);
  3522. audio_p0_res = AST_RTP_TRY_PARTIAL;
  3523. }
  3524. if (ast_test_flag(p1, FLAG_HAS_DTMF) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
  3525. ast_set_flag(p1, FLAG_P2P_NEED_DTMF);
  3526. audio_p1_res = AST_RTP_TRY_PARTIAL;
  3527. }
  3528. /* If both sides are not using the same method of DTMF transmission
  3529. * (ie: one is RFC2833, other is INFO... then we can not do direct media.
  3530. * --------------------------------------------------
  3531. * | DTMF Mode | HAS_DTMF | Accepts Begin Frames |
  3532. * |-----------|------------|-----------------------|
  3533. * | Inband | False | True |
  3534. * | RFC2833 | True | True |
  3535. * | SIP INFO | False | False |
  3536. * --------------------------------------------------
  3537. * However, if DTMF from both channels is being monitored by the core, then
  3538. * we can still do packet-to-packet bridging, because passing through the
  3539. * core will handle DTMF mode translation.
  3540. */
  3541. if ( (ast_test_flag(p0, FLAG_HAS_DTMF) != ast_test_flag(p1, FLAG_HAS_DTMF)) ||
  3542. (!c0->tech->send_digit_begin != !c1->tech->send_digit_begin)) {
  3543. if (!ast_test_flag(p0, FLAG_P2P_NEED_DTMF) || !ast_test_flag(p1, FLAG_P2P_NEED_DTMF)) {
  3544. ast_channel_unlock(c0);
  3545. ast_channel_unlock(c1);
  3546. return AST_BRIDGE_FAILED_NOWARN;
  3547. }
  3548. audio_p0_res = AST_RTP_TRY_PARTIAL;
  3549. audio_p1_res = AST_RTP_TRY_PARTIAL;
  3550. }
  3551. /* If we need to feed frames into the core don't do a P2P bridge */
  3552. if ((audio_p0_res == AST_RTP_TRY_PARTIAL && ast_test_flag(p0, FLAG_P2P_NEED_DTMF)) ||
  3553. (audio_p1_res == AST_RTP_TRY_PARTIAL && ast_test_flag(p1, FLAG_P2P_NEED_DTMF))) {
  3554. ast_channel_unlock(c0);
  3555. ast_channel_unlock(c1);
  3556. return AST_BRIDGE_FAILED_NOWARN;
  3557. }
  3558. /* Get codecs from both sides */
  3559. codec0 = pr0->get_codec ? pr0->get_codec(c0) : 0;
  3560. codec1 = pr1->get_codec ? pr1->get_codec(c1) : 0;
  3561. if (codec0 && codec1 && !(codec0 & codec1)) {
  3562. /* Hey, we can't do native bridging if both parties speak different codecs */
  3563. ast_debug(3, "Channel codec0 = %d is not codec1 = %d, cannot native bridge in RTP.\n", codec0, codec1);
  3564. ast_channel_unlock(c0);
  3565. ast_channel_unlock(c1);
  3566. return AST_BRIDGE_FAILED_NOWARN;
  3567. }
  3568. /* If either side can only do a partial bridge, then don't try for a true native bridge */
  3569. if (audio_p0_res == AST_RTP_TRY_PARTIAL || audio_p1_res == AST_RTP_TRY_PARTIAL) {
  3570. struct ast_format_list fmt0, fmt1;
  3571. /* In order to do Packet2Packet bridging both sides must be in the same rawread/rawwrite */
  3572. if (c0->rawreadformat != c1->rawwriteformat || c1->rawreadformat != c0->rawwriteformat) {
  3573. ast_debug(1, "Cannot packet2packet bridge - raw formats are incompatible\n");
  3574. ast_channel_unlock(c0);
  3575. ast_channel_unlock(c1);
  3576. return AST_BRIDGE_FAILED_NOWARN;
  3577. }
  3578. /* They must also be using the same packetization */
  3579. fmt0 = ast_codec_pref_getsize(&p0->pref, c0->rawreadformat);
  3580. fmt1 = ast_codec_pref_getsize(&p1->pref, c1->rawreadformat);
  3581. if (fmt0.cur_ms != fmt1.cur_ms) {
  3582. ast_debug(1, "Cannot packet2packet bridge - packetization settings prevent it\n");
  3583. ast_channel_unlock(c0);
  3584. ast_channel_unlock(c1);
  3585. return AST_BRIDGE_FAILED_NOWARN;
  3586. }
  3587. ast_verb(3, "Packet2Packet bridging %s and %s\n", c0->name, c1->name);
  3588. res = bridge_p2p_loop(c0, c1, p0, p1, timeoutms, flags, fo, rc, pvt0, pvt1);
  3589. } else {
  3590. ast_verb(3, "Native bridging %s and %s\n", c0->name, c1->name);
  3591. res = bridge_native_loop(c0, c1, p0, p1, vp0, vp1, tp0, tp1, pr0, pr1, codec0, codec1, timeoutms, flags, fo, rc, pvt0, pvt1);
  3592. }
  3593. return res;
  3594. }
  3595. static char *rtp_do_debug_ip(struct ast_cli_args *a, int deprecated)
  3596. {
  3597. struct hostent *hp;
  3598. struct ast_hostent ahp;
  3599. int port = 0;
  3600. char *p, *arg;
  3601. if (deprecated == 1) {
  3602. arg = a->argv[3];
  3603. } else {
  3604. arg = a->argv[4];
  3605. }
  3606. p = strstr(arg, ":");
  3607. if (p) {
  3608. *p = '\0';
  3609. p++;
  3610. port = atoi(p);
  3611. }
  3612. hp = ast_gethostbyname(arg, &ahp);
  3613. if (hp == NULL) {
  3614. ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
  3615. return CLI_FAILURE;
  3616. }
  3617. rtpdebugaddr.sin_family = AF_INET;
  3618. memcpy(&rtpdebugaddr.sin_addr, hp->h_addr, sizeof(rtpdebugaddr.sin_addr));
  3619. rtpdebugaddr.sin_port = htons(port);
  3620. if (port == 0)
  3621. ast_cli(a->fd, "RTP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtpdebugaddr.sin_addr));
  3622. else
  3623. ast_cli(a->fd, "RTP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtpdebugaddr.sin_addr), port);
  3624. rtpdebug = 1;
  3625. return CLI_SUCCESS;
  3626. }
  3627. static char *rtcp_do_debug_ip(struct ast_cli_args *a)
  3628. {
  3629. struct hostent *hp;
  3630. struct ast_hostent ahp;
  3631. int port = 0;
  3632. char *p, *arg;
  3633. arg = a->argv[3];
  3634. p = strstr(arg, ":");
  3635. if (p) {
  3636. *p = '\0';
  3637. p++;
  3638. port = atoi(p);
  3639. }
  3640. hp = ast_gethostbyname(arg, &ahp);
  3641. if (hp == NULL) {
  3642. ast_cli(a->fd, "Lookup failed for '%s'\n", arg);
  3643. return CLI_FAILURE;
  3644. }
  3645. rtcpdebugaddr.sin_family = AF_INET;
  3646. memcpy(&rtcpdebugaddr.sin_addr, hp->h_addr, sizeof(rtcpdebugaddr.sin_addr));
  3647. rtcpdebugaddr.sin_port = htons(port);
  3648. if (port == 0)
  3649. ast_cli(a->fd, "RTCP Debugging Enabled for IP: %s\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr));
  3650. else
  3651. ast_cli(a->fd, "RTCP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(rtcpdebugaddr.sin_addr), port);
  3652. rtcpdebug = 1;
  3653. return CLI_SUCCESS;
  3654. }
  3655. static char *handle_cli_rtp_debug_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3656. {
  3657. switch (cmd) {
  3658. case CLI_INIT:
  3659. e->command = "rtp debug [off|ip]";
  3660. e->usage =
  3661. "Usage: rtp debug [off]|[ip host[:port]]\n"
  3662. " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
  3663. " specified, limit the dumped packets to those to and from\n"
  3664. " the specified 'host' with optional port.\n";
  3665. return NULL;
  3666. case CLI_GENERATE:
  3667. return NULL;
  3668. }
  3669. if (a->argc < 2 || a->argc > 4)
  3670. return CLI_SHOWUSAGE;
  3671. if (a->argc == 2) {
  3672. rtpdebug = 1;
  3673. memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
  3674. ast_cli(a->fd, "RTP Debugging Enabled\n");
  3675. } else if (a->argc == 3) {
  3676. if (strncasecmp(a->argv[2], "off", 3))
  3677. return CLI_SHOWUSAGE;
  3678. rtpdebug = 0;
  3679. ast_cli(a->fd, "RTP Debugging Disabled\n");
  3680. } else {
  3681. if (strncasecmp(a->argv[2], "ip", 2))
  3682. return CLI_SHOWUSAGE;
  3683. return rtp_do_debug_ip(a, 1);
  3684. }
  3685. return CLI_SUCCESS;
  3686. }
  3687. static char *handle_cli_rtp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3688. {
  3689. switch (cmd) {
  3690. case CLI_INIT:
  3691. e->command = "rtp set debug {on|off|ip}";
  3692. e->usage =
  3693. "Usage: rtp set debug {on|off|ip host[:port]}\n"
  3694. " Enable/Disable dumping of all RTP packets. If 'ip' is\n"
  3695. " specified, limit the dumped packets to those to and from\n"
  3696. " the specified 'host' with optional port.\n";
  3697. return NULL;
  3698. case CLI_GENERATE:
  3699. return NULL;
  3700. }
  3701. if (a->argc == e->args) { /* set on or off */
  3702. if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
  3703. rtpdebug = 1;
  3704. memset(&rtpdebugaddr, 0, sizeof(rtpdebugaddr));
  3705. ast_cli(a->fd, "RTP Debugging Enabled\n");
  3706. return CLI_SUCCESS;
  3707. } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
  3708. rtpdebug = 0;
  3709. ast_cli(a->fd, "RTP Debugging Disabled\n");
  3710. return CLI_SUCCESS;
  3711. }
  3712. } else if (a->argc == e->args +1) { /* ip */
  3713. return rtp_do_debug_ip(a, 0);
  3714. }
  3715. return CLI_SHOWUSAGE; /* default, failure */
  3716. }
  3717. static char *handle_cli_rtcp_debug_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3718. {
  3719. switch (cmd) {
  3720. case CLI_INIT:
  3721. e->command = "rtcp debug [off|ip]";
  3722. e->usage =
  3723. "Usage: rtcp debug [off]|[ip host[:port]]\n"
  3724. " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
  3725. " specified, limit the dumped packets to those to and from\n"
  3726. " the specified 'host' with optional port.\n";
  3727. return NULL;
  3728. case CLI_GENERATE:
  3729. return NULL;
  3730. }
  3731. if (a->argc < 2 || a->argc > 4)
  3732. return CLI_SHOWUSAGE;
  3733. if (a->argc == 2) {
  3734. rtcpdebug = 1;
  3735. memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
  3736. ast_cli(a->fd, "RTCP Debugging Enabled\n");
  3737. } else if (a->argc == 3) {
  3738. if (strncasecmp(a->argv[2], "off", 3))
  3739. return CLI_SHOWUSAGE;
  3740. rtcpdebug = 0;
  3741. ast_cli(a->fd, "RTCP Debugging Disabled\n");
  3742. } else {
  3743. if (strncasecmp(a->argv[2], "ip", 2))
  3744. return CLI_SHOWUSAGE;
  3745. return rtcp_do_debug_ip(a);
  3746. }
  3747. return CLI_SUCCESS;
  3748. }
  3749. static char *handle_cli_rtcp_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3750. {
  3751. switch (cmd) {
  3752. case CLI_INIT:
  3753. e->command = "rtcp set debug {on|off|ip}";
  3754. e->usage =
  3755. "Usage: rtcp set debug {on|off|ip host[:port]}\n"
  3756. " Enable/Disable dumping of all RTCP packets. If 'ip' is\n"
  3757. " specified, limit the dumped packets to those to and from\n"
  3758. " the specified 'host' with optional port.\n";
  3759. return NULL;
  3760. case CLI_GENERATE:
  3761. return NULL;
  3762. }
  3763. if (a->argc == e->args) { /* set on or off */
  3764. if (!strncasecmp(a->argv[e->args-1], "on", 2)) {
  3765. rtcpdebug = 1;
  3766. memset(&rtcpdebugaddr, 0, sizeof(rtcpdebugaddr));
  3767. ast_cli(a->fd, "RTCP Debugging Enabled\n");
  3768. return CLI_SUCCESS;
  3769. } else if (!strncasecmp(a->argv[e->args-1], "off", 3)) {
  3770. rtcpdebug = 0;
  3771. ast_cli(a->fd, "RTCP Debugging Disabled\n");
  3772. return CLI_SUCCESS;
  3773. }
  3774. } else if (a->argc == e->args +1) { /* ip */
  3775. return rtcp_do_debug_ip(a);
  3776. }
  3777. return CLI_SHOWUSAGE; /* default, failure */
  3778. }
  3779. static char *handle_cli_rtcp_stats_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3780. {
  3781. switch (cmd) {
  3782. case CLI_INIT:
  3783. e->command = "rtcp stats [off]";
  3784. e->usage =
  3785. "Usage: rtcp stats [off]\n"
  3786. " Enable/Disable dumping of RTCP stats.\n";
  3787. return NULL;
  3788. case CLI_GENERATE:
  3789. return NULL;
  3790. }
  3791. if (a->argc < 2 || a->argc > 3)
  3792. return CLI_SHOWUSAGE;
  3793. if (a->argc == 3 && strncasecmp(a->argv[2], "off", 3))
  3794. return CLI_SHOWUSAGE;
  3795. rtcpstats = (a->argc == 3) ? 0 : 1;
  3796. ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
  3797. return CLI_SUCCESS;
  3798. }
  3799. static char *handle_cli_rtcp_set_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3800. {
  3801. switch (cmd) {
  3802. case CLI_INIT:
  3803. e->command = "rtcp set stats {on|off}";
  3804. e->usage =
  3805. "Usage: rtcp set stats {on|off}\n"
  3806. " Enable/Disable dumping of RTCP stats.\n";
  3807. return NULL;
  3808. case CLI_GENERATE:
  3809. return NULL;
  3810. }
  3811. if (a->argc != e->args)
  3812. return CLI_SHOWUSAGE;
  3813. if (!strncasecmp(a->argv[e->args-1], "on", 2))
  3814. rtcpstats = 1;
  3815. else if (!strncasecmp(a->argv[e->args-1], "off", 3))
  3816. rtcpstats = 0;
  3817. else
  3818. return CLI_SHOWUSAGE;
  3819. ast_cli(a->fd, "RTCP Stats %s\n", rtcpstats ? "Enabled" : "Disabled");
  3820. return CLI_SUCCESS;
  3821. }
  3822. static char *handle_cli_stun_debug_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3823. {
  3824. switch (cmd) {
  3825. case CLI_INIT:
  3826. e->command = "stun debug [off]";
  3827. e->usage =
  3828. "Usage: stun debug [off]\n"
  3829. " Enable/Disable STUN (Simple Traversal of UDP through NATs)\n"
  3830. " debugging\n";
  3831. return NULL;
  3832. case CLI_GENERATE:
  3833. return NULL;
  3834. }
  3835. if (a->argc < 2 || a->argc > 3)
  3836. return CLI_SHOWUSAGE;
  3837. if (a->argc == 3 && strncasecmp(a->argv[2], "off", 3))
  3838. return CLI_SHOWUSAGE;
  3839. stundebug = (a->argc == 3) ? 0 : 1;
  3840. ast_cli(a->fd, "STUN Debugging %s\n", stundebug ? "Enabled" : "Disabled");
  3841. return CLI_SUCCESS;
  3842. }
  3843. static char *handle_cli_stun_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
  3844. {
  3845. switch (cmd) {
  3846. case CLI_INIT:
  3847. e->command = "stun set debug {on|off}";
  3848. e->usage =
  3849. "Usage: stun set debug {on|off}\n"
  3850. " Enable/Disable STUN (Simple Traversal of UDP through NATs)\n"
  3851. " debugging\n";
  3852. return NULL;
  3853. case CLI_GENERATE:
  3854. return NULL;
  3855. }
  3856. if (a->argc != e->args)
  3857. return CLI_SHOWUSAGE;
  3858. if (!strncasecmp(a->argv[e->args-1], "on", 2))
  3859. stundebug = 1;
  3860. else if (!strncasecmp(a->argv[e->args-1], "off", 3))
  3861. stundebug = 0;
  3862. else
  3863. return CLI_SHOWUSAGE;
  3864. ast_cli(a->fd, "STUN Debugging %s\n", stundebug ? "Enabled" : "Disabled");
  3865. return CLI_SUCCESS;
  3866. }
  3867. static struct ast_cli_entry cli_rtp_debug_deprecated = AST_CLI_DEFINE(handle_cli_rtp_debug_deprecated, "Enable/Disable RTP debugging");
  3868. static struct ast_cli_entry cli_rtcp_debug_deprecated = AST_CLI_DEFINE(handle_cli_rtcp_debug_deprecated, "Enable/Disable RTCP debugging");
  3869. static struct ast_cli_entry cli_rtcp_stats_deprecated = AST_CLI_DEFINE(handle_cli_rtcp_stats_deprecated, "Enable/Disable RTCP stats");
  3870. static struct ast_cli_entry cli_stun_debug_deprecated = AST_CLI_DEFINE(handle_cli_stun_debug_deprecated, "Enable/Disable STUN debugging");
  3871. static struct ast_cli_entry cli_rtp[] = {
  3872. AST_CLI_DEFINE(handle_cli_rtp_set_debug, "Enable/Disable RTP debugging", .deprecate_cmd = &cli_rtp_debug_deprecated),
  3873. AST_CLI_DEFINE(handle_cli_rtcp_set_debug, "Enable/Disable RTCP debugging", .deprecate_cmd = &cli_rtcp_debug_deprecated),
  3874. AST_CLI_DEFINE(handle_cli_rtcp_set_stats, "Enable/Disable RTCP stats", .deprecate_cmd = &cli_rtcp_stats_deprecated),
  3875. AST_CLI_DEFINE(handle_cli_stun_set_debug, "Enable/Disable STUN debugging", .deprecate_cmd = &cli_stun_debug_deprecated),
  3876. };
  3877. static int __ast_rtp_reload(int reload)
  3878. {
  3879. struct ast_config *cfg;
  3880. const char *s;
  3881. struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
  3882. if ((cfg = ast_config_load("rtp.conf", config_flags)) == CONFIG_STATUS_FILEUNCHANGED)
  3883. return 0;
  3884. rtpstart = 5000;
  3885. rtpend = 31000;
  3886. dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  3887. strictrtp = STRICT_RTP_OPEN;
  3888. if (cfg) {
  3889. if ((s = ast_variable_retrieve(cfg, "general", "rtpstart"))) {
  3890. rtpstart = atoi(s);
  3891. if (rtpstart < 1024)
  3892. rtpstart = 1024;
  3893. if (rtpstart > 65535)
  3894. rtpstart = 65535;
  3895. }
  3896. if ((s = ast_variable_retrieve(cfg, "general", "rtpend"))) {
  3897. rtpend = atoi(s);
  3898. if (rtpend < 1024)
  3899. rtpend = 1024;
  3900. if (rtpend > 65535)
  3901. rtpend = 65535;
  3902. }
  3903. if ((s = ast_variable_retrieve(cfg, "general", "rtcpinterval"))) {
  3904. rtcpinterval = atoi(s);
  3905. if (rtcpinterval == 0)
  3906. rtcpinterval = 0; /* Just so we're clear... it's zero */
  3907. if (rtcpinterval < RTCP_MIN_INTERVALMS)
  3908. rtcpinterval = RTCP_MIN_INTERVALMS; /* This catches negative numbers too */
  3909. if (rtcpinterval > RTCP_MAX_INTERVALMS)
  3910. rtcpinterval = RTCP_MAX_INTERVALMS;
  3911. }
  3912. if ((s = ast_variable_retrieve(cfg, "general", "rtpchecksums"))) {
  3913. #ifdef SO_NO_CHECK
  3914. if (ast_false(s))
  3915. nochecksums = 1;
  3916. else
  3917. nochecksums = 0;
  3918. #else
  3919. if (ast_false(s))
  3920. ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
  3921. #endif
  3922. }
  3923. if ((s = ast_variable_retrieve(cfg, "general", "dtmftimeout"))) {
  3924. dtmftimeout = atoi(s);
  3925. if ((dtmftimeout < 0) || (dtmftimeout > 64000)) {
  3926. ast_log(LOG_WARNING, "DTMF timeout of '%d' outside range, using default of '%d' instead\n",
  3927. dtmftimeout, DEFAULT_DTMF_TIMEOUT);
  3928. dtmftimeout = DEFAULT_DTMF_TIMEOUT;
  3929. };
  3930. }
  3931. if ((s = ast_variable_retrieve(cfg, "general", "strictrtp"))) {
  3932. strictrtp = ast_true(s);
  3933. }
  3934. ast_config_destroy(cfg);
  3935. }
  3936. if (rtpstart >= rtpend) {
  3937. ast_log(LOG_WARNING, "Unreasonable values for RTP start/end port in rtp.conf\n");
  3938. rtpstart = 5000;
  3939. rtpend = 31000;
  3940. }
  3941. ast_verb(2, "RTP Allocating from port range %d -> %d\n", rtpstart, rtpend);
  3942. return 0;
  3943. }
  3944. int ast_rtp_reload(void)
  3945. {
  3946. return __ast_rtp_reload(1);
  3947. }
  3948. /*! \brief Initialize the RTP system in Asterisk */
  3949. void ast_rtp_init(void)
  3950. {
  3951. ast_cli_register_multiple(cli_rtp, sizeof(cli_rtp) / sizeof(struct ast_cli_entry));
  3952. __ast_rtp_reload(0);
  3953. }