rtcEngine.min.js 268 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.RtcEngine = factory());
  5. })(this, (function () { 'use strict';
  6. let ws = null, heartBeatFlag = null;
  7. //此文件实现将控制命令封装成协议,具体协议内容请看:
  8. //链接:http://note.youdao.com/noteshare?id=dabda6c613adef7a416bd2625cd770a1
  9. //bcc校验码计算
  10. //arry: 要计算的数组
  11. //返回计算协议中校验位的校验码
  12. function calBcc(arry)
  13. {
  14. var bcc = 0;
  15. for(let i = 0;i < arry.length;i++)
  16. {
  17. bcc ^= arry[i];
  18. }
  19. return bcc;
  20. }
  21. function makeFrameExtend(sn, dataType, body)
  22. {
  23. var index = 0;
  24. var dataLen = body.length;
  25. var frameLen = dataLen + 26;
  26. var outPut = new Uint8Array(frameLen);
  27. outPut[index++] = 0x68;
  28. outPut[index++] = (dataLen & 0xff000000) >> 24;
  29. outPut[index++] = (dataLen & 0x00ff0000) >> 16;
  30. outPut[index++] = (dataLen & 0x0000ff00) >> 8;
  31. outPut[index++] = dataLen & 0x000000ff;
  32. outPut[index++] = 0;//类型为client
  33. //sn号赋值,string转ascii
  34. for(let i = 0;i< sn.length;i++)
  35. {
  36. outPut[index++] = sn[i].charCodeAt();
  37. }
  38. outPut[index++] = dataType;//指定数据类型为json
  39. //json string转ascii
  40. for(let i = 0;i < body.length;i++)
  41. {
  42. outPut[index++] = body[i];
  43. }
  44. var bccBuffer = outPut.slice(1, frameLen-3 + 1);//忽略协议头和协议尾
  45. outPut[index++] = calBcc(bccBuffer);
  46. outPut[index++] = 0x16;
  47. //var str = PrintArry(outPut);
  48. //console.log("打印数组:%s", PrintArry(outPut));
  49. //return PrintArry(outPut);
  50. return outPut;
  51. }
  52. //根据报文识别屏幕方向, 0横屏,1竖屏
  53. function CheckScreenDirection(data)
  54. {
  55. if (data[0] == 0 && data[1] == 0 && data[2] == 0 &&data[3] == 1)
  56. {
  57. if (data[4] == 1 && data[5] == 1)
  58. {
  59. if (data[6] == 1)
  60. {
  61. screen = data[7];
  62. return screen;
  63. }
  64. }
  65. }
  66. }
  67. //查询屏幕方向
  68. function GetScreenState()
  69. {
  70. var sn = "RK3923C1201900139";
  71. var outPut = new Uint8Array([0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x02]);
  72. return makeFrameExtend(sn, 5, outPut);
  73. }
  74. //生成鉴权报文
  75. function VerifyCode(sn, code)
  76. {
  77. var len = code.length + 1;
  78. var codeBuffer = new TextEncoder("utf-8").encode(code);//获取字符串ascii码
  79. var buffer = new Uint8Array(len);
  80. buffer[0] = 0x04;
  81. for(let i = 0;i < codeBuffer.length;i++)
  82. {
  83. buffer[i + 1] = codeBuffer[i];
  84. }
  85. return makeFrameExtend(sn, 6, buffer);
  86. }
  87. //
  88. function CheckVerifyCode(data)
  89. {
  90. var dataLen = data.length - 26;
  91. var body = data.slice(24, 24 + dataLen);
  92. if(body[3] == 0x03)
  93. {
  94. return true;
  95. }
  96. return false;
  97. }
  98. //通道配置
  99. function ConfigChannel(sn, channelName)
  100. {
  101. var chanelBuffer = new TextEncoder("utf-8").encode(channelName);
  102. var outPut = [];
  103. outPut.push(0x07);
  104. for(let i = 0;i < chanelBuffer.length;i++) {
  105. outPut.push(chanelBuffer[i]);
  106. }
  107. return makeFrameExtend(sn, 6, outPut);
  108. }
  109. //切换清晰度
  110. function makeSharpness(level)
  111. {
  112. var sn = "RK3923C1201900139";
  113. var jsonObj =
  114. {"type":2,"data":{"definition":level,
  115. "clientType": "h5",
  116. "sceneType": "cloudPhone"
  117. }};
  118. var jsonStr = JSON.stringify(jsonObj);
  119. var outPut = new TextEncoder("utf-8").encode(jsonStr);
  120. return makeFrameExtend(sn, 0xd, outPut);
  121. }
  122. //I 帧请求报文生成
  123. function RequestIFrame()
  124. {
  125. var sn = "RK3923C1201900139";
  126. var outPut = new Uint8Array([0x20]);
  127. return makeFrameExtend(sn, 6, outPut);
  128. }
  129. function setFps(frameRate) {
  130. let sn = "RK3923C1201900139";
  131. let jsonObj = { "type": 1, "data": { "frame_rate": frameRate } };
  132. let jsonStr = JSON.stringify(jsonObj);
  133. let outPut = new TextEncoder("utf-8").encode(jsonStr);
  134. return makeFrameExtend(sn, 0xD, outPut);
  135. }
  136. const Authen_ID = 0x5C;//鉴权标识
  137. const MultiLogin_ID = 0x0B;//多端登录标识
  138. const ScreenDirection_ID = 0x05;//横竖屏状态
  139. const Audio_ID = 0xFF;//音频标识
  140. const Porto_Header_ID = 0x68;//协议头标识
  141. const Landscape_ID = 0x00;//横屏标识
  142. const Vertica_ID = 0X01;//竖屏标识
  143. const SPS_ID = 0X07;//SPD标识
  144. const PPS_ID = 0X08;//PPS标识
  145. const verify_Failed = -1001;//鉴权失败
  146. const OPEN_SUCCESS = 0;//拉流成功,正常显示
  147. function PCMPlayer(option) {
  148. this.init(option);
  149. }
  150. PCMPlayer.prototype.init = function(option) {
  151. var defaults = {
  152. encoding: '16bitInt',
  153. channels: 1,
  154. sampleRate: 8000,
  155. flushingTime: 1000
  156. };
  157. this.option = Object.assign({}, defaults, option);
  158. this.samples = new Float32Array();
  159. this.flush = this.flush.bind(this);
  160. this.interval = setInterval(this.flush, this.option.flushingTime);
  161. this.maxValue = this.getMaxValue();
  162. this.typedArray = this.getTypedArray();
  163. this.createContext();
  164. };
  165. PCMPlayer.prototype.getMaxValue = function () {
  166. var encodings = {
  167. '8bitInt': 128,
  168. '16bitInt': 32768,
  169. '32bitInt': 2147483648,
  170. '32bitFloat': 1
  171. };
  172. return encodings[this.option.encoding] ? encodings[this.option.encoding] : encodings['16bitInt'];
  173. };
  174. PCMPlayer.prototype.getTypedArray = function () {
  175. var typedArrays = {
  176. '8bitInt': Int8Array,
  177. '16bitInt': Int16Array,
  178. '32bitInt': Int32Array,
  179. '32bitFloat': Float32Array
  180. };
  181. return typedArrays[this.option.encoding] ? typedArrays[this.option.encoding] : typedArrays['16bitInt'];
  182. };
  183. PCMPlayer.prototype.createContext = function() {
  184. this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  185. this.gainNode = this.audioCtx.createGain();
  186. this.gainNode.gain.value = 1;
  187. this.gainNode.connect(this.audioCtx.destination);
  188. this.startTime = this.audioCtx.currentTime;
  189. };
  190. PCMPlayer.prototype.isTypedArray = function(data) {
  191. return (data.byteLength && data.buffer && data.buffer.constructor == ArrayBuffer);
  192. };
  193. PCMPlayer.prototype.feed = function(data) {
  194. if (!this.isTypedArray(data)) return;
  195. data = this.getFormatedValue(data);
  196. var tmp = new Float32Array(this.samples.length + data.length);
  197. tmp.set(this.samples, 0);
  198. tmp.set(data, this.samples.length);
  199. this.samples = tmp;
  200. };
  201. PCMPlayer.prototype.getFormatedValue = function(data) {
  202. var data = new this.typedArray(data.buffer),
  203. float32 = new Float32Array(data.length),
  204. i;
  205. for (i = 0; i < data.length; i++) {
  206. float32[i] = data[i] / this.maxValue;
  207. }
  208. return float32;
  209. };
  210. PCMPlayer.prototype.volume = function(volume) {
  211. this.gainNode.gain.value = volume;
  212. };
  213. PCMPlayer.prototype.destroy = function() {
  214. if (this.interval) {
  215. clearInterval(this.interval);
  216. }
  217. this.samples = null;
  218. this.audioCtx.close();
  219. this.audioCtx = null;
  220. };
  221. PCMPlayer.prototype.flush = function() {
  222. if (!this.samples.length) return;
  223. var bufferSource = this.audioCtx.createBufferSource(),
  224. length = this.samples.length / this.option.channels,
  225. audioBuffer = this.audioCtx.createBuffer(this.option.channels, length, this.option.sampleRate),
  226. audioData,
  227. channel,
  228. offset,
  229. i,
  230. decrement;
  231. for (channel = 0; channel < this.option.channels; channel++) {
  232. audioData = audioBuffer.getChannelData(channel);
  233. offset = channel;
  234. decrement = 50;
  235. for (i = 0; i < length; i++) {
  236. audioData[i] = this.samples[offset];
  237. /* fadein */
  238. if (i < 50) {
  239. audioData[i] = (audioData[i] * i) / 50;
  240. }
  241. /* fadeout*/
  242. if (i >= (length - 51)) {
  243. audioData[i] = (audioData[i] * decrement--) / 50;
  244. }
  245. offset += this.option.channels;
  246. }
  247. }
  248. if (this.startTime < this.audioCtx.currentTime) {
  249. this.startTime = this.audioCtx.currentTime;
  250. }
  251. //console.log('start vs current '+this.startTime+' vs '+this.audioCtx.currentTime+' duration: '+audioBuffer.duration);
  252. bufferSource.buffer = audioBuffer;
  253. bufferSource.connect(this.gainNode);
  254. bufferSource.start(this.startTime);
  255. this.startTime += audioBuffer.duration;
  256. this.samples = new Float32Array();
  257. };
  258. class AACPlayer {
  259. constructor() {
  260. this.pcmPlayer = new PCMPlayer({
  261. encoding: '16bitInt',
  262. channels: 2,
  263. sampleRate: 44100,
  264. flushingTime: 22,
  265. debug: false
  266. });
  267. this.decodeWorker = new Worker("decodeAACWorker.js");
  268. this.onDecodeFinished = this.onDecodeFinished.bind(this);
  269. this.decodeWorker.onmessage = this.onDecodeFinished;
  270. }
  271. onDecodeFinished(event) {
  272. let data = event.data;
  273. if(data.type == "pcmData") {
  274. this.pcmPlayer.feed(data.data);
  275. }
  276. }
  277. feed(data) {
  278. let info = {
  279. type:"aacData",
  280. data:data
  281. };
  282. this.decodeWorker.postMessage(info);
  283. }
  284. stop() {
  285. this.decodeWorker.terminate();
  286. this.pcmPlayer.destroy();
  287. }
  288. }
  289. //import JMuxer from 'jmuxer';
  290. class MseConnect {
  291. constructor(option) {
  292. this.token = option.token;
  293. this.callback = option.callback;
  294. this.url = option.url;
  295. this.videoId = option.videoId;
  296. this.fps = 60;
  297. this.wsOnMessage = this.wsOnMessage.bind(this);
  298. this.wsOnClose = this.wsOnClose.bind(this);
  299. this.wsOpen = this.wsOpen.bind(this);
  300. this.heartBeat = this.heartBeat.bind(this);
  301. this.startPlay = this.startPlay.bind(this);
  302. this.wasmFinish = false;
  303. this.isFeed = true;
  304. this.lastRequseTime = 0;
  305. this.netFps = 0;
  306. this.lastCalTime = 0;
  307. this.videoNum = 0;
  308. }
  309. heartBeat() {
  310. this.ws.send("ping");
  311. let interval = new Date().getTime() - this.lastRequseTime;
  312. if(interval >= 3000*10 && this.isFeed) {
  313. this.doReqesuIFrame();
  314. this.lastRequseTime = new Date().getTime();
  315. }
  316. }
  317. pause() {
  318. this.isFeed = false;
  319. }
  320. resume() {
  321. this.doReqesuIFrame();
  322. }
  323. doReqesuIFrame() {
  324. let buffer = RequestIFrame();
  325. this.ws.send(buffer);
  326. }
  327. stateCallBack(eventName, value, desc) {
  328. let info = {
  329. type:eventName,
  330. val: value,
  331. description:desc
  332. };
  333. this.callback(info);
  334. }
  335. setFps() {
  336. let buffer = setFps(this.fps);
  337. this.ws.send(buffer);
  338. }
  339. connect() {
  340. this.ws.onmessage = this.wsOnMessage;
  341. this.ws.onopen = this.wsOpen;
  342. this.ws.onclose = this.wsOnClose;
  343. this.ws = new WebSocket(this.url);
  344. this.ws.binaryType = 'arraybuffer';
  345. this.jmuxer = new JMuxer({
  346. node: this.videoId,
  347. flushingTime:0 ,
  348. fps: this.fps,
  349. mode:'video',
  350. debug: false
  351. });
  352. this.aacPlayer = new AACPlayer();
  353. this.videoTag = document.getElementById(this.videoId);
  354. let videoElement = document.getElementById(this.videoId);
  355. videoElement.onplay = this.startPlay;
  356. }
  357. startPlay() {
  358. this.stateCallBack("open", OPEN_SUCCESS, "拉流成功");
  359. }
  360. parseProto (data) {
  361. let input = new Uint8Array(data);
  362. var duration, video, audio, frameType;
  363. if(input[0] == 0 && input[1] == 0 && input[2] == 0 && input[3] == 1) {
  364. video = input;
  365. frameType = input[4] & 0x1f;
  366. }
  367. if(input[0] == Audio_ID) {
  368. audio = input;
  369. }
  370. if(input[0] == Porto_Header_ID) {
  371. if(input[23] == MultiLogin_ID) ;
  372. if(input[23] == Authen_ID) {
  373. if(CheckVerifyCode(input)) {
  374. this.configChannel();
  375. this.setFps();
  376. }
  377. else {
  378. this.stateCallBack("verifyFailed", verify_Failed, "鉴权失败");
  379. }
  380. }
  381. if(input[23] == ScreenDirection_ID) {
  382. let direction = CheckScreenDirection(input.slice(24, 24 + 8));
  383. if(direction == Vertica_ID) {
  384. this.stateCallBack("screenChange", direction, "安卓卡竖屏");
  385. }
  386. if(direction == Landscape_ID) {
  387. this.stateCallBack("screenChange", direction, "安卓卡横屏");
  388. }
  389. }
  390. }
  391. duration = 1000/this.fps;
  392. return {
  393. audio:audio,
  394. video:video,
  395. duration:duration,
  396. frameType:frameType
  397. }
  398. }
  399. configChannel() {
  400. let sn = "RK3923C1201900139";
  401. this.ws.send(ConfigChannel(sn, "chaohang"));//chaohang ??
  402. this.ws.send(GetScreenState());
  403. }
  404. switchShapness(sharpnessLevel) {
  405. let buffer = makeSharpness(sharpnessLevel);
  406. this.ws.send(buffer);
  407. }
  408. wsOnMessage(event) {
  409. let data = this.parseProto(event.data);
  410. if(data.audio != null) {
  411. this.aacPlayer.feed(data.audio);
  412. }
  413. if(data.video != null) {
  414. if(data.frameType == SPS_ID || data.frameType == PPS_ID){
  415. this.isFeed = true;
  416. }
  417. if(this.isFeed)
  418. this.jmuxer.feed(data);
  419. }
  420. }
  421. wsOpen(event) {
  422. let sn = "RK3923C1201900139";
  423. let verifyBuffer = VerifyCode(sn, this.token);
  424. this.ws.send(verifyBuffer);
  425. this.heartBeatFlag = setInterval(this.heartBeat, 2000);
  426. heartBeatFlag = this.heartBeatFlag
  427. }
  428. wsOnClose(event) {
  429. this.stateCallBack("closeEvent", event.code, "WS关闭事件");
  430. }
  431. disconnect() {
  432. clearInterval(this.heartBeatFlag);
  433. this.aacPlayer.stop();
  434. this.jmuxer.destroy();
  435. this.ws.close();
  436. this.onclose = undefined;
  437. }
  438. }
  439. const Events$1 = {
  440. WEBRTC_NOT_SUPPORT: 'WEBRTC_NOT_SUPPORT',
  441. WEBRTC_ICE_CANDIDATE_ERROR: 'WEBRTC_ICE_CANDIDATE_ERROR',
  442. WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED: 'WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED',
  443. WEBRTC_ON_REMOTE_STREAMS: 'WEBRTC_ON_REMOTE_STREAMS',
  444. WEBRTC_ON_LOCAL_STREAM: 'WEBRTC_ON_LOCAL_STREAM',
  445. WEBRTC_ON_CONNECTION_STATE_CHANGE: 'WEBRTC_ON_CONNECTION_STATE_CHANGE',
  446. WEBRTC_ON_DATA_CHANNEL_OPEN: 'WEBRTC_ON_DATA_CHANNEL_OPEN',
  447. WEBRTC_ON_DATA_CHANNEL_CLOSE: 'WEBRTC_ON_DATA_CHANNEL_CLOSE',
  448. WEBRTC_ON_DATA_CHANNEL_ERR: 'WEBRTC_ON_DATA_CHANNEL_ERR',
  449. WEBRTC_ON_DATA_CHANNEL_MSG: 'WEBRTC_ON_DATA_CHANNEL_MSG',
  450. CAPTURE_STREAM_FAILED: 'CAPTURE_STREAM_FAILED'
  451. };
  452. const VERSION$1 = '1.0.1';
  453. const BUILD_DATE = 'Fri Aug 26 2022 15:21:07 GMT+0800 (中国标准时间)';
  454. // Copyright (C) <2018> Intel Corporation
  455. //
  456. // SPDX-License-Identifier: Apache-2.0
  457. // eslint-disable-next-line require-jsdoc
  458. function isFirefox() {
  459. return window.navigator.userAgent.match('Firefox') !== null;
  460. } // eslint-disable-next-line require-jsdoc
  461. function isChrome() {
  462. return window.navigator.userAgent.match('Chrome') !== null;
  463. } // eslint-disable-next-line require-jsdoc
  464. function isEdge() {
  465. return window.navigator.userAgent.match(/Edge\/(\d+).(\d+)$/) !== null;
  466. } // eslint-disable-next-line require-jsdoc
  467. // Copyright (C) <2018> Intel Corporation
  468. /**
  469. * @class AudioSourceInfo
  470. * @classDesc Source info about an audio track. Values: 'mic', 'screen-cast', 'file', 'mixed'.
  471. * @memberOf Owt.Base
  472. * @readonly
  473. * @enum {string}
  474. */
  475. const AudioSourceInfo = {
  476. MIC: 'mic',
  477. SCREENCAST: 'screen-cast',
  478. FILE: 'file',
  479. MIXED: 'mixed'
  480. };
  481. /**
  482. * @class VideoSourceInfo
  483. * @classDesc Source info about a video track. Values: 'camera', 'screen-cast', 'file', 'mixed'.
  484. * @memberOf Owt.Base
  485. * @readonly
  486. * @enum {string}
  487. */
  488. const VideoSourceInfo = {
  489. CAMERA: 'camera',
  490. SCREENCAST: 'screen-cast',
  491. FILE: 'file',
  492. MIXED: 'mixed'
  493. };
  494. /**
  495. * @class Resolution
  496. * @memberOf Owt.Base
  497. * @classDesc The Resolution defines the size of a rectangle.
  498. * @constructor
  499. * @param {number} width
  500. * @param {number} height
  501. */
  502. class Resolution {
  503. // eslint-disable-next-line require-jsdoc
  504. constructor(width, height) {
  505. /**
  506. * @member {number} width
  507. * @instance
  508. * @memberof Owt.Base.Resolution
  509. */
  510. this.width = width;
  511. /**
  512. * @member {number} height
  513. * @instance
  514. * @memberof Owt.Base.Resolution
  515. */
  516. this.height = height;
  517. }
  518. }
  519. /*
  520. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  521. *
  522. * Use of this source code is governed by a BSD-style license
  523. * that can be found in the LICENSE file in the root of the source
  524. * tree.
  525. */
  526. let logDisabled_ = true;
  527. let deprecationWarnings_ = true;
  528. /**
  529. * Extract browser version out of the provided user agent string.
  530. *
  531. * @param {!string} uastring userAgent string.
  532. * @param {!string} expr Regular expression used as match criteria.
  533. * @param {!number} pos position in the version string to be returned.
  534. * @return {!number} browser version.
  535. */
  536. function extractVersion(uastring, expr, pos) {
  537. const match = uastring.match(expr);
  538. return match && match.length >= pos && parseInt(match[pos], 10);
  539. }
  540. // Wraps the peerconnection event eventNameToWrap in a function
  541. // which returns the modified event object (or false to prevent
  542. // the event).
  543. function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {
  544. if (!window.RTCPeerConnection) {
  545. return;
  546. }
  547. const proto = window.RTCPeerConnection.prototype;
  548. const nativeAddEventListener = proto.addEventListener;
  549. proto.addEventListener = function(nativeEventName, cb) {
  550. if (nativeEventName !== eventNameToWrap) {
  551. return nativeAddEventListener.apply(this, arguments);
  552. }
  553. const wrappedCallback = (e) => {
  554. const modifiedEvent = wrapper(e);
  555. if (modifiedEvent) {
  556. if (cb.handleEvent) {
  557. cb.handleEvent(modifiedEvent);
  558. } else {
  559. cb(modifiedEvent);
  560. }
  561. }
  562. };
  563. this._eventMap = this._eventMap || {};
  564. if (!this._eventMap[eventNameToWrap]) {
  565. this._eventMap[eventNameToWrap] = new Map();
  566. }
  567. this._eventMap[eventNameToWrap].set(cb, wrappedCallback);
  568. return nativeAddEventListener.apply(this, [nativeEventName,
  569. wrappedCallback
  570. ]);
  571. };
  572. const nativeRemoveEventListener = proto.removeEventListener;
  573. proto.removeEventListener = function(nativeEventName, cb) {
  574. if (nativeEventName !== eventNameToWrap || !this._eventMap ||
  575. !this._eventMap[eventNameToWrap]) {
  576. return nativeRemoveEventListener.apply(this, arguments);
  577. }
  578. if (!this._eventMap[eventNameToWrap].has(cb)) {
  579. return nativeRemoveEventListener.apply(this, arguments);
  580. }
  581. const unwrappedCb = this._eventMap[eventNameToWrap].get(cb);
  582. this._eventMap[eventNameToWrap].delete(cb);
  583. if (this._eventMap[eventNameToWrap].size === 0) {
  584. delete this._eventMap[eventNameToWrap];
  585. }
  586. if (Object.keys(this._eventMap).length === 0) {
  587. delete this._eventMap;
  588. }
  589. return nativeRemoveEventListener.apply(this, [nativeEventName,
  590. unwrappedCb
  591. ]);
  592. };
  593. Object.defineProperty(proto, 'on' + eventNameToWrap, {
  594. get() {
  595. return this['_on' + eventNameToWrap];
  596. },
  597. set(cb) {
  598. if (this['_on' + eventNameToWrap]) {
  599. this.removeEventListener(eventNameToWrap,
  600. this['_on' + eventNameToWrap]);
  601. delete this['_on' + eventNameToWrap];
  602. }
  603. if (cb) {
  604. this.addEventListener(eventNameToWrap,
  605. this['_on' + eventNameToWrap] = cb);
  606. }
  607. },
  608. enumerable: true,
  609. configurable: true
  610. });
  611. }
  612. function disableLog(bool) {
  613. if (typeof bool !== 'boolean') {
  614. return new Error('Argument type: ' + typeof bool +
  615. '. Please use a boolean.');
  616. }
  617. logDisabled_ = bool;
  618. return (bool) ? 'adapter.js logging disabled' :
  619. 'adapter.js logging enabled';
  620. }
  621. /**
  622. * Disable or enable deprecation warnings
  623. * @param {!boolean} bool set to true to disable warnings.
  624. */
  625. function disableWarnings(bool) {
  626. if (typeof bool !== 'boolean') {
  627. return new Error('Argument type: ' + typeof bool +
  628. '. Please use a boolean.');
  629. }
  630. deprecationWarnings_ = !bool;
  631. return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
  632. }
  633. function log$1() {
  634. if (typeof window === 'object') {
  635. if (logDisabled_) {
  636. return;
  637. }
  638. if (typeof console !== 'undefined' && typeof console.log === 'function') {
  639. console.log.apply(console, arguments);
  640. }
  641. }
  642. }
  643. /**
  644. * Shows a deprecation warning suggesting the modern and spec-compatible API.
  645. */
  646. function deprecated(oldMethod, newMethod) {
  647. if (!deprecationWarnings_) {
  648. return;
  649. }
  650. console.warn(oldMethod + ' is deprecated, please use ' + newMethod +
  651. ' instead.');
  652. }
  653. /**
  654. * Browser detector.
  655. *
  656. * @return {object} result containing browser and version
  657. * properties.
  658. */
  659. function detectBrowser(window) {
  660. // Returned result object.
  661. const result = {
  662. browser: null,
  663. version: null
  664. };
  665. // Fail early if it's not a browser
  666. if (typeof window === 'undefined' || !window.navigator) {
  667. result.browser = 'Not a browser.';
  668. return result;
  669. }
  670. const {
  671. navigator
  672. } = window;
  673. if (navigator.mozGetUserMedia) { // Firefox.
  674. result.browser = 'firefox';
  675. result.version = extractVersion(navigator.userAgent,
  676. /Firefox\/(\d+)\./, 1);
  677. } else if (navigator.webkitGetUserMedia ||
  678. (window.isSecureContext === false && window.webkitRTCPeerConnection &&
  679. !window.RTCIceGatherer)) {
  680. // Chrome, Chromium, Webview, Opera.
  681. // Version matches Chrome/WebRTC version.
  682. // Chrome 74 removed webkitGetUserMedia on http as well so we need the
  683. // more complicated fallback to webkitRTCPeerConnection.
  684. result.browser = 'chrome';
  685. result.version = extractVersion(navigator.userAgent,
  686. /Chrom(e|ium)\/(\d+)\./, 2);
  687. } else if (navigator.mediaDevices &&
  688. navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge.
  689. result.browser = 'edge';
  690. result.version = extractVersion(navigator.userAgent,
  691. /Edge\/(\d+).(\d+)$/, 2);
  692. } else if (window.RTCPeerConnection &&
  693. navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) { // Safari.
  694. result.browser = 'safari';
  695. result.version = extractVersion(navigator.userAgent,
  696. /AppleWebKit\/(\d+)\./, 1);
  697. result.supportsUnifiedPlan = window.RTCRtpTransceiver &&
  698. 'currentDirection' in window.RTCRtpTransceiver.prototype;
  699. } else { // Default fallthrough: not supported.
  700. result.browser = 'Not a supported browser.';
  701. return result;
  702. }
  703. return result;
  704. }
  705. /**
  706. * Checks if something is an object.
  707. *
  708. * @param {*} val The something you want to check.
  709. * @return true if val is an object, false otherwise.
  710. */
  711. function isObject$1(val) {
  712. return Object.prototype.toString.call(val) === '[object Object]';
  713. }
  714. /**
  715. * Remove all empty objects and undefined values
  716. * from a nested object -- an enhanced and vanilla version
  717. * of Lodash's `compact`.
  718. */
  719. function compactObject(data) {
  720. if (!isObject$1(data)) {
  721. return data;
  722. }
  723. return Object.keys(data).reduce(function(accumulator, key) {
  724. const isObj = isObject$1(data[key]);
  725. const value = isObj ? compactObject(data[key]) : data[key];
  726. const isEmptyObject = isObj && !Object.keys(value).length;
  727. if (value === undefined || isEmptyObject) {
  728. return accumulator;
  729. }
  730. return Object.assign(accumulator, {
  731. [key]: value
  732. });
  733. }, {});
  734. }
  735. /* iterates the stats graph recursively. */
  736. function walkStats(stats, base, resultSet) {
  737. if (!base || resultSet.has(base.id)) {
  738. return;
  739. }
  740. resultSet.set(base.id, base);
  741. Object.keys(base).forEach(name => {
  742. if (name.endsWith('Id')) {
  743. walkStats(stats, stats.get(base[name]), resultSet);
  744. } else if (name.endsWith('Ids')) {
  745. base[name].forEach(id => {
  746. walkStats(stats, stats.get(id), resultSet);
  747. });
  748. }
  749. });
  750. }
  751. /* filter getStats for a sender/receiver track. */
  752. function filterStats(result, track, outbound) {
  753. const streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp';
  754. const filteredResult = new Map();
  755. if (track === null) {
  756. return filteredResult;
  757. }
  758. const trackStats = [];
  759. result.forEach(value => {
  760. if (value.type === 'track' &&
  761. value.trackIdentifier === track.id) {
  762. trackStats.push(value);
  763. }
  764. });
  765. trackStats.forEach(trackStat => {
  766. result.forEach(stats => {
  767. if (stats.type === streamStatsType && stats.trackId === trackStat.id) {
  768. walkStats(result, stats, filteredResult);
  769. }
  770. });
  771. });
  772. return filteredResult;
  773. }
  774. /*
  775. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  776. *
  777. * Use of this source code is governed by a BSD-style license
  778. * that can be found in the LICENSE file in the root of the source
  779. * tree.
  780. */
  781. const logging = log$1;
  782. function shimGetUserMedia$3(window, browserDetails) {
  783. const navigator = window && window.navigator;
  784. if (!navigator.mediaDevices) {
  785. return;
  786. }
  787. const constraintsToChrome_ = function(c) {
  788. if (typeof c !== 'object' || c.mandatory || c.optional) {
  789. return c;
  790. }
  791. const cc = {};
  792. Object.keys(c).forEach(key => {
  793. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  794. return;
  795. }
  796. const r = (typeof c[key] === 'object') ? c[key] : {
  797. ideal: c[key]
  798. };
  799. if (r.exact !== undefined && typeof r.exact === 'number') {
  800. r.min = r.max = r.exact;
  801. }
  802. const oldname_ = function(prefix, name) {
  803. if (prefix) {
  804. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  805. }
  806. return (name === 'deviceId') ? 'sourceId' : name;
  807. };
  808. if (r.ideal !== undefined) {
  809. cc.optional = cc.optional || [];
  810. let oc = {};
  811. if (typeof r.ideal === 'number') {
  812. oc[oldname_('min', key)] = r.ideal;
  813. cc.optional.push(oc);
  814. oc = {};
  815. oc[oldname_('max', key)] = r.ideal;
  816. cc.optional.push(oc);
  817. } else {
  818. oc[oldname_('', key)] = r.ideal;
  819. cc.optional.push(oc);
  820. }
  821. }
  822. if (r.exact !== undefined && typeof r.exact !== 'number') {
  823. cc.mandatory = cc.mandatory || {};
  824. cc.mandatory[oldname_('', key)] = r.exact;
  825. } else {
  826. ['min', 'max'].forEach(mix => {
  827. if (r[mix] !== undefined) {
  828. cc.mandatory = cc.mandatory || {};
  829. cc.mandatory[oldname_(mix, key)] = r[mix];
  830. }
  831. });
  832. }
  833. });
  834. if (c.advanced) {
  835. cc.optional = (cc.optional || []).concat(c.advanced);
  836. }
  837. return cc;
  838. };
  839. const shimConstraints_ = function(constraints, func) {
  840. if (browserDetails.version >= 61) {
  841. return func(constraints);
  842. }
  843. constraints = JSON.parse(JSON.stringify(constraints));
  844. if (constraints && typeof constraints.audio === 'object') {
  845. const remap = function(obj, a, b) {
  846. if (a in obj && !(b in obj)) {
  847. obj[b] = obj[a];
  848. delete obj[a];
  849. }
  850. };
  851. constraints = JSON.parse(JSON.stringify(constraints));
  852. remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
  853. remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
  854. constraints.audio = constraintsToChrome_(constraints.audio);
  855. }
  856. if (constraints && typeof constraints.video === 'object') {
  857. // Shim facingMode for mobile & surface pro.
  858. let face = constraints.video.facingMode;
  859. face = face && ((typeof face === 'object') ? face : {
  860. ideal: face
  861. });
  862. const getSupportedFacingModeLies = browserDetails.version < 66;
  863. if ((face && (face.exact === 'user' || face.exact === 'environment' ||
  864. face.ideal === 'user' || face.ideal === 'environment')) &&
  865. !(navigator.mediaDevices.getSupportedConstraints &&
  866. navigator.mediaDevices.getSupportedConstraints().facingMode &&
  867. !getSupportedFacingModeLies)) {
  868. delete constraints.video.facingMode;
  869. let matches;
  870. if (face.exact === 'environment' || face.ideal === 'environment') {
  871. matches = ['back', 'rear'];
  872. } else if (face.exact === 'user' || face.ideal === 'user') {
  873. matches = ['front'];
  874. }
  875. if (matches) {
  876. // Look for matches in label, or use last cam for back (typical).
  877. return navigator.mediaDevices.enumerateDevices()
  878. .then(devices => {
  879. devices = devices.filter(d => d.kind === 'videoinput');
  880. let dev = devices.find(d => matches.some(match =>
  881. d.label.toLowerCase().includes(match)));
  882. if (!dev && devices.length && matches.includes('back')) {
  883. dev = devices[devices.length - 1]; // more likely the back cam
  884. }
  885. if (dev) {
  886. constraints.video.deviceId = face.exact ? {
  887. exact: dev.deviceId
  888. } : {
  889. ideal: dev.deviceId
  890. };
  891. }
  892. constraints.video = constraintsToChrome_(constraints.video);
  893. logging('chrome: ' + JSON.stringify(constraints));
  894. return func(constraints);
  895. });
  896. }
  897. }
  898. constraints.video = constraintsToChrome_(constraints.video);
  899. }
  900. logging('chrome: ' + JSON.stringify(constraints));
  901. return func(constraints);
  902. };
  903. const shimError_ = function(e) {
  904. if (browserDetails.version >= 64) {
  905. return e;
  906. }
  907. return {
  908. name: {
  909. PermissionDeniedError: 'NotAllowedError',
  910. PermissionDismissedError: 'NotAllowedError',
  911. InvalidStateError: 'NotAllowedError',
  912. DevicesNotFoundError: 'NotFoundError',
  913. ConstraintNotSatisfiedError: 'OverconstrainedError',
  914. TrackStartError: 'NotReadableError',
  915. MediaDeviceFailedDueToShutdown: 'NotAllowedError',
  916. MediaDeviceKillSwitchOn: 'NotAllowedError',
  917. TabCaptureError: 'AbortError',
  918. ScreenCaptureError: 'AbortError',
  919. DeviceCaptureError: 'AbortError'
  920. } [e.name] || e.name,
  921. message: e.message,
  922. constraint: e.constraint || e.constraintName,
  923. toString() {
  924. return this.name + (this.message && ': ') + this.message;
  925. }
  926. };
  927. };
  928. const getUserMedia_ = function(constraints, onSuccess, onError) {
  929. shimConstraints_(constraints, c => {
  930. navigator.webkitGetUserMedia(c, onSuccess, e => {
  931. if (onError) {
  932. onError(shimError_(e));
  933. }
  934. });
  935. });
  936. };
  937. navigator.getUserMedia = getUserMedia_.bind(navigator);
  938. // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
  939. // function which returns a Promise, it does not accept spec-style
  940. // constraints.
  941. if (navigator.mediaDevices.getUserMedia) {
  942. const origGetUserMedia = navigator.mediaDevices.getUserMedia.
  943. bind(navigator.mediaDevices);
  944. navigator.mediaDevices.getUserMedia = function(cs) {
  945. return shimConstraints_(cs, c => origGetUserMedia(c).then(stream => {
  946. if (c.audio && !stream.getAudioTracks().length ||
  947. c.video && !stream.getVideoTracks().length) {
  948. stream.getTracks().forEach(track => {
  949. track.stop();
  950. });
  951. throw new DOMException('', 'NotFoundError');
  952. }
  953. return stream;
  954. }, e => Promise.reject(shimError_(e))));
  955. };
  956. }
  957. }
  958. /*
  959. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  960. *
  961. * Use of this source code is governed by a BSD-style license
  962. * that can be found in the LICENSE file in the root of the source
  963. * tree.
  964. */
  965. function shimGetDisplayMedia$2(window, getSourceId) {
  966. if (window.navigator.mediaDevices &&
  967. 'getDisplayMedia' in window.navigator.mediaDevices) {
  968. return;
  969. }
  970. if (!(window.navigator.mediaDevices)) {
  971. return;
  972. }
  973. // getSourceId is a function that returns a promise resolving with
  974. // the sourceId of the screen/window/tab to be shared.
  975. if (typeof getSourceId !== 'function') {
  976. console.error('shimGetDisplayMedia: getSourceId argument is not ' +
  977. 'a function');
  978. return;
  979. }
  980. window.navigator.mediaDevices.getDisplayMedia =
  981. function getDisplayMedia(constraints) {
  982. return getSourceId(constraints)
  983. .then(sourceId => {
  984. const widthSpecified = constraints.video && constraints.video.width;
  985. const heightSpecified = constraints.video &&
  986. constraints.video.height;
  987. const frameRateSpecified = constraints.video &&
  988. constraints.video.frameRate;
  989. constraints.video = {
  990. mandatory: {
  991. chromeMediaSource: 'desktop',
  992. chromeMediaSourceId: sourceId,
  993. maxFrameRate: frameRateSpecified || 3
  994. }
  995. };
  996. if (widthSpecified) {
  997. constraints.video.mandatory.maxWidth = widthSpecified;
  998. }
  999. if (heightSpecified) {
  1000. constraints.video.mandatory.maxHeight = heightSpecified;
  1001. }
  1002. return window.navigator.mediaDevices.getUserMedia(constraints);
  1003. });
  1004. };
  1005. }
  1006. /*
  1007. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1008. *
  1009. * Use of this source code is governed by a BSD-style license
  1010. * that can be found in the LICENSE file in the root of the source
  1011. * tree.
  1012. */
  1013. function shimMediaStream(window) {
  1014. window.MediaStream = window.MediaStream || window.webkitMediaStream;
  1015. }
  1016. function shimOnTrack$1(window) {
  1017. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  1018. window.RTCPeerConnection.prototype)) {
  1019. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  1020. get() {
  1021. return this._ontrack;
  1022. },
  1023. set(f) {
  1024. if (this._ontrack) {
  1025. this.removeEventListener('track', this._ontrack);
  1026. }
  1027. this.addEventListener('track', this._ontrack = f);
  1028. },
  1029. enumerable: true,
  1030. configurable: true
  1031. });
  1032. const origSetRemoteDescription =
  1033. window.RTCPeerConnection.prototype.setRemoteDescription;
  1034. window.RTCPeerConnection.prototype.setRemoteDescription =
  1035. function setRemoteDescription() {
  1036. if (!this._ontrackpoly) {
  1037. this._ontrackpoly = (e) => {
  1038. // onaddstream does not fire when a track is added to an existing
  1039. // stream. But stream.onaddtrack is implemented so we use that.
  1040. e.stream.addEventListener('addtrack', te => {
  1041. let receiver;
  1042. if (window.RTCPeerConnection.prototype.getReceivers) {
  1043. receiver = this.getReceivers()
  1044. .find(r => r.track && r.track.id === te.track.id);
  1045. } else {
  1046. receiver = {
  1047. track: te.track
  1048. };
  1049. }
  1050. const event = new Event('track');
  1051. event.track = te.track;
  1052. event.receiver = receiver;
  1053. event.transceiver = {
  1054. receiver
  1055. };
  1056. event.streams = [e.stream];
  1057. this.dispatchEvent(event);
  1058. });
  1059. e.stream.getTracks().forEach(track => {
  1060. let receiver;
  1061. if (window.RTCPeerConnection.prototype.getReceivers) {
  1062. receiver = this.getReceivers()
  1063. .find(r => r.track && r.track.id === track.id);
  1064. } else {
  1065. receiver = {
  1066. track
  1067. };
  1068. }
  1069. const event = new Event('track');
  1070. event.track = track;
  1071. event.receiver = receiver;
  1072. event.transceiver = {
  1073. receiver
  1074. };
  1075. event.streams = [e.stream];
  1076. this.dispatchEvent(event);
  1077. });
  1078. };
  1079. this.addEventListener('addstream', this._ontrackpoly);
  1080. }
  1081. return origSetRemoteDescription.apply(this, arguments);
  1082. };
  1083. } else {
  1084. // even if RTCRtpTransceiver is in window, it is only used and
  1085. // emitted in unified-plan. Unfortunately this means we need
  1086. // to unconditionally wrap the event.
  1087. wrapPeerConnectionEvent(window, 'track', e => {
  1088. if (!e.transceiver) {
  1089. Object.defineProperty(e, 'transceiver', {
  1090. value: {
  1091. receiver: e.receiver
  1092. }
  1093. });
  1094. }
  1095. return e;
  1096. });
  1097. }
  1098. }
  1099. function shimGetSendersWithDtmf(window) {
  1100. // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
  1101. if (typeof window === 'object' && window.RTCPeerConnection &&
  1102. !('getSenders' in window.RTCPeerConnection.prototype) &&
  1103. 'createDTMFSender' in window.RTCPeerConnection.prototype) {
  1104. const shimSenderWithDtmf = function(pc, track) {
  1105. return {
  1106. track,
  1107. get dtmf() {
  1108. if (this._dtmf === undefined) {
  1109. if (track.kind === 'audio') {
  1110. this._dtmf = pc.createDTMFSender(track);
  1111. } else {
  1112. this._dtmf = null;
  1113. }
  1114. }
  1115. return this._dtmf;
  1116. },
  1117. _pc: pc
  1118. };
  1119. };
  1120. // augment addTrack when getSenders is not available.
  1121. if (!window.RTCPeerConnection.prototype.getSenders) {
  1122. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  1123. this._senders = this._senders || [];
  1124. return this._senders.slice(); // return a copy of the internal state.
  1125. };
  1126. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  1127. window.RTCPeerConnection.prototype.addTrack =
  1128. function addTrack(track, stream) {
  1129. let sender = origAddTrack.apply(this, arguments);
  1130. if (!sender) {
  1131. sender = shimSenderWithDtmf(this, track);
  1132. this._senders.push(sender);
  1133. }
  1134. return sender;
  1135. };
  1136. const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  1137. window.RTCPeerConnection.prototype.removeTrack =
  1138. function removeTrack(sender) {
  1139. origRemoveTrack.apply(this, arguments);
  1140. const idx = this._senders.indexOf(sender);
  1141. if (idx !== -1) {
  1142. this._senders.splice(idx, 1);
  1143. }
  1144. };
  1145. }
  1146. const origAddStream = window.RTCPeerConnection.prototype.addStream;
  1147. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  1148. this._senders = this._senders || [];
  1149. origAddStream.apply(this, [stream]);
  1150. stream.getTracks().forEach(track => {
  1151. this._senders.push(shimSenderWithDtmf(this, track));
  1152. });
  1153. };
  1154. const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  1155. window.RTCPeerConnection.prototype.removeStream =
  1156. function removeStream(stream) {
  1157. this._senders = this._senders || [];
  1158. origRemoveStream.apply(this, [stream]);
  1159. stream.getTracks().forEach(track => {
  1160. const sender = this._senders.find(s => s.track === track);
  1161. if (sender) { // remove sender
  1162. this._senders.splice(this._senders.indexOf(sender), 1);
  1163. }
  1164. });
  1165. };
  1166. } else if (typeof window === 'object' && window.RTCPeerConnection &&
  1167. 'getSenders' in window.RTCPeerConnection.prototype &&
  1168. 'createDTMFSender' in window.RTCPeerConnection.prototype &&
  1169. window.RTCRtpSender &&
  1170. !('dtmf' in window.RTCRtpSender.prototype)) {
  1171. const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  1172. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  1173. const senders = origGetSenders.apply(this, []);
  1174. senders.forEach(sender => sender._pc = this);
  1175. return senders;
  1176. };
  1177. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  1178. get() {
  1179. if (this._dtmf === undefined) {
  1180. if (this.track.kind === 'audio') {
  1181. this._dtmf = this._pc.createDTMFSender(this.track);
  1182. } else {
  1183. this._dtmf = null;
  1184. }
  1185. }
  1186. return this._dtmf;
  1187. }
  1188. });
  1189. }
  1190. }
  1191. function shimGetStats(window) {
  1192. if (!window.RTCPeerConnection) {
  1193. return;
  1194. }
  1195. const origGetStats = window.RTCPeerConnection.prototype.getStats;
  1196. window.RTCPeerConnection.prototype.getStats = function getStats() {
  1197. const [selector, onSucc, onErr] = arguments;
  1198. // If selector is a function then we are in the old style stats so just
  1199. // pass back the original getStats format to avoid breaking old users.
  1200. if (arguments.length > 0 && typeof selector === 'function') {
  1201. return origGetStats.apply(this, arguments);
  1202. }
  1203. // When spec-style getStats is supported, return those when called with
  1204. // either no arguments or the selector argument is null.
  1205. if (origGetStats.length === 0 && (arguments.length === 0 ||
  1206. typeof selector !== 'function')) {
  1207. return origGetStats.apply(this, []);
  1208. }
  1209. const fixChromeStats_ = function(response) {
  1210. const standardReport = {};
  1211. const reports = response.result();
  1212. reports.forEach(report => {
  1213. const standardStats = {
  1214. id: report.id,
  1215. timestamp: report.timestamp,
  1216. type: {
  1217. localcandidate: 'local-candidate',
  1218. remotecandidate: 'remote-candidate'
  1219. } [report.type] || report.type
  1220. };
  1221. report.names().forEach(name => {
  1222. standardStats[name] = report.stat(name);
  1223. });
  1224. standardReport[standardStats.id] = standardStats;
  1225. });
  1226. return standardReport;
  1227. };
  1228. // shim getStats with maplike support
  1229. const makeMapStats = function(stats) {
  1230. return new Map(Object.keys(stats).map(key => [key, stats[key]]));
  1231. };
  1232. if (arguments.length >= 2) {
  1233. const successCallbackWrapper_ = function(response) {
  1234. onSucc(makeMapStats(fixChromeStats_(response)));
  1235. };
  1236. return origGetStats.apply(this, [successCallbackWrapper_,
  1237. selector
  1238. ]);
  1239. }
  1240. // promise-support
  1241. return new Promise((resolve, reject) => {
  1242. origGetStats.apply(this, [
  1243. function(response) {
  1244. resolve(makeMapStats(fixChromeStats_(response)));
  1245. },
  1246. reject
  1247. ]);
  1248. }).then(onSucc, onErr);
  1249. };
  1250. }
  1251. function shimSenderReceiverGetStats(window) {
  1252. if (!(typeof window === 'object' && window.RTCPeerConnection &&
  1253. window.RTCRtpSender && window.RTCRtpReceiver)) {
  1254. return;
  1255. }
  1256. // shim sender stats.
  1257. if (!('getStats' in window.RTCRtpSender.prototype)) {
  1258. const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  1259. if (origGetSenders) {
  1260. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  1261. const senders = origGetSenders.apply(this, []);
  1262. senders.forEach(sender => sender._pc = this);
  1263. return senders;
  1264. };
  1265. }
  1266. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  1267. if (origAddTrack) {
  1268. window.RTCPeerConnection.prototype.addTrack = function addTrack() {
  1269. const sender = origAddTrack.apply(this, arguments);
  1270. sender._pc = this;
  1271. return sender;
  1272. };
  1273. }
  1274. window.RTCRtpSender.prototype.getStats = function getStats() {
  1275. const sender = this;
  1276. return this._pc.getStats().then(result =>
  1277. /* Note: this will include stats of all senders that
  1278. * send a track with the same id as sender.track as
  1279. * it is not possible to identify the RTCRtpSender.
  1280. */
  1281. filterStats(result, sender.track, true));
  1282. };
  1283. }
  1284. // shim receiver stats.
  1285. if (!('getStats' in window.RTCRtpReceiver.prototype)) {
  1286. const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
  1287. if (origGetReceivers) {
  1288. window.RTCPeerConnection.prototype.getReceivers =
  1289. function getReceivers() {
  1290. const receivers = origGetReceivers.apply(this, []);
  1291. receivers.forEach(receiver => receiver._pc = this);
  1292. return receivers;
  1293. };
  1294. }
  1295. wrapPeerConnectionEvent(window, 'track', e => {
  1296. e.receiver._pc = e.srcElement;
  1297. return e;
  1298. });
  1299. window.RTCRtpReceiver.prototype.getStats = function getStats() {
  1300. const receiver = this;
  1301. return this._pc.getStats().then(result =>
  1302. filterStats(result, receiver.track, false));
  1303. };
  1304. }
  1305. if (!('getStats' in window.RTCRtpSender.prototype &&
  1306. 'getStats' in window.RTCRtpReceiver.prototype)) {
  1307. return;
  1308. }
  1309. // shim RTCPeerConnection.getStats(track).
  1310. const origGetStats = window.RTCPeerConnection.prototype.getStats;
  1311. window.RTCPeerConnection.prototype.getStats = function getStats() {
  1312. if (arguments.length > 0 &&
  1313. arguments[0] instanceof window.MediaStreamTrack) {
  1314. const track = arguments[0];
  1315. let sender;
  1316. let receiver;
  1317. let err;
  1318. this.getSenders().forEach(s => {
  1319. if (s.track === track) {
  1320. if (sender) {
  1321. err = true;
  1322. } else {
  1323. sender = s;
  1324. }
  1325. }
  1326. });
  1327. this.getReceivers().forEach(r => {
  1328. if (r.track === track) {
  1329. if (receiver) {
  1330. err = true;
  1331. } else {
  1332. receiver = r;
  1333. }
  1334. }
  1335. return r.track === track;
  1336. });
  1337. if (err || (sender && receiver)) {
  1338. return Promise.reject(new DOMException(
  1339. 'There are more than one sender or receiver for the track.',
  1340. 'InvalidAccessError'));
  1341. } else if (sender) {
  1342. return sender.getStats();
  1343. } else if (receiver) {
  1344. return receiver.getStats();
  1345. }
  1346. return Promise.reject(new DOMException(
  1347. 'There is no sender or receiver for the track.',
  1348. 'InvalidAccessError'));
  1349. }
  1350. return origGetStats.apply(this, arguments);
  1351. };
  1352. }
  1353. function shimAddTrackRemoveTrackWithNative(window) {
  1354. // shim addTrack/removeTrack with native variants in order to make
  1355. // the interactions with legacy getLocalStreams behave as in other browsers.
  1356. // Keeps a mapping stream.id => [stream, rtpsenders...]
  1357. window.RTCPeerConnection.prototype.getLocalStreams =
  1358. function getLocalStreams() {
  1359. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  1360. return Object.keys(this._shimmedLocalStreams)
  1361. .map(streamId => this._shimmedLocalStreams[streamId][0]);
  1362. };
  1363. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  1364. window.RTCPeerConnection.prototype.addTrack =
  1365. function addTrack(track, stream) {
  1366. if (!stream) {
  1367. return origAddTrack.apply(this, arguments);
  1368. }
  1369. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  1370. const sender = origAddTrack.apply(this, arguments);
  1371. if (!this._shimmedLocalStreams[stream.id]) {
  1372. this._shimmedLocalStreams[stream.id] = [stream, sender];
  1373. } else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) {
  1374. this._shimmedLocalStreams[stream.id].push(sender);
  1375. }
  1376. return sender;
  1377. };
  1378. const origAddStream = window.RTCPeerConnection.prototype.addStream;
  1379. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  1380. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  1381. stream.getTracks().forEach(track => {
  1382. const alreadyExists = this.getSenders().find(s => s.track === track);
  1383. if (alreadyExists) {
  1384. throw new DOMException('Track already exists.',
  1385. 'InvalidAccessError');
  1386. }
  1387. });
  1388. const existingSenders = this.getSenders();
  1389. origAddStream.apply(this, arguments);
  1390. const newSenders = this.getSenders()
  1391. .filter(newSender => existingSenders.indexOf(newSender) === -1);
  1392. this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders);
  1393. };
  1394. const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  1395. window.RTCPeerConnection.prototype.removeStream =
  1396. function removeStream(stream) {
  1397. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  1398. delete this._shimmedLocalStreams[stream.id];
  1399. return origRemoveStream.apply(this, arguments);
  1400. };
  1401. const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  1402. window.RTCPeerConnection.prototype.removeTrack =
  1403. function removeTrack(sender) {
  1404. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  1405. if (sender) {
  1406. Object.keys(this._shimmedLocalStreams).forEach(streamId => {
  1407. const idx = this._shimmedLocalStreams[streamId].indexOf(sender);
  1408. if (idx !== -1) {
  1409. this._shimmedLocalStreams[streamId].splice(idx, 1);
  1410. }
  1411. if (this._shimmedLocalStreams[streamId].length === 1) {
  1412. delete this._shimmedLocalStreams[streamId];
  1413. }
  1414. });
  1415. }
  1416. return origRemoveTrack.apply(this, arguments);
  1417. };
  1418. }
  1419. function shimAddTrackRemoveTrack(window, browserDetails) {
  1420. if (!window.RTCPeerConnection) {
  1421. return;
  1422. }
  1423. // shim addTrack and removeTrack.
  1424. if (window.RTCPeerConnection.prototype.addTrack &&
  1425. browserDetails.version >= 65) {
  1426. return shimAddTrackRemoveTrackWithNative(window);
  1427. }
  1428. // also shim pc.getLocalStreams when addTrack is shimmed
  1429. // to return the original streams.
  1430. const origGetLocalStreams = window.RTCPeerConnection.prototype
  1431. .getLocalStreams;
  1432. window.RTCPeerConnection.prototype.getLocalStreams =
  1433. function getLocalStreams() {
  1434. const nativeStreams = origGetLocalStreams.apply(this);
  1435. this._reverseStreams = this._reverseStreams || {};
  1436. return nativeStreams.map(stream => this._reverseStreams[stream.id]);
  1437. };
  1438. const origAddStream = window.RTCPeerConnection.prototype.addStream;
  1439. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  1440. this._streams = this._streams || {};
  1441. this._reverseStreams = this._reverseStreams || {};
  1442. stream.getTracks().forEach(track => {
  1443. const alreadyExists = this.getSenders().find(s => s.track === track);
  1444. if (alreadyExists) {
  1445. throw new DOMException('Track already exists.',
  1446. 'InvalidAccessError');
  1447. }
  1448. });
  1449. // Add identity mapping for consistency with addTrack.
  1450. // Unless this is being used with a stream from addTrack.
  1451. if (!this._reverseStreams[stream.id]) {
  1452. const newStream = new window.MediaStream(stream.getTracks());
  1453. this._streams[stream.id] = newStream;
  1454. this._reverseStreams[newStream.id] = stream;
  1455. stream = newStream;
  1456. }
  1457. origAddStream.apply(this, [stream]);
  1458. };
  1459. const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  1460. window.RTCPeerConnection.prototype.removeStream =
  1461. function removeStream(stream) {
  1462. this._streams = this._streams || {};
  1463. this._reverseStreams = this._reverseStreams || {};
  1464. origRemoveStream.apply(this, [(this._streams[stream.id] || stream)]);
  1465. delete this._reverseStreams[(this._streams[stream.id] ?
  1466. this._streams[stream.id].id : stream.id)];
  1467. delete this._streams[stream.id];
  1468. };
  1469. window.RTCPeerConnection.prototype.addTrack =
  1470. function addTrack(track, stream) {
  1471. if (this.signalingState === 'closed') {
  1472. throw new DOMException(
  1473. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  1474. 'InvalidStateError');
  1475. }
  1476. const streams = [].slice.call(arguments, 1);
  1477. if (streams.length !== 1 ||
  1478. !streams[0].getTracks().find(t => t === track)) {
  1479. // this is not fully correct but all we can manage without
  1480. // [[associated MediaStreams]] internal slot.
  1481. throw new DOMException(
  1482. 'The adapter.js addTrack polyfill only supports a single ' +
  1483. ' stream which is associated with the specified track.',
  1484. 'NotSupportedError');
  1485. }
  1486. const alreadyExists = this.getSenders().find(s => s.track === track);
  1487. if (alreadyExists) {
  1488. throw new DOMException('Track already exists.',
  1489. 'InvalidAccessError');
  1490. }
  1491. this._streams = this._streams || {};
  1492. this._reverseStreams = this._reverseStreams || {};
  1493. const oldStream = this._streams[stream.id];
  1494. if (oldStream) {
  1495. // this is using odd Chrome behaviour, use with caution:
  1496. // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
  1497. // Note: we rely on the high-level addTrack/dtmf shim to
  1498. // create the sender with a dtmf sender.
  1499. oldStream.addTrack(track);
  1500. // Trigger ONN async.
  1501. Promise.resolve().then(() => {
  1502. this.dispatchEvent(new Event('negotiationneeded'));
  1503. });
  1504. } else {
  1505. const newStream = new window.MediaStream([track]);
  1506. this._streams[stream.id] = newStream;
  1507. this._reverseStreams[newStream.id] = stream;
  1508. this.addStream(newStream);
  1509. }
  1510. return this.getSenders().find(s => s.track === track);
  1511. };
  1512. // replace the internal stream id with the external one and
  1513. // vice versa.
  1514. function replaceInternalStreamId(pc, description) {
  1515. let sdp = description.sdp;
  1516. Object.keys(pc._reverseStreams || []).forEach(internalId => {
  1517. const externalStream = pc._reverseStreams[internalId];
  1518. const internalStream = pc._streams[externalStream.id];
  1519. sdp = sdp.replace(new RegExp(internalStream.id, 'g'),
  1520. externalStream.id);
  1521. });
  1522. return new RTCSessionDescription({
  1523. type: description.type,
  1524. sdp
  1525. });
  1526. }
  1527. function replaceExternalStreamId(pc, description) {
  1528. let sdp = description.sdp;
  1529. Object.keys(pc._reverseStreams || []).forEach(internalId => {
  1530. const externalStream = pc._reverseStreams[internalId];
  1531. const internalStream = pc._streams[externalStream.id];
  1532. sdp = sdp.replace(new RegExp(externalStream.id, 'g'),
  1533. internalStream.id);
  1534. });
  1535. return new RTCSessionDescription({
  1536. type: description.type,
  1537. sdp
  1538. });
  1539. }
  1540. ['createOffer', 'createAnswer'].forEach(function(method) {
  1541. const nativeMethod = window.RTCPeerConnection.prototype[method];
  1542. const methodObj = {
  1543. [method]() {
  1544. const args = arguments;
  1545. const isLegacyCall = arguments.length &&
  1546. typeof arguments[0] === 'function';
  1547. if (isLegacyCall) {
  1548. return nativeMethod.apply(this, [
  1549. (description) => {
  1550. const desc = replaceInternalStreamId(this, description);
  1551. args[0].apply(null, [desc]);
  1552. },
  1553. (err) => {
  1554. if (args[1]) {
  1555. args[1].apply(null, err);
  1556. }
  1557. },
  1558. arguments[2]
  1559. ]);
  1560. }
  1561. return nativeMethod.apply(this, arguments)
  1562. .then(description => replaceInternalStreamId(this, description));
  1563. }
  1564. };
  1565. window.RTCPeerConnection.prototype[method] = methodObj[method];
  1566. });
  1567. const origSetLocalDescription =
  1568. window.RTCPeerConnection.prototype.setLocalDescription;
  1569. window.RTCPeerConnection.prototype.setLocalDescription =
  1570. function setLocalDescription() {
  1571. if (!arguments.length || !arguments[0].type) {
  1572. return origSetLocalDescription.apply(this, arguments);
  1573. }
  1574. arguments[0] = replaceExternalStreamId(this, arguments[0]);
  1575. return origSetLocalDescription.apply(this, arguments);
  1576. };
  1577. // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
  1578. const origLocalDescription = Object.getOwnPropertyDescriptor(
  1579. window.RTCPeerConnection.prototype, 'localDescription');
  1580. Object.defineProperty(window.RTCPeerConnection.prototype,
  1581. 'localDescription', {
  1582. get() {
  1583. const description = origLocalDescription.get.apply(this);
  1584. if (description.type === '') {
  1585. return description;
  1586. }
  1587. return replaceInternalStreamId(this, description);
  1588. }
  1589. });
  1590. window.RTCPeerConnection.prototype.removeTrack =
  1591. function removeTrack(sender) {
  1592. if (this.signalingState === 'closed') {
  1593. throw new DOMException(
  1594. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  1595. 'InvalidStateError');
  1596. }
  1597. // We can not yet check for sender instanceof RTCRtpSender
  1598. // since we shim RTPSender. So we check if sender._pc is set.
  1599. if (!sender._pc) {
  1600. throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' +
  1601. 'does not implement interface RTCRtpSender.', 'TypeError');
  1602. }
  1603. const isLocal = sender._pc === this;
  1604. if (!isLocal) {
  1605. throw new DOMException('Sender was not created by this connection.',
  1606. 'InvalidAccessError');
  1607. }
  1608. // Search for the native stream the senders track belongs to.
  1609. this._streams = this._streams || {};
  1610. let stream;
  1611. Object.keys(this._streams).forEach(streamid => {
  1612. const hasTrack = this._streams[streamid].getTracks()
  1613. .find(track => sender.track === track);
  1614. if (hasTrack) {
  1615. stream = this._streams[streamid];
  1616. }
  1617. });
  1618. if (stream) {
  1619. if (stream.getTracks().length === 1) {
  1620. // if this is the last track of the stream, remove the stream. This
  1621. // takes care of any shimmed _senders.
  1622. this.removeStream(this._reverseStreams[stream.id]);
  1623. } else {
  1624. // relying on the same odd chrome behaviour as above.
  1625. stream.removeTrack(sender.track);
  1626. }
  1627. this.dispatchEvent(new Event('negotiationneeded'));
  1628. }
  1629. };
  1630. }
  1631. function shimPeerConnection$2(window, browserDetails) {
  1632. if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {
  1633. // very basic support for old versions.
  1634. window.RTCPeerConnection = window.webkitRTCPeerConnection;
  1635. }
  1636. if (!window.RTCPeerConnection) {
  1637. return;
  1638. }
  1639. // shim implicit creation of RTCSessionDescription/RTCIceCandidate
  1640. if (browserDetails.version < 53) {
  1641. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  1642. .forEach(function(method) {
  1643. const nativeMethod = window.RTCPeerConnection.prototype[method];
  1644. const methodObj = {
  1645. [method]() {
  1646. arguments[0] = new((method === 'addIceCandidate') ?
  1647. window.RTCIceCandidate :
  1648. window.RTCSessionDescription)(arguments[0]);
  1649. return nativeMethod.apply(this, arguments);
  1650. }
  1651. };
  1652. window.RTCPeerConnection.prototype[method] = methodObj[method];
  1653. });
  1654. }
  1655. }
  1656. // Attempt to fix ONN in plan-b mode.
  1657. function fixNegotiationNeeded(window, browserDetails) {
  1658. wrapPeerConnectionEvent(window, 'negotiationneeded', e => {
  1659. const pc = e.target;
  1660. if (browserDetails.version < 72 || (pc.getConfiguration &&
  1661. pc.getConfiguration().sdpSemantics === 'plan-b')) {
  1662. if (pc.signalingState !== 'stable') {
  1663. return;
  1664. }
  1665. }
  1666. return e;
  1667. });
  1668. }
  1669. var chromeShim = /*#__PURE__*/ Object.freeze({
  1670. __proto__: null,
  1671. shimMediaStream: shimMediaStream,
  1672. shimOnTrack: shimOnTrack$1,
  1673. shimGetSendersWithDtmf: shimGetSendersWithDtmf,
  1674. shimGetStats: shimGetStats,
  1675. shimSenderReceiverGetStats: shimSenderReceiverGetStats,
  1676. shimAddTrackRemoveTrackWithNative: shimAddTrackRemoveTrackWithNative,
  1677. shimAddTrackRemoveTrack: shimAddTrackRemoveTrack,
  1678. shimPeerConnection: shimPeerConnection$2,
  1679. fixNegotiationNeeded: fixNegotiationNeeded,
  1680. shimGetUserMedia: shimGetUserMedia$3,
  1681. shimGetDisplayMedia: shimGetDisplayMedia$2
  1682. });
  1683. /*
  1684. * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
  1685. *
  1686. * Use of this source code is governed by a BSD-style license
  1687. * that can be found in the LICENSE file in the root of the source
  1688. * tree.
  1689. */
  1690. // Edge does not like
  1691. // 1) stun: filtered after 14393 unless ?transport=udp is present
  1692. // 2) turn: that does not have all of turn:host:port?transport=udp
  1693. // 3) turn: with ipv6 addresses
  1694. // 4) turn: occurring muliple times
  1695. function filterIceServers$1(iceServers, edgeVersion) {
  1696. let hasTurn = false;
  1697. iceServers = JSON.parse(JSON.stringify(iceServers));
  1698. return iceServers.filter(server => {
  1699. if (server && (server.urls || server.url)) {
  1700. let urls = server.urls || server.url;
  1701. if (server.url && !server.urls) {
  1702. deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  1703. }
  1704. const isString = typeof urls === 'string';
  1705. if (isString) {
  1706. urls = [urls];
  1707. }
  1708. urls = urls.filter(url => {
  1709. // filter STUN unconditionally.
  1710. if (url.indexOf('stun:') === 0) {
  1711. return false;
  1712. }
  1713. const validTurn = url.startsWith('turn') &&
  1714. !url.startsWith('turn:[') &&
  1715. url.includes('transport=udp');
  1716. if (validTurn && !hasTurn) {
  1717. hasTurn = true;
  1718. return true;
  1719. }
  1720. return validTurn && !hasTurn;
  1721. });
  1722. delete server.url;
  1723. server.urls = isString ? urls[0] : urls;
  1724. return !!urls.length;
  1725. }
  1726. });
  1727. }
  1728. function createCommonjsModule(fn) {
  1729. var module = {
  1730. exports: {}
  1731. };
  1732. return fn(module, module.exports), module.exports;
  1733. }
  1734. /* eslint-env node */
  1735. var sdp = createCommonjsModule(function(module) {
  1736. // SDP helpers.
  1737. var SDPUtils = {};
  1738. // Generate an alphanumeric identifier for cname or mids.
  1739. // TODO: use UUIDs instead? https://gist.github.com/jed/982883
  1740. SDPUtils.generateIdentifier = function() {
  1741. return Math.random().toString(36).substr(2, 10);
  1742. };
  1743. // The RTCP CNAME used by all peerconnections from the same JS.
  1744. SDPUtils.localCName = SDPUtils.generateIdentifier();
  1745. // Splits SDP into lines, dealing with both CRLF and LF.
  1746. SDPUtils.splitLines = function(blob) {
  1747. return blob.trim().split('\n').map(function(line) {
  1748. return line.trim();
  1749. });
  1750. };
  1751. // Splits SDP into sessionpart and mediasections. Ensures CRLF.
  1752. SDPUtils.splitSections = function(blob) {
  1753. var parts = blob.split('\nm=');
  1754. return parts.map(function(part, index) {
  1755. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  1756. });
  1757. };
  1758. // returns the session description.
  1759. SDPUtils.getDescription = function(blob) {
  1760. var sections = SDPUtils.splitSections(blob);
  1761. return sections && sections[0];
  1762. };
  1763. // returns the individual media sections.
  1764. SDPUtils.getMediaSections = function(blob) {
  1765. var sections = SDPUtils.splitSections(blob);
  1766. sections.shift();
  1767. return sections;
  1768. };
  1769. // Returns lines that start with a certain prefix.
  1770. SDPUtils.matchPrefix = function(blob, prefix) {
  1771. return SDPUtils.splitLines(blob).filter(function(line) {
  1772. return line.indexOf(prefix) === 0;
  1773. });
  1774. };
  1775. // Parses an ICE candidate line. Sample input:
  1776. // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
  1777. // rport 55996"
  1778. SDPUtils.parseCandidate = function(line) {
  1779. var parts;
  1780. // Parse both variants.
  1781. if (line.indexOf('a=candidate:') === 0) {
  1782. parts = line.substring(12).split(' ');
  1783. } else {
  1784. parts = line.substring(10).split(' ');
  1785. }
  1786. var candidate = {
  1787. foundation: parts[0],
  1788. component: parseInt(parts[1], 10),
  1789. protocol: parts[2].toLowerCase(),
  1790. priority: parseInt(parts[3], 10),
  1791. ip: parts[4],
  1792. address: parts[4], // address is an alias for ip.
  1793. port: parseInt(parts[5], 10),
  1794. // skip parts[6] == 'typ'
  1795. type: parts[7]
  1796. };
  1797. for (var i = 8; i < parts.length; i += 2) {
  1798. switch (parts[i]) {
  1799. case 'raddr':
  1800. candidate.relatedAddress = parts[i + 1];
  1801. break;
  1802. case 'rport':
  1803. candidate.relatedPort = parseInt(parts[i + 1], 10);
  1804. break;
  1805. case 'tcptype':
  1806. candidate.tcpType = parts[i + 1];
  1807. break;
  1808. case 'ufrag':
  1809. candidate.ufrag = parts[i + 1]; // for backward compability.
  1810. candidate.usernameFragment = parts[i + 1];
  1811. break;
  1812. default: // extension handling, in particular ufrag
  1813. candidate[parts[i]] = parts[i + 1];
  1814. break;
  1815. }
  1816. }
  1817. return candidate;
  1818. };
  1819. // Translates a candidate object into SDP candidate attribute.
  1820. SDPUtils.writeCandidate = function(candidate) {
  1821. var sdp = [];
  1822. sdp.push(candidate.foundation);
  1823. sdp.push(candidate.component);
  1824. sdp.push(candidate.protocol.toUpperCase());
  1825. sdp.push(candidate.priority);
  1826. sdp.push(candidate.address || candidate.ip);
  1827. sdp.push(candidate.port);
  1828. var type = candidate.type;
  1829. sdp.push('typ');
  1830. sdp.push(type);
  1831. if (type !== 'host' && candidate.relatedAddress &&
  1832. candidate.relatedPort) {
  1833. sdp.push('raddr');
  1834. sdp.push(candidate.relatedAddress);
  1835. sdp.push('rport');
  1836. sdp.push(candidate.relatedPort);
  1837. }
  1838. if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
  1839. sdp.push('tcptype');
  1840. sdp.push(candidate.tcpType);
  1841. }
  1842. if (candidate.usernameFragment || candidate.ufrag) {
  1843. sdp.push('ufrag');
  1844. sdp.push(candidate.usernameFragment || candidate.ufrag);
  1845. }
  1846. return 'candidate:' + sdp.join(' ');
  1847. };
  1848. // Parses an ice-options line, returns an array of option tags.
  1849. // a=ice-options:foo bar
  1850. SDPUtils.parseIceOptions = function(line) {
  1851. return line.substr(14).split(' ');
  1852. };
  1853. // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
  1854. // a=rtpmap:111 opus/48000/2
  1855. SDPUtils.parseRtpMap = function(line) {
  1856. var parts = line.substr(9).split(' ');
  1857. var parsed = {
  1858. payloadType: parseInt(parts.shift(), 10) // was: id
  1859. };
  1860. parts = parts[0].split('/');
  1861. parsed.name = parts[0];
  1862. parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
  1863. parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
  1864. // legacy alias, got renamed back to channels in ORTC.
  1865. parsed.numChannels = parsed.channels;
  1866. return parsed;
  1867. };
  1868. // Generate an a=rtpmap line from RTCRtpCodecCapability or
  1869. // RTCRtpCodecParameters.
  1870. SDPUtils.writeRtpMap = function(codec) {
  1871. var pt = codec.payloadType;
  1872. if (codec.preferredPayloadType !== undefined) {
  1873. pt = codec.preferredPayloadType;
  1874. }
  1875. var channels = codec.channels || codec.numChannels || 1;
  1876. return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
  1877. (channels !== 1 ? '/' + channels : '') + '\r\n';
  1878. };
  1879. // Parses an a=extmap line (headerextension from RFC 5285). Sample input:
  1880. // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  1881. // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
  1882. SDPUtils.parseExtmap = function(line) {
  1883. var parts = line.substr(9).split(' ');
  1884. return {
  1885. id: parseInt(parts[0], 10),
  1886. direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
  1887. uri: parts[1]
  1888. };
  1889. };
  1890. // Generates a=extmap line from RTCRtpHeaderExtensionParameters or
  1891. // RTCRtpHeaderExtension.
  1892. SDPUtils.writeExtmap = function(headerExtension) {
  1893. return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
  1894. (headerExtension.direction && headerExtension.direction !== 'sendrecv' ?
  1895. '/' + headerExtension.direction :
  1896. '') +
  1897. ' ' + headerExtension.uri + '\r\n';
  1898. };
  1899. // Parses an ftmp line, returns dictionary. Sample input:
  1900. // a=fmtp:96 vbr=on;cng=on
  1901. // Also deals with vbr=on; cng=on
  1902. SDPUtils.parseFmtp = function(line) {
  1903. var parsed = {};
  1904. var kv;
  1905. var parts = line.substr(line.indexOf(' ') + 1).split(';');
  1906. for (var j = 0; j < parts.length; j++) {
  1907. kv = parts[j].trim().split('=');
  1908. parsed[kv[0].trim()] = kv[1];
  1909. }
  1910. return parsed;
  1911. };
  1912. // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
  1913. SDPUtils.writeFmtp = function(codec) {
  1914. var line = '';
  1915. var pt = codec.payloadType;
  1916. if (codec.preferredPayloadType !== undefined) {
  1917. pt = codec.preferredPayloadType;
  1918. }
  1919. if (codec.parameters && Object.keys(codec.parameters).length) {
  1920. var params = [];
  1921. Object.keys(codec.parameters).forEach(function(param) {
  1922. if (codec.parameters[param]) {
  1923. params.push(param + '=' + codec.parameters[param]);
  1924. } else {
  1925. params.push(param);
  1926. }
  1927. });
  1928. line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
  1929. }
  1930. return line;
  1931. };
  1932. // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
  1933. // a=rtcp-fb:98 nack rpsi
  1934. SDPUtils.parseRtcpFb = function(line) {
  1935. var parts = line.substr(line.indexOf(' ') + 1).split(' ');
  1936. return {
  1937. type: parts.shift(),
  1938. parameter: parts.join(' ')
  1939. };
  1940. };
  1941. // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
  1942. SDPUtils.writeRtcpFb = function(codec) {
  1943. var lines = '';
  1944. var pt = codec.payloadType;
  1945. if (codec.preferredPayloadType !== undefined) {
  1946. pt = codec.preferredPayloadType;
  1947. }
  1948. if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
  1949. // FIXME: special handling for trr-int?
  1950. codec.rtcpFeedback.forEach(function(fb) {
  1951. lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
  1952. (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
  1953. '\r\n';
  1954. });
  1955. }
  1956. return lines;
  1957. };
  1958. // Parses an RFC 5576 ssrc media attribute. Sample input:
  1959. // a=ssrc:3735928559 cname:something
  1960. SDPUtils.parseSsrcMedia = function(line) {
  1961. var sp = line.indexOf(' ');
  1962. var parts = {
  1963. ssrc: parseInt(line.substr(7, sp - 7), 10)
  1964. };
  1965. var colon = line.indexOf(':', sp);
  1966. if (colon > -1) {
  1967. parts.attribute = line.substr(sp + 1, colon - sp - 1);
  1968. parts.value = line.substr(colon + 1);
  1969. } else {
  1970. parts.attribute = line.substr(sp + 1);
  1971. }
  1972. return parts;
  1973. };
  1974. SDPUtils.parseSsrcGroup = function(line) {
  1975. var parts = line.substr(13).split(' ');
  1976. return {
  1977. semantics: parts.shift(),
  1978. ssrcs: parts.map(function(ssrc) {
  1979. return parseInt(ssrc, 10);
  1980. })
  1981. };
  1982. };
  1983. // Extracts the MID (RFC 5888) from a media section.
  1984. // returns the MID or undefined if no mid line was found.
  1985. SDPUtils.getMid = function(mediaSection) {
  1986. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
  1987. if (mid) {
  1988. return mid.substr(6);
  1989. }
  1990. };
  1991. SDPUtils.parseFingerprint = function(line) {
  1992. var parts = line.substr(14).split(' ');
  1993. return {
  1994. algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
  1995. value: parts[1]
  1996. };
  1997. };
  1998. // Extracts DTLS parameters from SDP media section or sessionpart.
  1999. // FIXME: for consistency with other functions this should only
  2000. // get the fingerprint line as input. See also getIceParameters.
  2001. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
  2002. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
  2003. 'a=fingerprint:');
  2004. // Note: a=setup line is ignored since we use the 'auto' role.
  2005. // Note2: 'algorithm' is not case sensitive except in Edge.
  2006. return {
  2007. role: 'auto',
  2008. fingerprints: lines.map(SDPUtils.parseFingerprint)
  2009. };
  2010. };
  2011. // Serializes DTLS parameters to SDP.
  2012. SDPUtils.writeDtlsParameters = function(params, setupType) {
  2013. var sdp = 'a=setup:' + setupType + '\r\n';
  2014. params.fingerprints.forEach(function(fp) {
  2015. sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
  2016. });
  2017. return sdp;
  2018. };
  2019. // Parses a=crypto lines into
  2020. // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#dictionary-rtcsrtpsdesparameters-members
  2021. SDPUtils.parseCryptoLine = function(line) {
  2022. var parts = line.substr(9).split(' ');
  2023. return {
  2024. tag: parseInt(parts[0], 10),
  2025. cryptoSuite: parts[1],
  2026. keyParams: parts[2],
  2027. sessionParams: parts.slice(3),
  2028. };
  2029. };
  2030. SDPUtils.writeCryptoLine = function(parameters) {
  2031. return 'a=crypto:' + parameters.tag + ' ' +
  2032. parameters.cryptoSuite + ' ' +
  2033. (typeof parameters.keyParams === 'object' ?
  2034. SDPUtils.writeCryptoKeyParams(parameters.keyParams) :
  2035. parameters.keyParams) +
  2036. (parameters.sessionParams ? ' ' + parameters.sessionParams.join(' ') : '') +
  2037. '\r\n';
  2038. };
  2039. // Parses the crypto key parameters into
  2040. // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#rtcsrtpkeyparam*
  2041. SDPUtils.parseCryptoKeyParams = function(keyParams) {
  2042. if (keyParams.indexOf('inline:') !== 0) {
  2043. return null;
  2044. }
  2045. var parts = keyParams.substr(7).split('|');
  2046. return {
  2047. keyMethod: 'inline',
  2048. keySalt: parts[0],
  2049. lifeTime: parts[1],
  2050. mkiValue: parts[2] ? parts[2].split(':')[0] : undefined,
  2051. mkiLength: parts[2] ? parts[2].split(':')[1] : undefined,
  2052. };
  2053. };
  2054. SDPUtils.writeCryptoKeyParams = function(keyParams) {
  2055. return keyParams.keyMethod + ':' +
  2056. keyParams.keySalt +
  2057. (keyParams.lifeTime ? '|' + keyParams.lifeTime : '') +
  2058. (keyParams.mkiValue && keyParams.mkiLength ?
  2059. '|' + keyParams.mkiValue + ':' + keyParams.mkiLength :
  2060. '');
  2061. };
  2062. // Extracts all SDES paramters.
  2063. SDPUtils.getCryptoParameters = function(mediaSection, sessionpart) {
  2064. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
  2065. 'a=crypto:');
  2066. return lines.map(SDPUtils.parseCryptoLine);
  2067. };
  2068. // Parses ICE information from SDP media section or sessionpart.
  2069. // FIXME: for consistency with other functions this should only
  2070. // get the ice-ufrag and ice-pwd lines as input.
  2071. SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
  2072. var ufrag = SDPUtils.matchPrefix(mediaSection + sessionpart,
  2073. 'a=ice-ufrag:')[0];
  2074. var pwd = SDPUtils.matchPrefix(mediaSection + sessionpart,
  2075. 'a=ice-pwd:')[0];
  2076. if (!(ufrag && pwd)) {
  2077. return null;
  2078. }
  2079. return {
  2080. usernameFragment: ufrag.substr(12),
  2081. password: pwd.substr(10),
  2082. };
  2083. };
  2084. // Serializes ICE parameters to SDP.
  2085. SDPUtils.writeIceParameters = function(params) {
  2086. return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
  2087. 'a=ice-pwd:' + params.password + '\r\n';
  2088. };
  2089. // Parses the SDP media section and returns RTCRtpParameters.
  2090. SDPUtils.parseRtpParameters = function(mediaSection) {
  2091. var description = {
  2092. codecs: [],
  2093. headerExtensions: [],
  2094. fecMechanisms: [],
  2095. rtcp: []
  2096. };
  2097. var lines = SDPUtils.splitLines(mediaSection);
  2098. var mline = lines[0].split(' ');
  2099. for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
  2100. var pt = mline[i];
  2101. var rtpmapline = SDPUtils.matchPrefix(
  2102. mediaSection, 'a=rtpmap:' + pt + ' ')[0];
  2103. if (rtpmapline) {
  2104. var codec = SDPUtils.parseRtpMap(rtpmapline);
  2105. var fmtps = SDPUtils.matchPrefix(
  2106. mediaSection, 'a=fmtp:' + pt + ' ');
  2107. // Only the first a=fmtp:<pt> is considered.
  2108. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
  2109. codec.rtcpFeedback = SDPUtils.matchPrefix(
  2110. mediaSection, 'a=rtcp-fb:' + pt + ' ')
  2111. .map(SDPUtils.parseRtcpFb);
  2112. description.codecs.push(codec);
  2113. // parse FEC mechanisms from rtpmap lines.
  2114. switch (codec.name.toUpperCase()) {
  2115. case 'RED':
  2116. case 'ULPFEC':
  2117. description.fecMechanisms.push(codec.name.toUpperCase());
  2118. break;
  2119. }
  2120. }
  2121. }
  2122. SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
  2123. description.headerExtensions.push(SDPUtils.parseExtmap(line));
  2124. });
  2125. // FIXME: parse rtcp.
  2126. return description;
  2127. };
  2128. // Generates parts of the SDP media section describing the capabilities /
  2129. // parameters.
  2130. SDPUtils.writeRtpDescription = function(kind, caps) {
  2131. var sdp = '';
  2132. // Build the mline.
  2133. sdp += 'm=' + kind + ' ';
  2134. sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
  2135. sdp += ' UDP/TLS/RTP/SAVPF ';
  2136. sdp += caps.codecs.map(function(codec) {
  2137. if (codec.preferredPayloadType !== undefined) {
  2138. return codec.preferredPayloadType;
  2139. }
  2140. return codec.payloadType;
  2141. }).join(' ') + '\r\n';
  2142. sdp += 'c=IN IP4 0.0.0.0\r\n';
  2143. sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
  2144. // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
  2145. caps.codecs.forEach(function(codec) {
  2146. sdp += SDPUtils.writeRtpMap(codec);
  2147. sdp += SDPUtils.writeFmtp(codec);
  2148. sdp += SDPUtils.writeRtcpFb(codec);
  2149. });
  2150. var maxptime = 0;
  2151. caps.codecs.forEach(function(codec) {
  2152. if (codec.maxptime > maxptime) {
  2153. maxptime = codec.maxptime;
  2154. }
  2155. });
  2156. if (maxptime > 0) {
  2157. sdp += 'a=maxptime:' + maxptime + '\r\n';
  2158. }
  2159. sdp += 'a=rtcp-mux\r\n';
  2160. if (caps.headerExtensions) {
  2161. caps.headerExtensions.forEach(function(extension) {
  2162. sdp += SDPUtils.writeExtmap(extension);
  2163. });
  2164. }
  2165. // FIXME: write fecMechanisms.
  2166. return sdp;
  2167. };
  2168. // Parses the SDP media section and returns an array of
  2169. // RTCRtpEncodingParameters.
  2170. SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
  2171. var encodingParameters = [];
  2172. var description = SDPUtils.parseRtpParameters(mediaSection);
  2173. var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
  2174. var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
  2175. // filter a=ssrc:... cname:, ignore PlanB-msid
  2176. var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  2177. .map(function(line) {
  2178. return SDPUtils.parseSsrcMedia(line);
  2179. })
  2180. .filter(function(parts) {
  2181. return parts.attribute === 'cname';
  2182. });
  2183. var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
  2184. var secondarySsrc;
  2185. var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
  2186. .map(function(line) {
  2187. var parts = line.substr(17).split(' ');
  2188. return parts.map(function(part) {
  2189. return parseInt(part, 10);
  2190. });
  2191. });
  2192. if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
  2193. secondarySsrc = flows[0][1];
  2194. }
  2195. description.codecs.forEach(function(codec) {
  2196. if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
  2197. var encParam = {
  2198. ssrc: primarySsrc,
  2199. codecPayloadType: parseInt(codec.parameters.apt, 10)
  2200. };
  2201. if (primarySsrc && secondarySsrc) {
  2202. encParam.rtx = {
  2203. ssrc: secondarySsrc
  2204. };
  2205. }
  2206. encodingParameters.push(encParam);
  2207. if (hasRed) {
  2208. encParam = JSON.parse(JSON.stringify(encParam));
  2209. encParam.fec = {
  2210. ssrc: primarySsrc,
  2211. mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
  2212. };
  2213. encodingParameters.push(encParam);
  2214. }
  2215. }
  2216. });
  2217. if (encodingParameters.length === 0 && primarySsrc) {
  2218. encodingParameters.push({
  2219. ssrc: primarySsrc
  2220. });
  2221. }
  2222. // we support both b=AS and b=TIAS but interpret AS as TIAS.
  2223. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
  2224. if (bandwidth.length) {
  2225. if (bandwidth[0].indexOf('b=TIAS:') === 0) {
  2226. bandwidth = parseInt(bandwidth[0].substr(7), 10);
  2227. } else if (bandwidth[0].indexOf('b=AS:') === 0) {
  2228. // use formula from JSEP to convert b=AS to TIAS value.
  2229. bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95 -
  2230. (50 * 40 * 8);
  2231. } else {
  2232. bandwidth = undefined;
  2233. }
  2234. encodingParameters.forEach(function(params) {
  2235. params.maxBitrate = bandwidth;
  2236. });
  2237. }
  2238. return encodingParameters;
  2239. };
  2240. // parses http://draft.ortc.org/#rtcrtcpparameters*
  2241. SDPUtils.parseRtcpParameters = function(mediaSection) {
  2242. var rtcpParameters = {};
  2243. // Gets the first SSRC. Note tha with RTX there might be multiple
  2244. // SSRCs.
  2245. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  2246. .map(function(line) {
  2247. return SDPUtils.parseSsrcMedia(line);
  2248. })
  2249. .filter(function(obj) {
  2250. return obj.attribute === 'cname';
  2251. })[0];
  2252. if (remoteSsrc) {
  2253. rtcpParameters.cname = remoteSsrc.value;
  2254. rtcpParameters.ssrc = remoteSsrc.ssrc;
  2255. }
  2256. // Edge uses the compound attribute instead of reducedSize
  2257. // compound is !reducedSize
  2258. var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
  2259. rtcpParameters.reducedSize = rsize.length > 0;
  2260. rtcpParameters.compound = rsize.length === 0;
  2261. // parses the rtcp-mux attrіbute.
  2262. // Note that Edge does not support unmuxed RTCP.
  2263. var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
  2264. rtcpParameters.mux = mux.length > 0;
  2265. return rtcpParameters;
  2266. };
  2267. // parses either a=msid: or a=ssrc:... msid lines and returns
  2268. // the id of the MediaStream and MediaStreamTrack.
  2269. SDPUtils.parseMsid = function(mediaSection) {
  2270. var parts;
  2271. var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
  2272. if (spec.length === 1) {
  2273. parts = spec[0].substr(7).split(' ');
  2274. return {
  2275. stream: parts[0],
  2276. track: parts[1]
  2277. };
  2278. }
  2279. var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  2280. .map(function(line) {
  2281. return SDPUtils.parseSsrcMedia(line);
  2282. })
  2283. .filter(function(msidParts) {
  2284. return msidParts.attribute === 'msid';
  2285. });
  2286. if (planB.length > 0) {
  2287. parts = planB[0].value.split(' ');
  2288. return {
  2289. stream: parts[0],
  2290. track: parts[1]
  2291. };
  2292. }
  2293. };
  2294. // SCTP
  2295. // parses draft-ietf-mmusic-sctp-sdp-26 first and falls back
  2296. // to draft-ietf-mmusic-sctp-sdp-05
  2297. SDPUtils.parseSctpDescription = function(mediaSection) {
  2298. var mline = SDPUtils.parseMLine(mediaSection);
  2299. var maxSizeLine = SDPUtils.matchPrefix(mediaSection, 'a=max-message-size:');
  2300. var maxMessageSize;
  2301. if (maxSizeLine.length > 0) {
  2302. maxMessageSize = parseInt(maxSizeLine[0].substr(19), 10);
  2303. }
  2304. if (isNaN(maxMessageSize)) {
  2305. maxMessageSize = 65536;
  2306. }
  2307. var sctpPort = SDPUtils.matchPrefix(mediaSection, 'a=sctp-port:');
  2308. if (sctpPort.length > 0) {
  2309. return {
  2310. port: parseInt(sctpPort[0].substr(12), 10),
  2311. protocol: mline.fmt,
  2312. maxMessageSize: maxMessageSize
  2313. };
  2314. }
  2315. var sctpMapLines = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:');
  2316. if (sctpMapLines.length > 0) {
  2317. var parts = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:')[0]
  2318. .substr(10)
  2319. .split(' ');
  2320. return {
  2321. port: parseInt(parts[0], 10),
  2322. protocol: parts[1],
  2323. maxMessageSize: maxMessageSize
  2324. };
  2325. }
  2326. };
  2327. // SCTP
  2328. // outputs the draft-ietf-mmusic-sctp-sdp-26 version that all browsers
  2329. // support by now receiving in this format, unless we originally parsed
  2330. // as the draft-ietf-mmusic-sctp-sdp-05 format (indicated by the m-line
  2331. // protocol of DTLS/SCTP -- without UDP/ or TCP/)
  2332. SDPUtils.writeSctpDescription = function(media, sctp) {
  2333. var output = [];
  2334. if (media.protocol !== 'DTLS/SCTP') {
  2335. output = [
  2336. 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.protocol + '\r\n',
  2337. 'c=IN IP4 0.0.0.0\r\n',
  2338. 'a=sctp-port:' + sctp.port + '\r\n'
  2339. ];
  2340. } else {
  2341. output = [
  2342. 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.port + '\r\n',
  2343. 'c=IN IP4 0.0.0.0\r\n',
  2344. 'a=sctpmap:' + sctp.port + ' ' + sctp.protocol + ' 65535\r\n'
  2345. ];
  2346. }
  2347. if (sctp.maxMessageSize !== undefined) {
  2348. output.push('a=max-message-size:' + sctp.maxMessageSize + '\r\n');
  2349. }
  2350. return output.join('');
  2351. };
  2352. // Generate a session ID for SDP.
  2353. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
  2354. // recommends using a cryptographically random +ve 64-bit value
  2355. // but right now this should be acceptable and within the right range
  2356. SDPUtils.generateSessionId = function() {
  2357. return Math.random().toString().substr(2, 21);
  2358. };
  2359. // Write boilder plate for start of SDP
  2360. // sessId argument is optional - if not supplied it will
  2361. // be generated randomly
  2362. // sessVersion is optional and defaults to 2
  2363. // sessUser is optional and defaults to 'thisisadapterortc'
  2364. SDPUtils.writeSessionBoilerplate = function(sessId, sessVer, sessUser) {
  2365. var sessionId;
  2366. var version = sessVer !== undefined ? sessVer : 2;
  2367. if (sessId) {
  2368. sessionId = sessId;
  2369. } else {
  2370. sessionId = SDPUtils.generateSessionId();
  2371. }
  2372. var user = sessUser || 'thisisadapterortc';
  2373. // FIXME: sess-id should be an NTP timestamp.
  2374. return 'v=0\r\n' +
  2375. 'o=' + user + ' ' + sessionId + ' ' + version +
  2376. ' IN IP4 127.0.0.1\r\n' +
  2377. 's=-\r\n' +
  2378. 't=0 0\r\n';
  2379. };
  2380. SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
  2381. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  2382. // Map ICE parameters (ufrag, pwd) to SDP.
  2383. sdp += SDPUtils.writeIceParameters(
  2384. transceiver.iceGatherer.getLocalParameters());
  2385. // Map DTLS parameters to SDP.
  2386. sdp += SDPUtils.writeDtlsParameters(
  2387. transceiver.dtlsTransport.getLocalParameters(),
  2388. type === 'offer' ? 'actpass' : 'active');
  2389. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  2390. if (transceiver.direction) {
  2391. sdp += 'a=' + transceiver.direction + '\r\n';
  2392. } else if (transceiver.rtpSender && transceiver.rtpReceiver) {
  2393. sdp += 'a=sendrecv\r\n';
  2394. } else if (transceiver.rtpSender) {
  2395. sdp += 'a=sendonly\r\n';
  2396. } else if (transceiver.rtpReceiver) {
  2397. sdp += 'a=recvonly\r\n';
  2398. } else {
  2399. sdp += 'a=inactive\r\n';
  2400. }
  2401. if (transceiver.rtpSender) {
  2402. // spec.
  2403. var msid = 'msid:' + stream.id + ' ' +
  2404. transceiver.rtpSender.track.id + '\r\n';
  2405. sdp += 'a=' + msid;
  2406. // for Chrome.
  2407. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2408. ' ' + msid;
  2409. if (transceiver.sendEncodingParameters[0].rtx) {
  2410. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2411. ' ' + msid;
  2412. sdp += 'a=ssrc-group:FID ' +
  2413. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  2414. transceiver.sendEncodingParameters[0].rtx.ssrc +
  2415. '\r\n';
  2416. }
  2417. }
  2418. // FIXME: this should be written by writeRtpDescription.
  2419. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2420. ' cname:' + SDPUtils.localCName + '\r\n';
  2421. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  2422. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2423. ' cname:' + SDPUtils.localCName + '\r\n';
  2424. }
  2425. return sdp;
  2426. };
  2427. // Gets the direction from the mediaSection or the sessionpart.
  2428. SDPUtils.getDirection = function(mediaSection, sessionpart) {
  2429. // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
  2430. var lines = SDPUtils.splitLines(mediaSection);
  2431. for (var i = 0; i < lines.length; i++) {
  2432. switch (lines[i]) {
  2433. case 'a=sendrecv':
  2434. case 'a=sendonly':
  2435. case 'a=recvonly':
  2436. case 'a=inactive':
  2437. return lines[i].substr(2);
  2438. // FIXME: What should happen here?
  2439. }
  2440. }
  2441. if (sessionpart) {
  2442. return SDPUtils.getDirection(sessionpart);
  2443. }
  2444. return 'sendrecv';
  2445. };
  2446. SDPUtils.getKind = function(mediaSection) {
  2447. var lines = SDPUtils.splitLines(mediaSection);
  2448. var mline = lines[0].split(' ');
  2449. return mline[0].substr(2);
  2450. };
  2451. SDPUtils.isRejected = function(mediaSection) {
  2452. return mediaSection.split(' ', 2)[1] === '0';
  2453. };
  2454. SDPUtils.parseMLine = function(mediaSection) {
  2455. var lines = SDPUtils.splitLines(mediaSection);
  2456. var parts = lines[0].substr(2).split(' ');
  2457. return {
  2458. kind: parts[0],
  2459. port: parseInt(parts[1], 10),
  2460. protocol: parts[2],
  2461. fmt: parts.slice(3).join(' ')
  2462. };
  2463. };
  2464. SDPUtils.parseOLine = function(mediaSection) {
  2465. var line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];
  2466. var parts = line.substr(2).split(' ');
  2467. return {
  2468. username: parts[0],
  2469. sessionId: parts[1],
  2470. sessionVersion: parseInt(parts[2], 10),
  2471. netType: parts[3],
  2472. addressType: parts[4],
  2473. address: parts[5]
  2474. };
  2475. };
  2476. // a very naive interpretation of a valid SDP.
  2477. SDPUtils.isValidSDP = function(blob) {
  2478. if (typeof blob !== 'string' || blob.length === 0) {
  2479. return false;
  2480. }
  2481. var lines = SDPUtils.splitLines(blob);
  2482. for (var i = 0; i < lines.length; i++) {
  2483. if (lines[i].length < 2 || lines[i].charAt(1) !== '=') {
  2484. return false;
  2485. }
  2486. // TODO: check the modifier a bit more.
  2487. }
  2488. return true;
  2489. };
  2490. // Expose public methods.
  2491. {
  2492. module.exports = SDPUtils;
  2493. }
  2494. });
  2495. /*
  2496. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  2497. *
  2498. * Use of this source code is governed by a BSD-style license
  2499. * that can be found in the LICENSE file in the root of the source
  2500. * tree.
  2501. */
  2502. function fixStatsType(stat) {
  2503. return {
  2504. inboundrtp: 'inbound-rtp',
  2505. outboundrtp: 'outbound-rtp',
  2506. candidatepair: 'candidate-pair',
  2507. localcandidate: 'local-candidate',
  2508. remotecandidate: 'remote-candidate'
  2509. } [stat.type] || stat.type;
  2510. }
  2511. function writeMediaSection(transceiver, caps, type, stream, dtlsRole) {
  2512. var sdp$1 = sdp.writeRtpDescription(transceiver.kind, caps);
  2513. // Map ICE parameters (ufrag, pwd) to SDP.
  2514. sdp$1 += sdp.writeIceParameters(
  2515. transceiver.iceGatherer.getLocalParameters());
  2516. // Map DTLS parameters to SDP.
  2517. sdp$1 += sdp.writeDtlsParameters(
  2518. transceiver.dtlsTransport.getLocalParameters(),
  2519. type === 'offer' ? 'actpass' : dtlsRole || 'active');
  2520. sdp$1 += 'a=mid:' + transceiver.mid + '\r\n';
  2521. if (transceiver.rtpSender && transceiver.rtpReceiver) {
  2522. sdp$1 += 'a=sendrecv\r\n';
  2523. } else if (transceiver.rtpSender) {
  2524. sdp$1 += 'a=sendonly\r\n';
  2525. } else if (transceiver.rtpReceiver) {
  2526. sdp$1 += 'a=recvonly\r\n';
  2527. } else {
  2528. sdp$1 += 'a=inactive\r\n';
  2529. }
  2530. if (transceiver.rtpSender) {
  2531. var trackId = transceiver.rtpSender._initialTrackId ||
  2532. transceiver.rtpSender.track.id;
  2533. transceiver.rtpSender._initialTrackId = trackId;
  2534. // spec.
  2535. var msid = 'msid:' + (stream ? stream.id : '-') + ' ' +
  2536. trackId + '\r\n';
  2537. sdp$1 += 'a=' + msid;
  2538. // for Chrome. Legacy should no longer be required.
  2539. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2540. ' ' + msid;
  2541. // RTX
  2542. if (transceiver.sendEncodingParameters[0].rtx) {
  2543. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2544. ' ' + msid;
  2545. sdp$1 += 'a=ssrc-group:FID ' +
  2546. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  2547. transceiver.sendEncodingParameters[0].rtx.ssrc +
  2548. '\r\n';
  2549. }
  2550. }
  2551. // FIXME: this should be written by writeRtpDescription.
  2552. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2553. ' cname:' + sdp.localCName + '\r\n';
  2554. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  2555. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2556. ' cname:' + sdp.localCName + '\r\n';
  2557. }
  2558. return sdp$1;
  2559. }
  2560. // Edge does not like
  2561. // 1) stun: filtered after 14393 unless ?transport=udp is present
  2562. // 2) turn: that does not have all of turn:host:port?transport=udp
  2563. // 3) turn: with ipv6 addresses
  2564. // 4) turn: occurring muliple times
  2565. function filterIceServers(iceServers, edgeVersion) {
  2566. var hasTurn = false;
  2567. iceServers = JSON.parse(JSON.stringify(iceServers));
  2568. return iceServers.filter(function(server) {
  2569. if (server && (server.urls || server.url)) {
  2570. var urls = server.urls || server.url;
  2571. if (server.url && !server.urls) {
  2572. console.warn('RTCIceServer.url is deprecated! Use urls instead.');
  2573. }
  2574. var isString = typeof urls === 'string';
  2575. if (isString) {
  2576. urls = [urls];
  2577. }
  2578. urls = urls.filter(function(url) {
  2579. var validTurn = url.indexOf('turn:') === 0 &&
  2580. url.indexOf('transport=udp') !== -1 &&
  2581. url.indexOf('turn:[') === -1 &&
  2582. !hasTurn;
  2583. if (validTurn) {
  2584. hasTurn = true;
  2585. return true;
  2586. }
  2587. return url.indexOf('stun:') === 0 && edgeVersion >= 14393 &&
  2588. url.indexOf('?transport=udp') === -1;
  2589. });
  2590. delete server.url;
  2591. server.urls = isString ? urls[0] : urls;
  2592. return !!urls.length;
  2593. }
  2594. });
  2595. }
  2596. // Determines the intersection of local and remote capabilities.
  2597. function getCommonCapabilities(localCapabilities, remoteCapabilities) {
  2598. var commonCapabilities = {
  2599. codecs: [],
  2600. headerExtensions: [],
  2601. fecMechanisms: []
  2602. };
  2603. var findCodecByPayloadType = function(pt, codecs) {
  2604. pt = parseInt(pt, 10);
  2605. for (var i = 0; i < codecs.length; i++) {
  2606. if (codecs[i].payloadType === pt ||
  2607. codecs[i].preferredPayloadType === pt) {
  2608. return codecs[i];
  2609. }
  2610. }
  2611. };
  2612. var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) {
  2613. var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs);
  2614. var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs);
  2615. return lCodec && rCodec &&
  2616. lCodec.name.toLowerCase() === rCodec.name.toLowerCase();
  2617. };
  2618. localCapabilities.codecs.forEach(function(lCodec) {
  2619. for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
  2620. var rCodec = remoteCapabilities.codecs[i];
  2621. if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
  2622. lCodec.clockRate === rCodec.clockRate) {
  2623. if (lCodec.name.toLowerCase() === 'rtx' &&
  2624. lCodec.parameters && rCodec.parameters.apt) {
  2625. // for RTX we need to find the local rtx that has a apt
  2626. // which points to the same local codec as the remote one.
  2627. if (!rtxCapabilityMatches(lCodec, rCodec,
  2628. localCapabilities.codecs, remoteCapabilities.codecs)) {
  2629. continue;
  2630. }
  2631. }
  2632. rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy
  2633. // number of channels is the highest common number of channels
  2634. rCodec.numChannels = Math.min(lCodec.numChannels,
  2635. rCodec.numChannels);
  2636. // push rCodec so we reply with offerer payload type
  2637. commonCapabilities.codecs.push(rCodec);
  2638. // determine common feedback mechanisms
  2639. rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
  2640. for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
  2641. if (lCodec.rtcpFeedback[j].type === fb.type &&
  2642. lCodec.rtcpFeedback[j].parameter === fb.parameter) {
  2643. return true;
  2644. }
  2645. }
  2646. return false;
  2647. });
  2648. // FIXME: also need to determine .parameters
  2649. // see https://github.com/openpeer/ortc/issues/569
  2650. break;
  2651. }
  2652. }
  2653. });
  2654. localCapabilities.headerExtensions.forEach(function(lHeaderExtension) {
  2655. for (var i = 0; i < remoteCapabilities.headerExtensions.length; i++) {
  2656. var rHeaderExtension = remoteCapabilities.headerExtensions[i];
  2657. if (lHeaderExtension.uri === rHeaderExtension.uri) {
  2658. commonCapabilities.headerExtensions.push(rHeaderExtension);
  2659. break;
  2660. }
  2661. }
  2662. });
  2663. // FIXME: fecMechanisms
  2664. return commonCapabilities;
  2665. }
  2666. // is action=setLocalDescription with type allowed in signalingState
  2667. function isActionAllowedInSignalingState(action, type, signalingState) {
  2668. return {
  2669. offer: {
  2670. setLocalDescription: ['stable', 'have-local-offer'],
  2671. setRemoteDescription: ['stable', 'have-remote-offer']
  2672. },
  2673. answer: {
  2674. setLocalDescription: ['have-remote-offer', 'have-local-pranswer'],
  2675. setRemoteDescription: ['have-local-offer', 'have-remote-pranswer']
  2676. }
  2677. } [type][action].indexOf(signalingState) !== -1;
  2678. }
  2679. function maybeAddCandidate(iceTransport, candidate) {
  2680. // Edge's internal representation adds some fields therefore
  2681. // not all fieldѕ are taken into account.
  2682. var alreadyAdded = iceTransport.getRemoteCandidates()
  2683. .find(function(remoteCandidate) {
  2684. return candidate.foundation === remoteCandidate.foundation &&
  2685. candidate.ip === remoteCandidate.ip &&
  2686. candidate.port === remoteCandidate.port &&
  2687. candidate.priority === remoteCandidate.priority &&
  2688. candidate.protocol === remoteCandidate.protocol &&
  2689. candidate.type === remoteCandidate.type;
  2690. });
  2691. if (!alreadyAdded) {
  2692. iceTransport.addRemoteCandidate(candidate);
  2693. }
  2694. return !alreadyAdded;
  2695. }
  2696. function makeError(name, description) {
  2697. var e = new Error(description);
  2698. e.name = name;
  2699. // legacy error codes from https://heycam.github.io/webidl/#idl-DOMException-error-names
  2700. e.code = {
  2701. NotSupportedError: 9,
  2702. InvalidStateError: 11,
  2703. InvalidAccessError: 15,
  2704. TypeError: undefined,
  2705. OperationError: undefined
  2706. } [name];
  2707. return e;
  2708. }
  2709. var rtcpeerconnection = function(window, edgeVersion) {
  2710. // https://w3c.github.io/mediacapture-main/#mediastream
  2711. // Helper function to add the track to the stream and
  2712. // dispatch the event ourselves.
  2713. function addTrackToStreamAndFireEvent(track, stream) {
  2714. stream.addTrack(track);
  2715. stream.dispatchEvent(new window.MediaStreamTrackEvent('addtrack', {
  2716. track: track
  2717. }));
  2718. }
  2719. function removeTrackFromStreamAndFireEvent(track, stream) {
  2720. stream.removeTrack(track);
  2721. stream.dispatchEvent(new window.MediaStreamTrackEvent('removetrack', {
  2722. track: track
  2723. }));
  2724. }
  2725. function fireAddTrack(pc, track, receiver, streams) {
  2726. var trackEvent = new Event('track');
  2727. trackEvent.track = track;
  2728. trackEvent.receiver = receiver;
  2729. trackEvent.transceiver = {
  2730. receiver: receiver
  2731. };
  2732. trackEvent.streams = streams;
  2733. window.setTimeout(function() {
  2734. pc._dispatchEvent('track', trackEvent);
  2735. });
  2736. }
  2737. var RTCPeerConnection = function(config) {
  2738. var pc = this;
  2739. var _eventTarget = document.createDocumentFragment();
  2740. ['addEventListener', 'removeEventListener', 'dispatchEvent']
  2741. .forEach(function(method) {
  2742. pc[method] = _eventTarget[method].bind(_eventTarget);
  2743. });
  2744. this.canTrickleIceCandidates = null;
  2745. this.needNegotiation = false;
  2746. this.localStreams = [];
  2747. this.remoteStreams = [];
  2748. this._localDescription = null;
  2749. this._remoteDescription = null;
  2750. this.signalingState = 'stable';
  2751. this.iceConnectionState = 'new';
  2752. this.connectionState = 'new';
  2753. this.iceGatheringState = 'new';
  2754. config = JSON.parse(JSON.stringify(config || {}));
  2755. this.usingBundle = config.bundlePolicy === 'max-bundle';
  2756. if (config.rtcpMuxPolicy === 'negotiate') {
  2757. throw (makeError('NotSupportedError',
  2758. 'rtcpMuxPolicy \'negotiate\' is not supported'));
  2759. } else if (!config.rtcpMuxPolicy) {
  2760. config.rtcpMuxPolicy = 'require';
  2761. }
  2762. switch (config.iceTransportPolicy) {
  2763. case 'all':
  2764. case 'relay':
  2765. break;
  2766. default:
  2767. config.iceTransportPolicy = 'all';
  2768. break;
  2769. }
  2770. switch (config.bundlePolicy) {
  2771. case 'balanced':
  2772. case 'max-compat':
  2773. case 'max-bundle':
  2774. break;
  2775. default:
  2776. config.bundlePolicy = 'balanced';
  2777. break;
  2778. }
  2779. config.iceServers = filterIceServers(config.iceServers || [], edgeVersion);
  2780. this._iceGatherers = [];
  2781. if (config.iceCandidatePoolSize) {
  2782. for (var i = config.iceCandidatePoolSize; i > 0; i--) {
  2783. this._iceGatherers.push(new window.RTCIceGatherer({
  2784. iceServers: config.iceServers,
  2785. gatherPolicy: config.iceTransportPolicy
  2786. }));
  2787. }
  2788. } else {
  2789. config.iceCandidatePoolSize = 0;
  2790. }
  2791. this._config = config;
  2792. // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
  2793. // everything that is needed to describe a SDP m-line.
  2794. this.transceivers = [];
  2795. this._sdpSessionId = sdp.generateSessionId();
  2796. this._sdpSessionVersion = 0;
  2797. this._dtlsRole = undefined; // role for a=setup to use in answers.
  2798. this._isClosed = false;
  2799. };
  2800. Object.defineProperty(RTCPeerConnection.prototype, 'localDescription', {
  2801. configurable: true,
  2802. get: function() {
  2803. return this._localDescription;
  2804. }
  2805. });
  2806. Object.defineProperty(RTCPeerConnection.prototype, 'remoteDescription', {
  2807. configurable: true,
  2808. get: function() {
  2809. return this._remoteDescription;
  2810. }
  2811. });
  2812. // set up event handlers on prototype
  2813. RTCPeerConnection.prototype.onicecandidate = null;
  2814. RTCPeerConnection.prototype.onaddstream = null;
  2815. RTCPeerConnection.prototype.ontrack = null;
  2816. RTCPeerConnection.prototype.onremovestream = null;
  2817. RTCPeerConnection.prototype.onsignalingstatechange = null;
  2818. RTCPeerConnection.prototype.oniceconnectionstatechange = null;
  2819. RTCPeerConnection.prototype.onconnectionstatechange = null;
  2820. RTCPeerConnection.prototype.onicegatheringstatechange = null;
  2821. RTCPeerConnection.prototype.onnegotiationneeded = null;
  2822. RTCPeerConnection.prototype.ondatachannel = null;
  2823. RTCPeerConnection.prototype._dispatchEvent = function(name, event) {
  2824. if (this._isClosed) {
  2825. return;
  2826. }
  2827. this.dispatchEvent(event);
  2828. if (typeof this['on' + name] === 'function') {
  2829. this['on' + name](event);
  2830. }
  2831. };
  2832. RTCPeerConnection.prototype._emitGatheringStateChange = function() {
  2833. var event = new Event('icegatheringstatechange');
  2834. this._dispatchEvent('icegatheringstatechange', event);
  2835. };
  2836. RTCPeerConnection.prototype.getConfiguration = function() {
  2837. return this._config;
  2838. };
  2839. RTCPeerConnection.prototype.getLocalStreams = function() {
  2840. return this.localStreams;
  2841. };
  2842. RTCPeerConnection.prototype.getRemoteStreams = function() {
  2843. return this.remoteStreams;
  2844. };
  2845. // internal helper to create a transceiver object.
  2846. // (which is not yet the same as the WebRTC 1.0 transceiver)
  2847. RTCPeerConnection.prototype._createTransceiver = function(kind, doNotAdd) {
  2848. var hasBundleTransport = this.transceivers.length > 0;
  2849. var transceiver = {
  2850. track: null,
  2851. iceGatherer: null,
  2852. iceTransport: null,
  2853. dtlsTransport: null,
  2854. localCapabilities: null,
  2855. remoteCapabilities: null,
  2856. rtpSender: null,
  2857. rtpReceiver: null,
  2858. kind: kind,
  2859. mid: null,
  2860. sendEncodingParameters: null,
  2861. recvEncodingParameters: null,
  2862. stream: null,
  2863. associatedRemoteMediaStreams: [],
  2864. wantReceive: true
  2865. };
  2866. if (this.usingBundle && hasBundleTransport) {
  2867. transceiver.iceTransport = this.transceivers[0].iceTransport;
  2868. transceiver.dtlsTransport = this.transceivers[0].dtlsTransport;
  2869. } else {
  2870. var transports = this._createIceAndDtlsTransports();
  2871. transceiver.iceTransport = transports.iceTransport;
  2872. transceiver.dtlsTransport = transports.dtlsTransport;
  2873. }
  2874. if (!doNotAdd) {
  2875. this.transceivers.push(transceiver);
  2876. }
  2877. return transceiver;
  2878. };
  2879. RTCPeerConnection.prototype.addTrack = function(track, stream) {
  2880. if (this._isClosed) {
  2881. throw makeError('InvalidStateError',
  2882. 'Attempted to call addTrack on a closed peerconnection.');
  2883. }
  2884. var alreadyExists = this.transceivers.find(function(s) {
  2885. return s.track === track;
  2886. });
  2887. if (alreadyExists) {
  2888. throw makeError('InvalidAccessError', 'Track already exists.');
  2889. }
  2890. var transceiver;
  2891. for (var i = 0; i < this.transceivers.length; i++) {
  2892. if (!this.transceivers[i].track &&
  2893. this.transceivers[i].kind === track.kind) {
  2894. transceiver = this.transceivers[i];
  2895. }
  2896. }
  2897. if (!transceiver) {
  2898. transceiver = this._createTransceiver(track.kind);
  2899. }
  2900. this._maybeFireNegotiationNeeded();
  2901. if (this.localStreams.indexOf(stream) === -1) {
  2902. this.localStreams.push(stream);
  2903. }
  2904. transceiver.track = track;
  2905. transceiver.stream = stream;
  2906. transceiver.rtpSender = new window.RTCRtpSender(track,
  2907. transceiver.dtlsTransport);
  2908. return transceiver.rtpSender;
  2909. };
  2910. RTCPeerConnection.prototype.addStream = function(stream) {
  2911. var pc = this;
  2912. if (edgeVersion >= 15025) {
  2913. stream.getTracks().forEach(function(track) {
  2914. pc.addTrack(track, stream);
  2915. });
  2916. } else {
  2917. // Clone is necessary for local demos mostly, attaching directly
  2918. // to two different senders does not work (build 10547).
  2919. // Fixed in 15025 (or earlier)
  2920. var clonedStream = stream.clone();
  2921. stream.getTracks().forEach(function(track, idx) {
  2922. var clonedTrack = clonedStream.getTracks()[idx];
  2923. track.addEventListener('enabled', function(event) {
  2924. clonedTrack.enabled = event.enabled;
  2925. });
  2926. });
  2927. clonedStream.getTracks().forEach(function(track) {
  2928. pc.addTrack(track, clonedStream);
  2929. });
  2930. }
  2931. };
  2932. RTCPeerConnection.prototype.removeTrack = function(sender) {
  2933. if (this._isClosed) {
  2934. throw makeError('InvalidStateError',
  2935. 'Attempted to call removeTrack on a closed peerconnection.');
  2936. }
  2937. if (!(sender instanceof window.RTCRtpSender)) {
  2938. throw new TypeError('Argument 1 of RTCPeerConnection.removeTrack ' +
  2939. 'does not implement interface RTCRtpSender.');
  2940. }
  2941. var transceiver = this.transceivers.find(function(t) {
  2942. return t.rtpSender === sender;
  2943. });
  2944. if (!transceiver) {
  2945. throw makeError('InvalidAccessError',
  2946. 'Sender was not created by this connection.');
  2947. }
  2948. var stream = transceiver.stream;
  2949. transceiver.rtpSender.stop();
  2950. transceiver.rtpSender = null;
  2951. transceiver.track = null;
  2952. transceiver.stream = null;
  2953. // remove the stream from the set of local streams
  2954. var localStreams = this.transceivers.map(function(t) {
  2955. return t.stream;
  2956. });
  2957. if (localStreams.indexOf(stream) === -1 &&
  2958. this.localStreams.indexOf(stream) > -1) {
  2959. this.localStreams.splice(this.localStreams.indexOf(stream), 1);
  2960. }
  2961. this._maybeFireNegotiationNeeded();
  2962. };
  2963. RTCPeerConnection.prototype.removeStream = function(stream) {
  2964. var pc = this;
  2965. stream.getTracks().forEach(function(track) {
  2966. var sender = pc.getSenders().find(function(s) {
  2967. return s.track === track;
  2968. });
  2969. if (sender) {
  2970. pc.removeTrack(sender);
  2971. }
  2972. });
  2973. };
  2974. RTCPeerConnection.prototype.getSenders = function() {
  2975. return this.transceivers.filter(function(transceiver) {
  2976. return !!transceiver.rtpSender;
  2977. })
  2978. .map(function(transceiver) {
  2979. return transceiver.rtpSender;
  2980. });
  2981. };
  2982. RTCPeerConnection.prototype.getReceivers = function() {
  2983. return this.transceivers.filter(function(transceiver) {
  2984. return !!transceiver.rtpReceiver;
  2985. })
  2986. .map(function(transceiver) {
  2987. return transceiver.rtpReceiver;
  2988. });
  2989. };
  2990. RTCPeerConnection.prototype._createIceGatherer = function(sdpMLineIndex,
  2991. usingBundle) {
  2992. var pc = this;
  2993. if (usingBundle && sdpMLineIndex > 0) {
  2994. return this.transceivers[0].iceGatherer;
  2995. } else if (this._iceGatherers.length) {
  2996. return this._iceGatherers.shift();
  2997. }
  2998. var iceGatherer = new window.RTCIceGatherer({
  2999. iceServers: this._config.iceServers,
  3000. gatherPolicy: this._config.iceTransportPolicy
  3001. });
  3002. Object.defineProperty(iceGatherer, 'state', {
  3003. value: 'new',
  3004. writable: true
  3005. });
  3006. this.transceivers[sdpMLineIndex].bufferedCandidateEvents = [];
  3007. this.transceivers[sdpMLineIndex].bufferCandidates = function(event) {
  3008. var end = !event.candidate || Object.keys(event.candidate).length === 0;
  3009. // polyfill since RTCIceGatherer.state is not implemented in
  3010. // Edge 10547 yet.
  3011. iceGatherer.state = end ? 'completed' : 'gathering';
  3012. if (pc.transceivers[sdpMLineIndex].bufferedCandidateEvents !== null) {
  3013. pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event);
  3014. }
  3015. };
  3016. iceGatherer.addEventListener('localcandidate',
  3017. this.transceivers[sdpMLineIndex].bufferCandidates);
  3018. return iceGatherer;
  3019. };
  3020. // start gathering from an RTCIceGatherer.
  3021. RTCPeerConnection.prototype._gather = function(mid, sdpMLineIndex) {
  3022. var pc = this;
  3023. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  3024. if (iceGatherer.onlocalcandidate) {
  3025. return;
  3026. }
  3027. var bufferedCandidateEvents =
  3028. this.transceivers[sdpMLineIndex].bufferedCandidateEvents;
  3029. this.transceivers[sdpMLineIndex].bufferedCandidateEvents = null;
  3030. iceGatherer.removeEventListener('localcandidate',
  3031. this.transceivers[sdpMLineIndex].bufferCandidates);
  3032. iceGatherer.onlocalcandidate = function(evt) {
  3033. if (pc.usingBundle && sdpMLineIndex > 0) {
  3034. // if we know that we use bundle we can drop candidates with
  3035. // ѕdpMLineIndex > 0. If we don't do this then our state gets
  3036. // confused since we dispose the extra ice gatherer.
  3037. return;
  3038. }
  3039. var event = new Event('icecandidate');
  3040. event.candidate = {
  3041. sdpMid: mid,
  3042. sdpMLineIndex: sdpMLineIndex
  3043. };
  3044. var cand = evt.candidate;
  3045. // Edge emits an empty object for RTCIceCandidateComplete‥
  3046. var end = !cand || Object.keys(cand).length === 0;
  3047. if (end) {
  3048. // polyfill since RTCIceGatherer.state is not implemented in
  3049. // Edge 10547 yet.
  3050. if (iceGatherer.state === 'new' || iceGatherer.state === 'gathering') {
  3051. iceGatherer.state = 'completed';
  3052. }
  3053. } else {
  3054. if (iceGatherer.state === 'new') {
  3055. iceGatherer.state = 'gathering';
  3056. }
  3057. // RTCIceCandidate doesn't have a component, needs to be added
  3058. cand.component = 1;
  3059. // also the usernameFragment. TODO: update SDP to take both variants.
  3060. cand.ufrag = iceGatherer.getLocalParameters().usernameFragment;
  3061. var serializedCandidate = sdp.writeCandidate(cand);
  3062. event.candidate = Object.assign(event.candidate,
  3063. sdp.parseCandidate(serializedCandidate));
  3064. event.candidate.candidate = serializedCandidate;
  3065. event.candidate.toJSON = function() {
  3066. return {
  3067. candidate: event.candidate.candidate,
  3068. sdpMid: event.candidate.sdpMid,
  3069. sdpMLineIndex: event.candidate.sdpMLineIndex,
  3070. usernameFragment: event.candidate.usernameFragment
  3071. };
  3072. };
  3073. }
  3074. // update local description.
  3075. var sections = sdp.getMediaSections(pc._localDescription.sdp);
  3076. if (!end) {
  3077. sections[event.candidate.sdpMLineIndex] +=
  3078. 'a=' + event.candidate.candidate + '\r\n';
  3079. } else {
  3080. sections[event.candidate.sdpMLineIndex] +=
  3081. 'a=end-of-candidates\r\n';
  3082. }
  3083. pc._localDescription.sdp =
  3084. sdp.getDescription(pc._localDescription.sdp) +
  3085. sections.join('');
  3086. var complete = pc.transceivers.every(function(transceiver) {
  3087. return transceiver.iceGatherer &&
  3088. transceiver.iceGatherer.state === 'completed';
  3089. });
  3090. if (pc.iceGatheringState !== 'gathering') {
  3091. pc.iceGatheringState = 'gathering';
  3092. pc._emitGatheringStateChange();
  3093. }
  3094. // Emit candidate. Also emit null candidate when all gatherers are
  3095. // complete.
  3096. if (!end) {
  3097. pc._dispatchEvent('icecandidate', event);
  3098. }
  3099. if (complete) {
  3100. pc._dispatchEvent('icecandidate', new Event('icecandidate'));
  3101. pc.iceGatheringState = 'complete';
  3102. pc._emitGatheringStateChange();
  3103. }
  3104. };
  3105. // emit already gathered candidates.
  3106. window.setTimeout(function() {
  3107. bufferedCandidateEvents.forEach(function(e) {
  3108. iceGatherer.onlocalcandidate(e);
  3109. });
  3110. }, 0);
  3111. };
  3112. // Create ICE transport and DTLS transport.
  3113. RTCPeerConnection.prototype._createIceAndDtlsTransports = function() {
  3114. var pc = this;
  3115. var iceTransport = new window.RTCIceTransport(null);
  3116. iceTransport.onicestatechange = function() {
  3117. pc._updateIceConnectionState();
  3118. pc._updateConnectionState();
  3119. };
  3120. var dtlsTransport = new window.RTCDtlsTransport(iceTransport);
  3121. dtlsTransport.ondtlsstatechange = function() {
  3122. pc._updateConnectionState();
  3123. };
  3124. dtlsTransport.onerror = function() {
  3125. // onerror does not set state to failed by itself.
  3126. Object.defineProperty(dtlsTransport, 'state', {
  3127. value: 'failed',
  3128. writable: true
  3129. });
  3130. pc._updateConnectionState();
  3131. };
  3132. return {
  3133. iceTransport: iceTransport,
  3134. dtlsTransport: dtlsTransport
  3135. };
  3136. };
  3137. // Destroy ICE gatherer, ICE transport and DTLS transport.
  3138. // Without triggering the callbacks.
  3139. RTCPeerConnection.prototype._disposeIceAndDtlsTransports = function(
  3140. sdpMLineIndex) {
  3141. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  3142. if (iceGatherer) {
  3143. delete iceGatherer.onlocalcandidate;
  3144. delete this.transceivers[sdpMLineIndex].iceGatherer;
  3145. }
  3146. var iceTransport = this.transceivers[sdpMLineIndex].iceTransport;
  3147. if (iceTransport) {
  3148. delete iceTransport.onicestatechange;
  3149. delete this.transceivers[sdpMLineIndex].iceTransport;
  3150. }
  3151. var dtlsTransport = this.transceivers[sdpMLineIndex].dtlsTransport;
  3152. if (dtlsTransport) {
  3153. delete dtlsTransport.ondtlsstatechange;
  3154. delete dtlsTransport.onerror;
  3155. delete this.transceivers[sdpMLineIndex].dtlsTransport;
  3156. }
  3157. };
  3158. // Start the RTP Sender and Receiver for a transceiver.
  3159. RTCPeerConnection.prototype._transceive = function(transceiver,
  3160. send, recv) {
  3161. var params = getCommonCapabilities(transceiver.localCapabilities,
  3162. transceiver.remoteCapabilities);
  3163. if (send && transceiver.rtpSender) {
  3164. params.encodings = transceiver.sendEncodingParameters;
  3165. params.rtcp = {
  3166. cname: sdp.localCName,
  3167. compound: transceiver.rtcpParameters.compound
  3168. };
  3169. if (transceiver.recvEncodingParameters.length) {
  3170. params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
  3171. }
  3172. transceiver.rtpSender.send(params);
  3173. }
  3174. if (recv && transceiver.rtpReceiver && params.codecs.length > 0) {
  3175. // remove RTX field in Edge 14942
  3176. if (transceiver.kind === 'video' &&
  3177. transceiver.recvEncodingParameters &&
  3178. edgeVersion < 15019) {
  3179. transceiver.recvEncodingParameters.forEach(function(p) {
  3180. delete p.rtx;
  3181. });
  3182. }
  3183. if (transceiver.recvEncodingParameters.length) {
  3184. params.encodings = transceiver.recvEncodingParameters;
  3185. } else {
  3186. params.encodings = [{}];
  3187. }
  3188. params.rtcp = {
  3189. compound: transceiver.rtcpParameters.compound
  3190. };
  3191. if (transceiver.rtcpParameters.cname) {
  3192. params.rtcp.cname = transceiver.rtcpParameters.cname;
  3193. }
  3194. if (transceiver.sendEncodingParameters.length) {
  3195. params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
  3196. }
  3197. transceiver.rtpReceiver.receive(params);
  3198. }
  3199. };
  3200. RTCPeerConnection.prototype.setLocalDescription = function(description) {
  3201. var pc = this;
  3202. // Note: pranswer is not supported.
  3203. if (['offer', 'answer'].indexOf(description.type) === -1) {
  3204. return Promise.reject(makeError('TypeError',
  3205. 'Unsupported type "' + description.type + '"'));
  3206. }
  3207. if (!isActionAllowedInSignalingState('setLocalDescription',
  3208. description.type, pc.signalingState) || pc._isClosed) {
  3209. return Promise.reject(makeError('InvalidStateError',
  3210. 'Can not set local ' + description.type +
  3211. ' in state ' + pc.signalingState));
  3212. }
  3213. var sections;
  3214. var sessionpart;
  3215. if (description.type === 'offer') {
  3216. // VERY limited support for SDP munging. Limited to:
  3217. // * changing the order of codecs
  3218. sections = sdp.splitSections(description.sdp);
  3219. sessionpart = sections.shift();
  3220. sections.forEach(function(mediaSection, sdpMLineIndex) {
  3221. var caps = sdp.parseRtpParameters(mediaSection);
  3222. pc.transceivers[sdpMLineIndex].localCapabilities = caps;
  3223. });
  3224. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3225. pc._gather(transceiver.mid, sdpMLineIndex);
  3226. });
  3227. } else if (description.type === 'answer') {
  3228. sections = sdp.splitSections(pc._remoteDescription.sdp);
  3229. sessionpart = sections.shift();
  3230. var isIceLite = sdp.matchPrefix(sessionpart,
  3231. 'a=ice-lite').length > 0;
  3232. sections.forEach(function(mediaSection, sdpMLineIndex) {
  3233. var transceiver = pc.transceivers[sdpMLineIndex];
  3234. var iceGatherer = transceiver.iceGatherer;
  3235. var iceTransport = transceiver.iceTransport;
  3236. var dtlsTransport = transceiver.dtlsTransport;
  3237. var localCapabilities = transceiver.localCapabilities;
  3238. var remoteCapabilities = transceiver.remoteCapabilities;
  3239. // treat bundle-only as not-rejected.
  3240. var rejected = sdp.isRejected(mediaSection) &&
  3241. sdp.matchPrefix(mediaSection, 'a=bundle-only').length === 0;
  3242. if (!rejected && !transceiver.rejected) {
  3243. var remoteIceParameters = sdp.getIceParameters(
  3244. mediaSection, sessionpart);
  3245. var remoteDtlsParameters = sdp.getDtlsParameters(
  3246. mediaSection, sessionpart);
  3247. if (isIceLite) {
  3248. remoteDtlsParameters.role = 'server';
  3249. }
  3250. if (!pc.usingBundle || sdpMLineIndex === 0) {
  3251. pc._gather(transceiver.mid, sdpMLineIndex);
  3252. if (iceTransport.state === 'new') {
  3253. iceTransport.start(iceGatherer, remoteIceParameters,
  3254. isIceLite ? 'controlling' : 'controlled');
  3255. }
  3256. if (dtlsTransport.state === 'new') {
  3257. dtlsTransport.start(remoteDtlsParameters);
  3258. }
  3259. }
  3260. // Calculate intersection of capabilities.
  3261. var params = getCommonCapabilities(localCapabilities,
  3262. remoteCapabilities);
  3263. // Start the RTCRtpSender. The RTCRtpReceiver for this
  3264. // transceiver has already been started in setRemoteDescription.
  3265. pc._transceive(transceiver,
  3266. params.codecs.length > 0,
  3267. false);
  3268. }
  3269. });
  3270. }
  3271. pc._localDescription = {
  3272. type: description.type,
  3273. sdp: description.sdp
  3274. };
  3275. if (description.type === 'offer') {
  3276. pc._updateSignalingState('have-local-offer');
  3277. } else {
  3278. pc._updateSignalingState('stable');
  3279. }
  3280. return Promise.resolve();
  3281. };
  3282. RTCPeerConnection.prototype.setRemoteDescription = function(description) {
  3283. var pc = this;
  3284. // Note: pranswer is not supported.
  3285. if (['offer', 'answer'].indexOf(description.type) === -1) {
  3286. return Promise.reject(makeError('TypeError',
  3287. 'Unsupported type "' + description.type + '"'));
  3288. }
  3289. if (!isActionAllowedInSignalingState('setRemoteDescription',
  3290. description.type, pc.signalingState) || pc._isClosed) {
  3291. return Promise.reject(makeError('InvalidStateError',
  3292. 'Can not set remote ' + description.type +
  3293. ' in state ' + pc.signalingState));
  3294. }
  3295. var streams = {};
  3296. pc.remoteStreams.forEach(function(stream) {
  3297. streams[stream.id] = stream;
  3298. });
  3299. var receiverList = [];
  3300. var sections = sdp.splitSections(description.sdp);
  3301. var sessionpart = sections.shift();
  3302. var isIceLite = sdp.matchPrefix(sessionpart,
  3303. 'a=ice-lite').length > 0;
  3304. var usingBundle = sdp.matchPrefix(sessionpart,
  3305. 'a=group:BUNDLE ').length > 0;
  3306. pc.usingBundle = usingBundle;
  3307. var iceOptions = sdp.matchPrefix(sessionpart,
  3308. 'a=ice-options:')[0];
  3309. if (iceOptions) {
  3310. pc.canTrickleIceCandidates = iceOptions.substr(14).split(' ')
  3311. .indexOf('trickle') >= 0;
  3312. } else {
  3313. pc.canTrickleIceCandidates = false;
  3314. }
  3315. sections.forEach(function(mediaSection, sdpMLineIndex) {
  3316. var lines = sdp.splitLines(mediaSection);
  3317. var kind = sdp.getKind(mediaSection);
  3318. // treat bundle-only as not-rejected.
  3319. var rejected = sdp.isRejected(mediaSection) &&
  3320. sdp.matchPrefix(mediaSection, 'a=bundle-only').length === 0;
  3321. var protocol = lines[0].substr(2).split(' ')[2];
  3322. var direction = sdp.getDirection(mediaSection, sessionpart);
  3323. var remoteMsid = sdp.parseMsid(mediaSection);
  3324. var mid = sdp.getMid(mediaSection) || sdp.generateIdentifier();
  3325. // Reject datachannels which are not implemented yet.
  3326. if (rejected || (kind === 'application' && (protocol === 'DTLS/SCTP' ||
  3327. protocol === 'UDP/DTLS/SCTP'))) {
  3328. // TODO: this is dangerous in the case where a non-rejected m-line
  3329. // becomes rejected.
  3330. pc.transceivers[sdpMLineIndex] = {
  3331. mid: mid,
  3332. kind: kind,
  3333. protocol: protocol,
  3334. rejected: true
  3335. };
  3336. return;
  3337. }
  3338. if (!rejected && pc.transceivers[sdpMLineIndex] &&
  3339. pc.transceivers[sdpMLineIndex].rejected) {
  3340. // recycle a rejected transceiver.
  3341. pc.transceivers[sdpMLineIndex] = pc._createTransceiver(kind, true);
  3342. }
  3343. var transceiver;
  3344. var iceGatherer;
  3345. var iceTransport;
  3346. var dtlsTransport;
  3347. var rtpReceiver;
  3348. var sendEncodingParameters;
  3349. var recvEncodingParameters;
  3350. var localCapabilities;
  3351. var track;
  3352. // FIXME: ensure the mediaSection has rtcp-mux set.
  3353. var remoteCapabilities = sdp.parseRtpParameters(mediaSection);
  3354. var remoteIceParameters;
  3355. var remoteDtlsParameters;
  3356. if (!rejected) {
  3357. remoteIceParameters = sdp.getIceParameters(mediaSection,
  3358. sessionpart);
  3359. remoteDtlsParameters = sdp.getDtlsParameters(mediaSection,
  3360. sessionpart);
  3361. remoteDtlsParameters.role = 'client';
  3362. }
  3363. recvEncodingParameters =
  3364. sdp.parseRtpEncodingParameters(mediaSection);
  3365. var rtcpParameters = sdp.parseRtcpParameters(mediaSection);
  3366. var isComplete = sdp.matchPrefix(mediaSection,
  3367. 'a=end-of-candidates', sessionpart).length > 0;
  3368. var cands = sdp.matchPrefix(mediaSection, 'a=candidate:')
  3369. .map(function(cand) {
  3370. return sdp.parseCandidate(cand);
  3371. })
  3372. .filter(function(cand) {
  3373. return cand.component === 1;
  3374. });
  3375. // Check if we can use BUNDLE and dispose transports.
  3376. if ((description.type === 'offer' || description.type === 'answer') &&
  3377. !rejected && usingBundle && sdpMLineIndex > 0 &&
  3378. pc.transceivers[sdpMLineIndex]) {
  3379. pc._disposeIceAndDtlsTransports(sdpMLineIndex);
  3380. pc.transceivers[sdpMLineIndex].iceGatherer =
  3381. pc.transceivers[0].iceGatherer;
  3382. pc.transceivers[sdpMLineIndex].iceTransport =
  3383. pc.transceivers[0].iceTransport;
  3384. pc.transceivers[sdpMLineIndex].dtlsTransport =
  3385. pc.transceivers[0].dtlsTransport;
  3386. if (pc.transceivers[sdpMLineIndex].rtpSender) {
  3387. pc.transceivers[sdpMLineIndex].rtpSender.setTransport(
  3388. pc.transceivers[0].dtlsTransport);
  3389. }
  3390. if (pc.transceivers[sdpMLineIndex].rtpReceiver) {
  3391. pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(
  3392. pc.transceivers[0].dtlsTransport);
  3393. }
  3394. }
  3395. if (description.type === 'offer' && !rejected) {
  3396. transceiver = pc.transceivers[sdpMLineIndex] ||
  3397. pc._createTransceiver(kind);
  3398. transceiver.mid = mid;
  3399. if (!transceiver.iceGatherer) {
  3400. transceiver.iceGatherer = pc._createIceGatherer(sdpMLineIndex,
  3401. usingBundle);
  3402. }
  3403. if (cands.length && transceiver.iceTransport.state === 'new') {
  3404. if (isComplete && (!usingBundle || sdpMLineIndex === 0)) {
  3405. transceiver.iceTransport.setRemoteCandidates(cands);
  3406. } else {
  3407. cands.forEach(function(candidate) {
  3408. maybeAddCandidate(transceiver.iceTransport, candidate);
  3409. });
  3410. }
  3411. }
  3412. localCapabilities = window.RTCRtpReceiver.getCapabilities(kind);
  3413. // filter RTX until additional stuff needed for RTX is implemented
  3414. // in adapter.js
  3415. if (edgeVersion < 15019) {
  3416. localCapabilities.codecs = localCapabilities.codecs.filter(
  3417. function(codec) {
  3418. return codec.name !== 'rtx';
  3419. });
  3420. }
  3421. sendEncodingParameters = transceiver.sendEncodingParameters || [{
  3422. ssrc: (2 * sdpMLineIndex + 2) * 1001
  3423. }];
  3424. // TODO: rewrite to use http://w3c.github.io/webrtc-pc/#set-associated-remote-streams
  3425. var isNewTrack = false;
  3426. if (direction === 'sendrecv' || direction === 'sendonly') {
  3427. isNewTrack = !transceiver.rtpReceiver;
  3428. rtpReceiver = transceiver.rtpReceiver ||
  3429. new window.RTCRtpReceiver(transceiver.dtlsTransport, kind);
  3430. if (isNewTrack) {
  3431. var stream;
  3432. track = rtpReceiver.track;
  3433. // FIXME: does not work with Plan B.
  3434. if (remoteMsid && remoteMsid.stream === '-');
  3435. else if (remoteMsid) {
  3436. if (!streams[remoteMsid.stream]) {
  3437. streams[remoteMsid.stream] = new window.MediaStream();
  3438. Object.defineProperty(streams[remoteMsid.stream], 'id', {
  3439. get: function() {
  3440. return remoteMsid.stream;
  3441. }
  3442. });
  3443. }
  3444. Object.defineProperty(track, 'id', {
  3445. get: function() {
  3446. return remoteMsid.track;
  3447. }
  3448. });
  3449. stream = streams[remoteMsid.stream];
  3450. } else {
  3451. if (!streams.default) {
  3452. streams.default = new window.MediaStream();
  3453. }
  3454. stream = streams.default;
  3455. }
  3456. if (stream) {
  3457. addTrackToStreamAndFireEvent(track, stream);
  3458. transceiver.associatedRemoteMediaStreams.push(stream);
  3459. }
  3460. receiverList.push([track, rtpReceiver, stream]);
  3461. }
  3462. } else if (transceiver.rtpReceiver && transceiver.rtpReceiver.track) {
  3463. transceiver.associatedRemoteMediaStreams.forEach(function(s) {
  3464. var nativeTrack = s.getTracks().find(function(t) {
  3465. return t.id === transceiver.rtpReceiver.track.id;
  3466. });
  3467. if (nativeTrack) {
  3468. removeTrackFromStreamAndFireEvent(nativeTrack, s);
  3469. }
  3470. });
  3471. transceiver.associatedRemoteMediaStreams = [];
  3472. }
  3473. transceiver.localCapabilities = localCapabilities;
  3474. transceiver.remoteCapabilities = remoteCapabilities;
  3475. transceiver.rtpReceiver = rtpReceiver;
  3476. transceiver.rtcpParameters = rtcpParameters;
  3477. transceiver.sendEncodingParameters = sendEncodingParameters;
  3478. transceiver.recvEncodingParameters = recvEncodingParameters;
  3479. // Start the RTCRtpReceiver now. The RTPSender is started in
  3480. // setLocalDescription.
  3481. pc._transceive(pc.transceivers[sdpMLineIndex],
  3482. false,
  3483. isNewTrack);
  3484. } else if (description.type === 'answer' && !rejected) {
  3485. transceiver = pc.transceivers[sdpMLineIndex];
  3486. iceGatherer = transceiver.iceGatherer;
  3487. iceTransport = transceiver.iceTransport;
  3488. dtlsTransport = transceiver.dtlsTransport;
  3489. rtpReceiver = transceiver.rtpReceiver;
  3490. sendEncodingParameters = transceiver.sendEncodingParameters;
  3491. localCapabilities = transceiver.localCapabilities;
  3492. pc.transceivers[sdpMLineIndex].recvEncodingParameters =
  3493. recvEncodingParameters;
  3494. pc.transceivers[sdpMLineIndex].remoteCapabilities =
  3495. remoteCapabilities;
  3496. pc.transceivers[sdpMLineIndex].rtcpParameters = rtcpParameters;
  3497. if (cands.length && iceTransport.state === 'new') {
  3498. if ((isIceLite || isComplete) &&
  3499. (!usingBundle || sdpMLineIndex === 0)) {
  3500. iceTransport.setRemoteCandidates(cands);
  3501. } else {
  3502. cands.forEach(function(candidate) {
  3503. maybeAddCandidate(transceiver.iceTransport, candidate);
  3504. });
  3505. }
  3506. }
  3507. if (!usingBundle || sdpMLineIndex === 0) {
  3508. if (iceTransport.state === 'new') {
  3509. iceTransport.start(iceGatherer, remoteIceParameters,
  3510. 'controlling');
  3511. }
  3512. if (dtlsTransport.state === 'new') {
  3513. dtlsTransport.start(remoteDtlsParameters);
  3514. }
  3515. }
  3516. // If the offer contained RTX but the answer did not,
  3517. // remove RTX from sendEncodingParameters.
  3518. var commonCapabilities = getCommonCapabilities(
  3519. transceiver.localCapabilities,
  3520. transceiver.remoteCapabilities);
  3521. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  3522. return c.name.toLowerCase() === 'rtx';
  3523. }).length;
  3524. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  3525. delete transceiver.sendEncodingParameters[0].rtx;
  3526. }
  3527. pc._transceive(transceiver,
  3528. direction === 'sendrecv' || direction === 'recvonly',
  3529. direction === 'sendrecv' || direction === 'sendonly');
  3530. // TODO: rewrite to use http://w3c.github.io/webrtc-pc/#set-associated-remote-streams
  3531. if (rtpReceiver &&
  3532. (direction === 'sendrecv' || direction === 'sendonly')) {
  3533. track = rtpReceiver.track;
  3534. if (remoteMsid) {
  3535. if (!streams[remoteMsid.stream]) {
  3536. streams[remoteMsid.stream] = new window.MediaStream();
  3537. }
  3538. addTrackToStreamAndFireEvent(track, streams[remoteMsid.stream]);
  3539. receiverList.push([track, rtpReceiver, streams[remoteMsid.stream]]);
  3540. } else {
  3541. if (!streams.default) {
  3542. streams.default = new window.MediaStream();
  3543. }
  3544. addTrackToStreamAndFireEvent(track, streams.default);
  3545. receiverList.push([track, rtpReceiver, streams.default]);
  3546. }
  3547. } else {
  3548. // FIXME: actually the receiver should be created later.
  3549. delete transceiver.rtpReceiver;
  3550. }
  3551. }
  3552. });
  3553. if (pc._dtlsRole === undefined) {
  3554. pc._dtlsRole = description.type === 'offer' ? 'active' : 'passive';
  3555. }
  3556. pc._remoteDescription = {
  3557. type: description.type,
  3558. sdp: description.sdp
  3559. };
  3560. if (description.type === 'offer') {
  3561. pc._updateSignalingState('have-remote-offer');
  3562. } else {
  3563. pc._updateSignalingState('stable');
  3564. }
  3565. Object.keys(streams).forEach(function(sid) {
  3566. var stream = streams[sid];
  3567. if (stream.getTracks().length) {
  3568. if (pc.remoteStreams.indexOf(stream) === -1) {
  3569. pc.remoteStreams.push(stream);
  3570. var event = new Event('addstream');
  3571. event.stream = stream;
  3572. window.setTimeout(function() {
  3573. pc._dispatchEvent('addstream', event);
  3574. });
  3575. }
  3576. receiverList.forEach(function(item) {
  3577. var track = item[0];
  3578. var receiver = item[1];
  3579. if (stream.id !== item[2].id) {
  3580. return;
  3581. }
  3582. fireAddTrack(pc, track, receiver, [stream]);
  3583. });
  3584. }
  3585. });
  3586. receiverList.forEach(function(item) {
  3587. if (item[2]) {
  3588. return;
  3589. }
  3590. fireAddTrack(pc, item[0], item[1], []);
  3591. });
  3592. // check whether addIceCandidate({}) was called within four seconds after
  3593. // setRemoteDescription.
  3594. window.setTimeout(function() {
  3595. if (!(pc && pc.transceivers)) {
  3596. return;
  3597. }
  3598. pc.transceivers.forEach(function(transceiver) {
  3599. if (transceiver.iceTransport &&
  3600. transceiver.iceTransport.state === 'new' &&
  3601. transceiver.iceTransport.getRemoteCandidates().length > 0) {
  3602. console.warn('Timeout for addRemoteCandidate. Consider sending ' +
  3603. 'an end-of-candidates notification');
  3604. transceiver.iceTransport.addRemoteCandidate({});
  3605. }
  3606. });
  3607. }, 4000);
  3608. return Promise.resolve();
  3609. };
  3610. RTCPeerConnection.prototype.close = function() {
  3611. this.transceivers.forEach(function(transceiver) {
  3612. /* not yet
  3613. if (transceiver.iceGatherer) {
  3614. transceiver.iceGatherer.close();
  3615. }
  3616. */
  3617. if (transceiver.iceTransport) {
  3618. transceiver.iceTransport.stop();
  3619. }
  3620. if (transceiver.dtlsTransport) {
  3621. transceiver.dtlsTransport.stop();
  3622. }
  3623. if (transceiver.rtpSender) {
  3624. transceiver.rtpSender.stop();
  3625. }
  3626. if (transceiver.rtpReceiver) {
  3627. transceiver.rtpReceiver.stop();
  3628. }
  3629. });
  3630. // FIXME: clean up tracks, local streams, remote streams, etc
  3631. this._isClosed = true;
  3632. this._updateSignalingState('closed');
  3633. };
  3634. // Update the signaling state.
  3635. RTCPeerConnection.prototype._updateSignalingState = function(newState) {
  3636. this.signalingState = newState;
  3637. var event = new Event('signalingstatechange');
  3638. this._dispatchEvent('signalingstatechange', event);
  3639. };
  3640. // Determine whether to fire the negotiationneeded event.
  3641. RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() {
  3642. var pc = this;
  3643. if (this.signalingState !== 'stable' || this.needNegotiation === true) {
  3644. return;
  3645. }
  3646. this.needNegotiation = true;
  3647. window.setTimeout(function() {
  3648. if (pc.needNegotiation) {
  3649. pc.needNegotiation = false;
  3650. var event = new Event('negotiationneeded');
  3651. pc._dispatchEvent('negotiationneeded', event);
  3652. }
  3653. }, 0);
  3654. };
  3655. // Update the ice connection state.
  3656. RTCPeerConnection.prototype._updateIceConnectionState = function() {
  3657. var newState;
  3658. var states = {
  3659. 'new': 0,
  3660. closed: 0,
  3661. checking: 0,
  3662. connected: 0,
  3663. completed: 0,
  3664. disconnected: 0,
  3665. failed: 0
  3666. };
  3667. this.transceivers.forEach(function(transceiver) {
  3668. if (transceiver.iceTransport && !transceiver.rejected) {
  3669. states[transceiver.iceTransport.state]++;
  3670. }
  3671. });
  3672. newState = 'new';
  3673. if (states.failed > 0) {
  3674. newState = 'failed';
  3675. } else if (states.checking > 0) {
  3676. newState = 'checking';
  3677. } else if (states.disconnected > 0) {
  3678. newState = 'disconnected';
  3679. } else if (states.new > 0) {
  3680. newState = 'new';
  3681. } else if (states.connected > 0) {
  3682. newState = 'connected';
  3683. } else if (states.completed > 0) {
  3684. newState = 'completed';
  3685. }
  3686. if (newState !== this.iceConnectionState) {
  3687. this.iceConnectionState = newState;
  3688. var event = new Event('iceconnectionstatechange');
  3689. this._dispatchEvent('iceconnectionstatechange', event);
  3690. }
  3691. };
  3692. // Update the connection state.
  3693. RTCPeerConnection.prototype._updateConnectionState = function() {
  3694. var newState;
  3695. var states = {
  3696. 'new': 0,
  3697. closed: 0,
  3698. connecting: 0,
  3699. connected: 0,
  3700. completed: 0,
  3701. disconnected: 0,
  3702. failed: 0
  3703. };
  3704. this.transceivers.forEach(function(transceiver) {
  3705. if (transceiver.iceTransport && transceiver.dtlsTransport &&
  3706. !transceiver.rejected) {
  3707. states[transceiver.iceTransport.state]++;
  3708. states[transceiver.dtlsTransport.state]++;
  3709. }
  3710. });
  3711. // ICETransport.completed and connected are the same for this purpose.
  3712. states.connected += states.completed;
  3713. newState = 'new';
  3714. if (states.failed > 0) {
  3715. newState = 'failed';
  3716. } else if (states.connecting > 0) {
  3717. newState = 'connecting';
  3718. } else if (states.disconnected > 0) {
  3719. newState = 'disconnected';
  3720. } else if (states.new > 0) {
  3721. newState = 'new';
  3722. } else if (states.connected > 0) {
  3723. newState = 'connected';
  3724. }
  3725. if (newState !== this.connectionState) {
  3726. this.connectionState = newState;
  3727. var event = new Event('connectionstatechange');
  3728. this._dispatchEvent('connectionstatechange', event);
  3729. }
  3730. };
  3731. RTCPeerConnection.prototype.createOffer = function() {
  3732. var pc = this;
  3733. if (pc._isClosed) {
  3734. return Promise.reject(makeError('InvalidStateError',
  3735. 'Can not call createOffer after close'));
  3736. }
  3737. var numAudioTracks = pc.transceivers.filter(function(t) {
  3738. return t.kind === 'audio';
  3739. }).length;
  3740. var numVideoTracks = pc.transceivers.filter(function(t) {
  3741. return t.kind === 'video';
  3742. }).length;
  3743. // Determine number of audio and video tracks we need to send/recv.
  3744. var offerOptions = arguments[0];
  3745. if (offerOptions) {
  3746. // Reject Chrome legacy constraints.
  3747. if (offerOptions.mandatory || offerOptions.optional) {
  3748. throw new TypeError(
  3749. 'Legacy mandatory/optional constraints not supported.');
  3750. }
  3751. if (offerOptions.offerToReceiveAudio !== undefined) {
  3752. if (offerOptions.offerToReceiveAudio === true) {
  3753. numAudioTracks = 1;
  3754. } else if (offerOptions.offerToReceiveAudio === false) {
  3755. numAudioTracks = 0;
  3756. } else {
  3757. numAudioTracks = offerOptions.offerToReceiveAudio;
  3758. }
  3759. }
  3760. if (offerOptions.offerToReceiveVideo !== undefined) {
  3761. if (offerOptions.offerToReceiveVideo === true) {
  3762. numVideoTracks = 1;
  3763. } else if (offerOptions.offerToReceiveVideo === false) {
  3764. numVideoTracks = 0;
  3765. } else {
  3766. numVideoTracks = offerOptions.offerToReceiveVideo;
  3767. }
  3768. }
  3769. }
  3770. pc.transceivers.forEach(function(transceiver) {
  3771. if (transceiver.kind === 'audio') {
  3772. numAudioTracks--;
  3773. if (numAudioTracks < 0) {
  3774. transceiver.wantReceive = false;
  3775. }
  3776. } else if (transceiver.kind === 'video') {
  3777. numVideoTracks--;
  3778. if (numVideoTracks < 0) {
  3779. transceiver.wantReceive = false;
  3780. }
  3781. }
  3782. });
  3783. // Create M-lines for recvonly streams.
  3784. while (numAudioTracks > 0 || numVideoTracks > 0) {
  3785. if (numAudioTracks > 0) {
  3786. pc._createTransceiver('audio');
  3787. numAudioTracks--;
  3788. }
  3789. if (numVideoTracks > 0) {
  3790. pc._createTransceiver('video');
  3791. numVideoTracks--;
  3792. }
  3793. }
  3794. var sdp$1 = sdp.writeSessionBoilerplate(pc._sdpSessionId,
  3795. pc._sdpSessionVersion++);
  3796. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3797. // For each track, create an ice gatherer, ice transport,
  3798. // dtls transport, potentially rtpsender and rtpreceiver.
  3799. var track = transceiver.track;
  3800. var kind = transceiver.kind;
  3801. var mid = transceiver.mid || sdp.generateIdentifier();
  3802. transceiver.mid = mid;
  3803. if (!transceiver.iceGatherer) {
  3804. transceiver.iceGatherer = pc._createIceGatherer(sdpMLineIndex,
  3805. pc.usingBundle);
  3806. }
  3807. var localCapabilities = window.RTCRtpSender.getCapabilities(kind);
  3808. // filter RTX until additional stuff needed for RTX is implemented
  3809. // in adapter.js
  3810. if (edgeVersion < 15019) {
  3811. localCapabilities.codecs = localCapabilities.codecs.filter(
  3812. function(codec) {
  3813. return codec.name !== 'rtx';
  3814. });
  3815. }
  3816. localCapabilities.codecs.forEach(function(codec) {
  3817. // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
  3818. // by adding level-asymmetry-allowed=1
  3819. if (codec.name === 'H264' &&
  3820. codec.parameters['level-asymmetry-allowed'] === undefined) {
  3821. codec.parameters['level-asymmetry-allowed'] = '1';
  3822. }
  3823. // for subsequent offers, we might have to re-use the payload
  3824. // type of the last offer.
  3825. if (transceiver.remoteCapabilities &&
  3826. transceiver.remoteCapabilities.codecs) {
  3827. transceiver.remoteCapabilities.codecs.forEach(function(remoteCodec) {
  3828. if (codec.name.toLowerCase() === remoteCodec.name
  3829. .toLowerCase() &&
  3830. codec.clockRate === remoteCodec.clockRate) {
  3831. codec.preferredPayloadType = remoteCodec.payloadType;
  3832. }
  3833. });
  3834. }
  3835. });
  3836. localCapabilities.headerExtensions.forEach(function(hdrExt) {
  3837. var remoteExtensions = transceiver.remoteCapabilities &&
  3838. transceiver.remoteCapabilities.headerExtensions || [];
  3839. remoteExtensions.forEach(function(rHdrExt) {
  3840. if (hdrExt.uri === rHdrExt.uri) {
  3841. hdrExt.id = rHdrExt.id;
  3842. }
  3843. });
  3844. });
  3845. // generate an ssrc now, to be used later in rtpSender.send
  3846. var sendEncodingParameters = transceiver.sendEncodingParameters || [{
  3847. ssrc: (2 * sdpMLineIndex + 1) * 1001
  3848. }];
  3849. if (track) {
  3850. // add RTX
  3851. if (edgeVersion >= 15019 && kind === 'video' &&
  3852. !sendEncodingParameters[0].rtx) {
  3853. sendEncodingParameters[0].rtx = {
  3854. ssrc: sendEncodingParameters[0].ssrc + 1
  3855. };
  3856. }
  3857. }
  3858. if (transceiver.wantReceive) {
  3859. transceiver.rtpReceiver = new window.RTCRtpReceiver(
  3860. transceiver.dtlsTransport, kind);
  3861. }
  3862. transceiver.localCapabilities = localCapabilities;
  3863. transceiver.sendEncodingParameters = sendEncodingParameters;
  3864. });
  3865. // always offer BUNDLE and dispose on return if not supported.
  3866. if (pc._config.bundlePolicy !== 'max-compat') {
  3867. sdp$1 += 'a=group:BUNDLE ' + pc.transceivers.map(function(t) {
  3868. return t.mid;
  3869. }).join(' ') + '\r\n';
  3870. }
  3871. sdp$1 += 'a=ice-options:trickle\r\n';
  3872. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3873. sdp$1 += writeMediaSection(transceiver, transceiver.localCapabilities,
  3874. 'offer', transceiver.stream, pc._dtlsRole);
  3875. sdp$1 += 'a=rtcp-rsize\r\n';
  3876. if (transceiver.iceGatherer && pc.iceGatheringState !== 'new' &&
  3877. (sdpMLineIndex === 0 || !pc.usingBundle)) {
  3878. transceiver.iceGatherer.getLocalCandidates().forEach(function(cand) {
  3879. cand.component = 1;
  3880. sdp$1 += 'a=' + sdp.writeCandidate(cand) + '\r\n';
  3881. });
  3882. if (transceiver.iceGatherer.state === 'completed') {
  3883. sdp$1 += 'a=end-of-candidates\r\n';
  3884. }
  3885. }
  3886. });
  3887. var desc = new window.RTCSessionDescription({
  3888. type: 'offer',
  3889. sdp: sdp$1
  3890. });
  3891. return Promise.resolve(desc);
  3892. };
  3893. RTCPeerConnection.prototype.createAnswer = function() {
  3894. var pc = this;
  3895. if (pc._isClosed) {
  3896. return Promise.reject(makeError('InvalidStateError',
  3897. 'Can not call createAnswer after close'));
  3898. }
  3899. if (!(pc.signalingState === 'have-remote-offer' ||
  3900. pc.signalingState === 'have-local-pranswer')) {
  3901. return Promise.reject(makeError('InvalidStateError',
  3902. 'Can not call createAnswer in signalingState ' + pc.signalingState));
  3903. }
  3904. var sdp$1 = sdp.writeSessionBoilerplate(pc._sdpSessionId,
  3905. pc._sdpSessionVersion++);
  3906. if (pc.usingBundle) {
  3907. sdp$1 += 'a=group:BUNDLE ' + pc.transceivers.map(function(t) {
  3908. return t.mid;
  3909. }).join(' ') + '\r\n';
  3910. }
  3911. sdp$1 += 'a=ice-options:trickle\r\n';
  3912. var mediaSectionsInOffer = sdp.getMediaSections(
  3913. pc._remoteDescription.sdp).length;
  3914. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3915. if (sdpMLineIndex + 1 > mediaSectionsInOffer) {
  3916. return;
  3917. }
  3918. if (transceiver.rejected) {
  3919. if (transceiver.kind === 'application') {
  3920. if (transceiver.protocol === 'DTLS/SCTP') { // legacy fmt
  3921. sdp$1 += 'm=application 0 DTLS/SCTP 5000\r\n';
  3922. } else {
  3923. sdp$1 += 'm=application 0 ' + transceiver.protocol +
  3924. ' webrtc-datachannel\r\n';
  3925. }
  3926. } else if (transceiver.kind === 'audio') {
  3927. sdp$1 += 'm=audio 0 UDP/TLS/RTP/SAVPF 0\r\n' +
  3928. 'a=rtpmap:0 PCMU/8000\r\n';
  3929. } else if (transceiver.kind === 'video') {
  3930. sdp$1 += 'm=video 0 UDP/TLS/RTP/SAVPF 120\r\n' +
  3931. 'a=rtpmap:120 VP8/90000\r\n';
  3932. }
  3933. sdp$1 += 'c=IN IP4 0.0.0.0\r\n' +
  3934. 'a=inactive\r\n' +
  3935. 'a=mid:' + transceiver.mid + '\r\n';
  3936. return;
  3937. }
  3938. // FIXME: look at direction.
  3939. if (transceiver.stream) {
  3940. var localTrack;
  3941. if (transceiver.kind === 'audio') {
  3942. localTrack = transceiver.stream.getAudioTracks()[0];
  3943. } else if (transceiver.kind === 'video') {
  3944. localTrack = transceiver.stream.getVideoTracks()[0];
  3945. }
  3946. if (localTrack) {
  3947. // add RTX
  3948. if (edgeVersion >= 15019 && transceiver.kind === 'video' &&
  3949. !transceiver.sendEncodingParameters[0].rtx) {
  3950. transceiver.sendEncodingParameters[0].rtx = {
  3951. ssrc: transceiver.sendEncodingParameters[0].ssrc + 1
  3952. };
  3953. }
  3954. }
  3955. }
  3956. // Calculate intersection of capabilities.
  3957. var commonCapabilities = getCommonCapabilities(
  3958. transceiver.localCapabilities,
  3959. transceiver.remoteCapabilities);
  3960. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  3961. return c.name.toLowerCase() === 'rtx';
  3962. }).length;
  3963. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  3964. delete transceiver.sendEncodingParameters[0].rtx;
  3965. }
  3966. sdp$1 += writeMediaSection(transceiver, commonCapabilities,
  3967. 'answer', transceiver.stream, pc._dtlsRole);
  3968. if (transceiver.rtcpParameters &&
  3969. transceiver.rtcpParameters.reducedSize) {
  3970. sdp$1 += 'a=rtcp-rsize\r\n';
  3971. }
  3972. });
  3973. var desc = new window.RTCSessionDescription({
  3974. type: 'answer',
  3975. sdp: sdp$1
  3976. });
  3977. return Promise.resolve(desc);
  3978. };
  3979. RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
  3980. var pc = this;
  3981. var sections;
  3982. if (candidate && !(candidate.sdpMLineIndex !== undefined ||
  3983. candidate.sdpMid)) {
  3984. return Promise.reject(new TypeError('sdpMLineIndex or sdpMid required'));
  3985. }
  3986. // TODO: needs to go into ops queue.
  3987. return new Promise(function(resolve, reject) {
  3988. if (!pc._remoteDescription) {
  3989. return reject(makeError('InvalidStateError',
  3990. 'Can not add ICE candidate without a remote description'));
  3991. } else if (!candidate || candidate.candidate === '') {
  3992. for (var j = 0; j < pc.transceivers.length; j++) {
  3993. if (pc.transceivers[j].rejected) {
  3994. continue;
  3995. }
  3996. pc.transceivers[j].iceTransport.addRemoteCandidate({});
  3997. sections = sdp.getMediaSections(pc._remoteDescription.sdp);
  3998. sections[j] += 'a=end-of-candidates\r\n';
  3999. pc._remoteDescription.sdp =
  4000. sdp.getDescription(pc._remoteDescription.sdp) +
  4001. sections.join('');
  4002. if (pc.usingBundle) {
  4003. break;
  4004. }
  4005. }
  4006. } else {
  4007. var sdpMLineIndex = candidate.sdpMLineIndex;
  4008. if (candidate.sdpMid) {
  4009. for (var i = 0; i < pc.transceivers.length; i++) {
  4010. if (pc.transceivers[i].mid === candidate.sdpMid) {
  4011. sdpMLineIndex = i;
  4012. break;
  4013. }
  4014. }
  4015. }
  4016. var transceiver = pc.transceivers[sdpMLineIndex];
  4017. if (transceiver) {
  4018. if (transceiver.rejected) {
  4019. return resolve();
  4020. }
  4021. var cand = Object.keys(candidate.candidate).length > 0 ?
  4022. sdp.parseCandidate(candidate.candidate) : {};
  4023. // Ignore Chrome's invalid candidates since Edge does not like them.
  4024. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
  4025. return resolve();
  4026. }
  4027. // Ignore RTCP candidates, we assume RTCP-MUX.
  4028. if (cand.component && cand.component !== 1) {
  4029. return resolve();
  4030. }
  4031. // when using bundle, avoid adding candidates to the wrong
  4032. // ice transport. And avoid adding candidates added in the SDP.
  4033. if (sdpMLineIndex === 0 || (sdpMLineIndex > 0 &&
  4034. transceiver.iceTransport !== pc.transceivers[0].iceTransport)) {
  4035. if (!maybeAddCandidate(transceiver.iceTransport, cand)) {
  4036. return reject(makeError('OperationError',
  4037. 'Can not add ICE candidate'));
  4038. }
  4039. }
  4040. // update the remoteDescription.
  4041. var candidateString = candidate.candidate.trim();
  4042. if (candidateString.indexOf('a=') === 0) {
  4043. candidateString = candidateString.substr(2);
  4044. }
  4045. sections = sdp.getMediaSections(pc._remoteDescription.sdp);
  4046. sections[sdpMLineIndex] += 'a=' +
  4047. (cand.type ? candidateString : 'end-of-candidates') +
  4048. '\r\n';
  4049. pc._remoteDescription.sdp =
  4050. sdp.getDescription(pc._remoteDescription.sdp) +
  4051. sections.join('');
  4052. } else {
  4053. return reject(makeError('OperationError',
  4054. 'Can not add ICE candidate'));
  4055. }
  4056. }
  4057. resolve();
  4058. });
  4059. };
  4060. RTCPeerConnection.prototype.getStats = function(selector) {
  4061. if (selector && selector instanceof window.MediaStreamTrack) {
  4062. var senderOrReceiver = null;
  4063. this.transceivers.forEach(function(transceiver) {
  4064. if (transceiver.rtpSender &&
  4065. transceiver.rtpSender.track === selector) {
  4066. senderOrReceiver = transceiver.rtpSender;
  4067. } else if (transceiver.rtpReceiver &&
  4068. transceiver.rtpReceiver.track === selector) {
  4069. senderOrReceiver = transceiver.rtpReceiver;
  4070. }
  4071. });
  4072. if (!senderOrReceiver) {
  4073. throw makeError('InvalidAccessError', 'Invalid selector.');
  4074. }
  4075. return senderOrReceiver.getStats();
  4076. }
  4077. var promises = [];
  4078. this.transceivers.forEach(function(transceiver) {
  4079. ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
  4080. 'dtlsTransport'
  4081. ].forEach(function(method) {
  4082. if (transceiver[method]) {
  4083. promises.push(transceiver[method].getStats());
  4084. }
  4085. });
  4086. });
  4087. return Promise.all(promises).then(function(allStats) {
  4088. var results = new Map();
  4089. allStats.forEach(function(stats) {
  4090. stats.forEach(function(stat) {
  4091. results.set(stat.id, stat);
  4092. });
  4093. });
  4094. return results;
  4095. });
  4096. };
  4097. // fix low-level stat names and return Map instead of object.
  4098. var ortcObjects = ['RTCRtpSender', 'RTCRtpReceiver', 'RTCIceGatherer',
  4099. 'RTCIceTransport', 'RTCDtlsTransport'
  4100. ];
  4101. ortcObjects.forEach(function(ortcObjectName) {
  4102. var obj = window[ortcObjectName];
  4103. if (obj && obj.prototype && obj.prototype.getStats) {
  4104. var nativeGetstats = obj.prototype.getStats;
  4105. obj.prototype.getStats = function() {
  4106. return nativeGetstats.apply(this)
  4107. .then(function(nativeStats) {
  4108. var mapStats = new Map();
  4109. Object.keys(nativeStats).forEach(function(id) {
  4110. nativeStats[id].type = fixStatsType(nativeStats[id]);
  4111. mapStats.set(id, nativeStats[id]);
  4112. });
  4113. return mapStats;
  4114. });
  4115. };
  4116. }
  4117. });
  4118. // legacy callback shims. Should be moved to adapter.js some days.
  4119. var methods = ['createOffer', 'createAnswer'];
  4120. methods.forEach(function(method) {
  4121. var nativeMethod = RTCPeerConnection.prototype[method];
  4122. RTCPeerConnection.prototype[method] = function() {
  4123. var args = arguments;
  4124. if (typeof args[0] === 'function' ||
  4125. typeof args[1] === 'function') { // legacy
  4126. return nativeMethod.apply(this, [arguments[2]])
  4127. .then(function(description) {
  4128. if (typeof args[0] === 'function') {
  4129. args[0].apply(null, [description]);
  4130. }
  4131. }, function(error) {
  4132. if (typeof args[1] === 'function') {
  4133. args[1].apply(null, [error]);
  4134. }
  4135. });
  4136. }
  4137. return nativeMethod.apply(this, arguments);
  4138. };
  4139. });
  4140. methods = ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'];
  4141. methods.forEach(function(method) {
  4142. var nativeMethod = RTCPeerConnection.prototype[method];
  4143. RTCPeerConnection.prototype[method] = function() {
  4144. var args = arguments;
  4145. if (typeof args[1] === 'function' ||
  4146. typeof args[2] === 'function') { // legacy
  4147. return nativeMethod.apply(this, arguments)
  4148. .then(function() {
  4149. if (typeof args[1] === 'function') {
  4150. args[1].apply(null);
  4151. }
  4152. }, function(error) {
  4153. if (typeof args[2] === 'function') {
  4154. args[2].apply(null, [error]);
  4155. }
  4156. });
  4157. }
  4158. return nativeMethod.apply(this, arguments);
  4159. };
  4160. });
  4161. // getStats is special. It doesn't have a spec legacy method yet we support
  4162. // getStats(something, cb) without error callbacks.
  4163. ['getStats'].forEach(function(method) {
  4164. var nativeMethod = RTCPeerConnection.prototype[method];
  4165. RTCPeerConnection.prototype[method] = function() {
  4166. var args = arguments;
  4167. if (typeof args[1] === 'function') {
  4168. return nativeMethod.apply(this, arguments)
  4169. .then(function() {
  4170. if (typeof args[1] === 'function') {
  4171. args[1].apply(null);
  4172. }
  4173. });
  4174. }
  4175. return nativeMethod.apply(this, arguments);
  4176. };
  4177. });
  4178. return RTCPeerConnection;
  4179. };
  4180. /*
  4181. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4182. *
  4183. * Use of this source code is governed by a BSD-style license
  4184. * that can be found in the LICENSE file in the root of the source
  4185. * tree.
  4186. */
  4187. function shimGetUserMedia$2(window) {
  4188. const navigator = window && window.navigator;
  4189. const shimError_ = function(e) {
  4190. return {
  4191. name: {
  4192. PermissionDeniedError: 'NotAllowedError'
  4193. } [e.name] || e.name,
  4194. message: e.message,
  4195. constraint: e.constraint,
  4196. toString() {
  4197. return this.name;
  4198. }
  4199. };
  4200. };
  4201. // getUserMedia error shim.
  4202. const origGetUserMedia = navigator.mediaDevices.getUserMedia.
  4203. bind(navigator.mediaDevices);
  4204. navigator.mediaDevices.getUserMedia = function(c) {
  4205. return origGetUserMedia(c).catch(e => Promise.reject(shimError_(e)));
  4206. };
  4207. }
  4208. /*
  4209. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  4210. *
  4211. * Use of this source code is governed by a BSD-style license
  4212. * that can be found in the LICENSE file in the root of the source
  4213. * tree.
  4214. */
  4215. function shimGetDisplayMedia$1(window) {
  4216. if (!('getDisplayMedia' in window.navigator)) {
  4217. return;
  4218. }
  4219. if (!(window.navigator.mediaDevices)) {
  4220. return;
  4221. }
  4222. if (window.navigator.mediaDevices &&
  4223. 'getDisplayMedia' in window.navigator.mediaDevices) {
  4224. return;
  4225. }
  4226. window.navigator.mediaDevices.getDisplayMedia =
  4227. window.navigator.getDisplayMedia.bind(window.navigator);
  4228. }
  4229. /*
  4230. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4231. *
  4232. * Use of this source code is governed by a BSD-style license
  4233. * that can be found in the LICENSE file in the root of the source
  4234. * tree.
  4235. */
  4236. function shimPeerConnection$1(window, browserDetails) {
  4237. if (window.RTCIceGatherer) {
  4238. if (!window.RTCIceCandidate) {
  4239. window.RTCIceCandidate = function RTCIceCandidate(args) {
  4240. return args;
  4241. };
  4242. }
  4243. if (!window.RTCSessionDescription) {
  4244. window.RTCSessionDescription = function RTCSessionDescription(args) {
  4245. return args;
  4246. };
  4247. }
  4248. // this adds an additional event listener to MediaStrackTrack that signals
  4249. // when a tracks enabled property was changed. Workaround for a bug in
  4250. // addStream, see below. No longer required in 15025+
  4251. if (browserDetails.version < 15025) {
  4252. const origMSTEnabled = Object.getOwnPropertyDescriptor(
  4253. window.MediaStreamTrack.prototype, 'enabled');
  4254. Object.defineProperty(window.MediaStreamTrack.prototype, 'enabled', {
  4255. set(value) {
  4256. origMSTEnabled.set.call(this, value);
  4257. const ev = new Event('enabled');
  4258. ev.enabled = value;
  4259. this.dispatchEvent(ev);
  4260. }
  4261. });
  4262. }
  4263. }
  4264. // ORTC defines the DTMF sender a bit different.
  4265. // https://github.com/w3c/ortc/issues/714
  4266. if (window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
  4267. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  4268. get() {
  4269. if (this._dtmf === undefined) {
  4270. if (this.track.kind === 'audio') {
  4271. this._dtmf = new window.RTCDtmfSender(this);
  4272. } else if (this.track.kind === 'video') {
  4273. this._dtmf = null;
  4274. }
  4275. }
  4276. return this._dtmf;
  4277. }
  4278. });
  4279. }
  4280. // Edge currently only implements the RTCDtmfSender, not the
  4281. // RTCDTMFSender alias. See http://draft.ortc.org/#rtcdtmfsender2*
  4282. if (window.RTCDtmfSender && !window.RTCDTMFSender) {
  4283. window.RTCDTMFSender = window.RTCDtmfSender;
  4284. }
  4285. const RTCPeerConnectionShim = rtcpeerconnection(window,
  4286. browserDetails.version);
  4287. window.RTCPeerConnection = function RTCPeerConnection(config) {
  4288. if (config && config.iceServers) {
  4289. config.iceServers = filterIceServers$1(config.iceServers,
  4290. browserDetails.version);
  4291. log$1('ICE servers after filtering:', config.iceServers);
  4292. }
  4293. return new RTCPeerConnectionShim(config);
  4294. };
  4295. window.RTCPeerConnection.prototype = RTCPeerConnectionShim.prototype;
  4296. }
  4297. function shimReplaceTrack(window) {
  4298. // ORTC has replaceTrack -- https://github.com/w3c/ortc/issues/614
  4299. if (window.RTCRtpSender &&
  4300. !('replaceTrack' in window.RTCRtpSender.prototype)) {
  4301. window.RTCRtpSender.prototype.replaceTrack =
  4302. window.RTCRtpSender.prototype.setTrack;
  4303. }
  4304. }
  4305. var edgeShim = /*#__PURE__*/ Object.freeze({
  4306. __proto__: null,
  4307. shimPeerConnection: shimPeerConnection$1,
  4308. shimReplaceTrack: shimReplaceTrack,
  4309. shimGetUserMedia: shimGetUserMedia$2,
  4310. shimGetDisplayMedia: shimGetDisplayMedia$1
  4311. });
  4312. /*
  4313. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4314. *
  4315. * Use of this source code is governed by a BSD-style license
  4316. * that can be found in the LICENSE file in the root of the source
  4317. * tree.
  4318. */
  4319. function shimGetUserMedia$1(window, browserDetails) {
  4320. const navigator = window && window.navigator;
  4321. const MediaStreamTrack = window && window.MediaStreamTrack;
  4322. navigator.getUserMedia = function(constraints, onSuccess, onError) {
  4323. // Replace Firefox 44+'s deprecation warning with unprefixed version.
  4324. deprecated('navigator.getUserMedia',
  4325. 'navigator.mediaDevices.getUserMedia');
  4326. navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  4327. };
  4328. if (!(browserDetails.version > 55 &&
  4329. 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
  4330. const remap = function(obj, a, b) {
  4331. if (a in obj && !(b in obj)) {
  4332. obj[b] = obj[a];
  4333. delete obj[a];
  4334. }
  4335. };
  4336. const nativeGetUserMedia = navigator.mediaDevices.getUserMedia.
  4337. bind(navigator.mediaDevices);
  4338. navigator.mediaDevices.getUserMedia = function(c) {
  4339. if (typeof c === 'object' && typeof c.audio === 'object') {
  4340. c = JSON.parse(JSON.stringify(c));
  4341. remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
  4342. remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
  4343. }
  4344. return nativeGetUserMedia(c);
  4345. };
  4346. if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
  4347. const nativeGetSettings = MediaStreamTrack.prototype.getSettings;
  4348. MediaStreamTrack.prototype.getSettings = function() {
  4349. const obj = nativeGetSettings.apply(this, arguments);
  4350. remap(obj, 'mozAutoGainControl', 'autoGainControl');
  4351. remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
  4352. return obj;
  4353. };
  4354. }
  4355. if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
  4356. const nativeApplyConstraints =
  4357. MediaStreamTrack.prototype.applyConstraints;
  4358. MediaStreamTrack.prototype.applyConstraints = function(c) {
  4359. if (this.kind === 'audio' && typeof c === 'object') {
  4360. c = JSON.parse(JSON.stringify(c));
  4361. remap(c, 'autoGainControl', 'mozAutoGainControl');
  4362. remap(c, 'noiseSuppression', 'mozNoiseSuppression');
  4363. }
  4364. return nativeApplyConstraints.apply(this, [c]);
  4365. };
  4366. }
  4367. }
  4368. }
  4369. /*
  4370. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  4371. *
  4372. * Use of this source code is governed by a BSD-style license
  4373. * that can be found in the LICENSE file in the root of the source
  4374. * tree.
  4375. */
  4376. function shimGetDisplayMedia(window, preferredMediaSource) {
  4377. if (window.navigator.mediaDevices &&
  4378. 'getDisplayMedia' in window.navigator.mediaDevices) {
  4379. return;
  4380. }
  4381. if (!(window.navigator.mediaDevices)) {
  4382. return;
  4383. }
  4384. window.navigator.mediaDevices.getDisplayMedia =
  4385. function getDisplayMedia(constraints) {
  4386. if (!(constraints && constraints.video)) {
  4387. const err = new DOMException('getDisplayMedia without video ' +
  4388. 'constraints is undefined');
  4389. err.name = 'NotFoundError';
  4390. // from https://heycam.github.io/webidl/#idl-DOMException-error-names
  4391. err.code = 8;
  4392. return Promise.reject(err);
  4393. }
  4394. if (constraints.video === true) {
  4395. constraints.video = {
  4396. mediaSource: preferredMediaSource
  4397. };
  4398. } else {
  4399. constraints.video.mediaSource = preferredMediaSource;
  4400. }
  4401. return window.navigator.mediaDevices.getUserMedia(constraints);
  4402. };
  4403. }
  4404. /*
  4405. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4406. *
  4407. * Use of this source code is governed by a BSD-style license
  4408. * that can be found in the LICENSE file in the root of the source
  4409. * tree.
  4410. */
  4411. function shimOnTrack(window) {
  4412. if (typeof window === 'object' && window.RTCTrackEvent &&
  4413. ('receiver' in window.RTCTrackEvent.prototype) &&
  4414. !('transceiver' in window.RTCTrackEvent.prototype)) {
  4415. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  4416. get() {
  4417. return {
  4418. receiver: this.receiver
  4419. };
  4420. }
  4421. });
  4422. }
  4423. }
  4424. function shimPeerConnection(window, browserDetails) {
  4425. if (typeof window !== 'object' ||
  4426. !(window.RTCPeerConnection || window.mozRTCPeerConnection)) {
  4427. return; // probably media.peerconnection.enabled=false in about:config
  4428. }
  4429. if (!window.RTCPeerConnection && window.mozRTCPeerConnection) {
  4430. // very basic support for old versions.
  4431. window.RTCPeerConnection = window.mozRTCPeerConnection;
  4432. }
  4433. if (browserDetails.version < 53) {
  4434. // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
  4435. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  4436. .forEach(function(method) {
  4437. const nativeMethod = window.RTCPeerConnection.prototype[method];
  4438. const methodObj = {
  4439. [method]() {
  4440. arguments[0] = new((method === 'addIceCandidate') ?
  4441. window.RTCIceCandidate :
  4442. window.RTCSessionDescription)(arguments[0]);
  4443. return nativeMethod.apply(this, arguments);
  4444. }
  4445. };
  4446. window.RTCPeerConnection.prototype[method] = methodObj[method];
  4447. });
  4448. }
  4449. const modernStatsTypes = {
  4450. inboundrtp: 'inbound-rtp',
  4451. outboundrtp: 'outbound-rtp',
  4452. candidatepair: 'candidate-pair',
  4453. localcandidate: 'local-candidate',
  4454. remotecandidate: 'remote-candidate'
  4455. };
  4456. const nativeGetStats = window.RTCPeerConnection.prototype.getStats;
  4457. window.RTCPeerConnection.prototype.getStats = function getStats() {
  4458. const [selector, onSucc, onErr] = arguments;
  4459. return nativeGetStats.apply(this, [selector || null])
  4460. .then(stats => {
  4461. if (browserDetails.version < 53 && !onSucc) {
  4462. // Shim only promise getStats with spec-hyphens in type names
  4463. // Leave callback version alone; misc old uses of forEach before Map
  4464. try {
  4465. stats.forEach(stat => {
  4466. stat.type = modernStatsTypes[stat.type] || stat.type;
  4467. });
  4468. } catch (e) {
  4469. if (e.name !== 'TypeError') {
  4470. throw e;
  4471. }
  4472. // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
  4473. stats.forEach((stat, i) => {
  4474. stats.set(i, Object.assign({}, stat, {
  4475. type: modernStatsTypes[stat.type] || stat.type
  4476. }));
  4477. });
  4478. }
  4479. }
  4480. return stats;
  4481. })
  4482. .then(onSucc, onErr);
  4483. };
  4484. }
  4485. function shimSenderGetStats(window) {
  4486. if (!(typeof window === 'object' && window.RTCPeerConnection &&
  4487. window.RTCRtpSender)) {
  4488. return;
  4489. }
  4490. if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) {
  4491. return;
  4492. }
  4493. const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  4494. if (origGetSenders) {
  4495. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  4496. const senders = origGetSenders.apply(this, []);
  4497. senders.forEach(sender => sender._pc = this);
  4498. return senders;
  4499. };
  4500. }
  4501. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  4502. if (origAddTrack) {
  4503. window.RTCPeerConnection.prototype.addTrack = function addTrack() {
  4504. const sender = origAddTrack.apply(this, arguments);
  4505. sender._pc = this;
  4506. return sender;
  4507. };
  4508. }
  4509. window.RTCRtpSender.prototype.getStats = function getStats() {
  4510. return this.track ? this._pc.getStats(this.track) :
  4511. Promise.resolve(new Map());
  4512. };
  4513. }
  4514. function shimReceiverGetStats(window) {
  4515. if (!(typeof window === 'object' && window.RTCPeerConnection &&
  4516. window.RTCRtpSender)) {
  4517. return;
  4518. }
  4519. if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) {
  4520. return;
  4521. }
  4522. const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
  4523. if (origGetReceivers) {
  4524. window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
  4525. const receivers = origGetReceivers.apply(this, []);
  4526. receivers.forEach(receiver => receiver._pc = this);
  4527. return receivers;
  4528. };
  4529. }
  4530. wrapPeerConnectionEvent(window, 'track', e => {
  4531. e.receiver._pc = e.srcElement;
  4532. return e;
  4533. });
  4534. window.RTCRtpReceiver.prototype.getStats = function getStats() {
  4535. return this._pc.getStats(this.track);
  4536. };
  4537. }
  4538. function shimRemoveStream(window) {
  4539. if (!window.RTCPeerConnection ||
  4540. 'removeStream' in window.RTCPeerConnection.prototype) {
  4541. return;
  4542. }
  4543. window.RTCPeerConnection.prototype.removeStream =
  4544. function removeStream(stream) {
  4545. deprecated('removeStream', 'removeTrack');
  4546. this.getSenders().forEach(sender => {
  4547. if (sender.track && stream.getTracks().includes(sender.track)) {
  4548. this.removeTrack(sender);
  4549. }
  4550. });
  4551. };
  4552. }
  4553. function shimRTCDataChannel(window) {
  4554. // rename DataChannel to RTCDataChannel (native fix in FF60):
  4555. // https://bugzilla.mozilla.org/show_bug.cgi?id=1173851
  4556. if (window.DataChannel && !window.RTCDataChannel) {
  4557. window.RTCDataChannel = window.DataChannel;
  4558. }
  4559. }
  4560. function shimAddTransceiver(window) {
  4561. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  4562. // Firefox ignores the init sendEncodings options passed to addTransceiver
  4563. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  4564. if (!(typeof window === 'object' && window.RTCPeerConnection)) {
  4565. return;
  4566. }
  4567. const origAddTransceiver = window.RTCPeerConnection.prototype.addTransceiver;
  4568. if (origAddTransceiver) {
  4569. window.RTCPeerConnection.prototype.addTransceiver =
  4570. function addTransceiver() {
  4571. this.setParametersPromises = [];
  4572. const initParameters = arguments[1];
  4573. const shouldPerformCheck = initParameters &&
  4574. 'sendEncodings' in initParameters;
  4575. if (shouldPerformCheck) {
  4576. // If sendEncodings params are provided, validate grammar
  4577. initParameters.sendEncodings.forEach((encodingParam) => {
  4578. if ('rid' in encodingParam) {
  4579. const ridRegex = /^[a-z0-9]{0,16}$/i;
  4580. if (!ridRegex.test(encodingParam.rid)) {
  4581. throw new TypeError('Invalid RID value provided.');
  4582. }
  4583. }
  4584. if ('scaleResolutionDownBy' in encodingParam) {
  4585. if (!(parseFloat(encodingParam.scaleResolutionDownBy) >= 1.0)) {
  4586. throw new RangeError('scale_resolution_down_by must be >= 1.0');
  4587. }
  4588. }
  4589. if ('maxFramerate' in encodingParam) {
  4590. if (!(parseFloat(encodingParam.maxFramerate) >= 0)) {
  4591. throw new RangeError('max_framerate must be >= 0.0');
  4592. }
  4593. }
  4594. });
  4595. }
  4596. const transceiver = origAddTransceiver.apply(this, arguments);
  4597. if (shouldPerformCheck) {
  4598. // Check if the init options were applied. If not we do this in an
  4599. // asynchronous way and save the promise reference in a global object.
  4600. // This is an ugly hack, but at the same time is way more robust than
  4601. // checking the sender parameters before and after the createOffer
  4602. // Also note that after the createoffer we are not 100% sure that
  4603. // the params were asynchronously applied so we might miss the
  4604. // opportunity to recreate offer.
  4605. const {
  4606. sender
  4607. } = transceiver;
  4608. const params = sender.getParameters();
  4609. if (!('encodings' in params) ||
  4610. // Avoid being fooled by patched getParameters() below.
  4611. (params.encodings.length === 1 &&
  4612. Object.keys(params.encodings[0]).length === 0)) {
  4613. params.encodings = initParameters.sendEncodings;
  4614. sender.sendEncodings = initParameters.sendEncodings;
  4615. this.setParametersPromises.push(sender.setParameters(params)
  4616. .then(() => {
  4617. delete sender.sendEncodings;
  4618. }).catch(() => {
  4619. delete sender.sendEncodings;
  4620. })
  4621. );
  4622. }
  4623. }
  4624. return transceiver;
  4625. };
  4626. }
  4627. }
  4628. function shimGetParameters(window) {
  4629. if (!(typeof window === 'object' && window.RTCRtpSender)) {
  4630. return;
  4631. }
  4632. const origGetParameters = window.RTCRtpSender.prototype.getParameters;
  4633. if (origGetParameters) {
  4634. window.RTCRtpSender.prototype.getParameters =
  4635. function getParameters() {
  4636. const params = origGetParameters.apply(this, arguments);
  4637. if (!('encodings' in params)) {
  4638. params.encodings = [].concat(this.sendEncodings || [{}]);
  4639. }
  4640. return params;
  4641. };
  4642. }
  4643. }
  4644. function shimCreateOffer(window) {
  4645. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  4646. // Firefox ignores the init sendEncodings options passed to addTransceiver
  4647. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  4648. if (!(typeof window === 'object' && window.RTCPeerConnection)) {
  4649. return;
  4650. }
  4651. const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  4652. window.RTCPeerConnection.prototype.createOffer = function createOffer() {
  4653. if (this.setParametersPromises && this.setParametersPromises.length) {
  4654. return Promise.all(this.setParametersPromises)
  4655. .then(() => {
  4656. return origCreateOffer.apply(this, arguments);
  4657. })
  4658. .finally(() => {
  4659. this.setParametersPromises = [];
  4660. });
  4661. }
  4662. return origCreateOffer.apply(this, arguments);
  4663. };
  4664. }
  4665. function shimCreateAnswer(window) {
  4666. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  4667. // Firefox ignores the init sendEncodings options passed to addTransceiver
  4668. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  4669. if (!(typeof window === 'object' && window.RTCPeerConnection)) {
  4670. return;
  4671. }
  4672. const origCreateAnswer = window.RTCPeerConnection.prototype.createAnswer;
  4673. window.RTCPeerConnection.prototype.createAnswer = function createAnswer() {
  4674. if (this.setParametersPromises && this.setParametersPromises.length) {
  4675. return Promise.all(this.setParametersPromises)
  4676. .then(() => {
  4677. return origCreateAnswer.apply(this, arguments);
  4678. })
  4679. .finally(() => {
  4680. this.setParametersPromises = [];
  4681. });
  4682. }
  4683. return origCreateAnswer.apply(this, arguments);
  4684. };
  4685. }
  4686. var firefoxShim = /*#__PURE__*/ Object.freeze({
  4687. __proto__: null,
  4688. shimOnTrack: shimOnTrack,
  4689. shimPeerConnection: shimPeerConnection,
  4690. shimSenderGetStats: shimSenderGetStats,
  4691. shimReceiverGetStats: shimReceiverGetStats,
  4692. shimRemoveStream: shimRemoveStream,
  4693. shimRTCDataChannel: shimRTCDataChannel,
  4694. shimAddTransceiver: shimAddTransceiver,
  4695. shimGetParameters: shimGetParameters,
  4696. shimCreateOffer: shimCreateOffer,
  4697. shimCreateAnswer: shimCreateAnswer,
  4698. shimGetUserMedia: shimGetUserMedia$1,
  4699. shimGetDisplayMedia: shimGetDisplayMedia
  4700. });
  4701. /*
  4702. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4703. *
  4704. * Use of this source code is governed by a BSD-style license
  4705. * that can be found in the LICENSE file in the root of the source
  4706. * tree.
  4707. */
  4708. function shimLocalStreamsAPI(window) {
  4709. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4710. return;
  4711. }
  4712. if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
  4713. window.RTCPeerConnection.prototype.getLocalStreams =
  4714. function getLocalStreams() {
  4715. if (!this._localStreams) {
  4716. this._localStreams = [];
  4717. }
  4718. return this._localStreams;
  4719. };
  4720. }
  4721. if (!('addStream' in window.RTCPeerConnection.prototype)) {
  4722. const _addTrack = window.RTCPeerConnection.prototype.addTrack;
  4723. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  4724. if (!this._localStreams) {
  4725. this._localStreams = [];
  4726. }
  4727. if (!this._localStreams.includes(stream)) {
  4728. this._localStreams.push(stream);
  4729. }
  4730. // Try to emulate Chrome's behaviour of adding in audio-video order.
  4731. // Safari orders by track id.
  4732. stream.getAudioTracks().forEach(track => _addTrack.call(this, track,
  4733. stream));
  4734. stream.getVideoTracks().forEach(track => _addTrack.call(this, track,
  4735. stream));
  4736. };
  4737. window.RTCPeerConnection.prototype.addTrack =
  4738. function addTrack(track, ...streams) {
  4739. if (streams) {
  4740. streams.forEach((stream) => {
  4741. if (!this._localStreams) {
  4742. this._localStreams = [stream];
  4743. } else if (!this._localStreams.includes(stream)) {
  4744. this._localStreams.push(stream);
  4745. }
  4746. });
  4747. }
  4748. return _addTrack.apply(this, arguments);
  4749. };
  4750. }
  4751. if (!('removeStream' in window.RTCPeerConnection.prototype)) {
  4752. window.RTCPeerConnection.prototype.removeStream =
  4753. function removeStream(stream) {
  4754. if (!this._localStreams) {
  4755. this._localStreams = [];
  4756. }
  4757. const index = this._localStreams.indexOf(stream);
  4758. if (index === -1) {
  4759. return;
  4760. }
  4761. this._localStreams.splice(index, 1);
  4762. const tracks = stream.getTracks();
  4763. this.getSenders().forEach(sender => {
  4764. if (tracks.includes(sender.track)) {
  4765. this.removeTrack(sender);
  4766. }
  4767. });
  4768. };
  4769. }
  4770. }
  4771. function shimRemoteStreamsAPI(window) {
  4772. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4773. return;
  4774. }
  4775. if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
  4776. window.RTCPeerConnection.prototype.getRemoteStreams =
  4777. function getRemoteStreams() {
  4778. return this._remoteStreams ? this._remoteStreams : [];
  4779. };
  4780. }
  4781. if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
  4782. Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
  4783. get() {
  4784. return this._onaddstream;
  4785. },
  4786. set(f) {
  4787. if (this._onaddstream) {
  4788. this.removeEventListener('addstream', this._onaddstream);
  4789. this.removeEventListener('track', this._onaddstreampoly);
  4790. }
  4791. this.addEventListener('addstream', this._onaddstream = f);
  4792. this.addEventListener('track', this._onaddstreampoly = (e) => {
  4793. e.streams.forEach(stream => {
  4794. if (!this._remoteStreams) {
  4795. this._remoteStreams = [];
  4796. }
  4797. if (this._remoteStreams.includes(stream)) {
  4798. return;
  4799. }
  4800. this._remoteStreams.push(stream);
  4801. const event = new Event('addstream');
  4802. event.stream = stream;
  4803. this.dispatchEvent(event);
  4804. });
  4805. });
  4806. }
  4807. });
  4808. const origSetRemoteDescription =
  4809. window.RTCPeerConnection.prototype.setRemoteDescription;
  4810. window.RTCPeerConnection.prototype.setRemoteDescription =
  4811. function setRemoteDescription() {
  4812. const pc = this;
  4813. if (!this._onaddstreampoly) {
  4814. this.addEventListener('track', this._onaddstreampoly = function(e) {
  4815. e.streams.forEach(stream => {
  4816. if (!pc._remoteStreams) {
  4817. pc._remoteStreams = [];
  4818. }
  4819. if (pc._remoteStreams.indexOf(stream) >= 0) {
  4820. return;
  4821. }
  4822. pc._remoteStreams.push(stream);
  4823. const event = new Event('addstream');
  4824. event.stream = stream;
  4825. pc.dispatchEvent(event);
  4826. });
  4827. });
  4828. }
  4829. return origSetRemoteDescription.apply(pc, arguments);
  4830. };
  4831. }
  4832. }
  4833. function shimCallbacksAPI(window) {
  4834. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4835. return;
  4836. }
  4837. const prototype = window.RTCPeerConnection.prototype;
  4838. const origCreateOffer = prototype.createOffer;
  4839. const origCreateAnswer = prototype.createAnswer;
  4840. const setLocalDescription = prototype.setLocalDescription;
  4841. const setRemoteDescription = prototype.setRemoteDescription;
  4842. const addIceCandidate = prototype.addIceCandidate;
  4843. prototype.createOffer =
  4844. function createOffer(successCallback, failureCallback) {
  4845. const options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  4846. const promise = origCreateOffer.apply(this, [options]);
  4847. if (!failureCallback) {
  4848. return promise;
  4849. }
  4850. promise.then(successCallback, failureCallback);
  4851. return Promise.resolve();
  4852. };
  4853. prototype.createAnswer =
  4854. function createAnswer(successCallback, failureCallback) {
  4855. const options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  4856. const promise = origCreateAnswer.apply(this, [options]);
  4857. if (!failureCallback) {
  4858. return promise;
  4859. }
  4860. promise.then(successCallback, failureCallback);
  4861. return Promise.resolve();
  4862. };
  4863. let withCallback = function(description, successCallback, failureCallback) {
  4864. const promise = setLocalDescription.apply(this, [description]);
  4865. if (!failureCallback) {
  4866. return promise;
  4867. }
  4868. promise.then(successCallback, failureCallback);
  4869. return Promise.resolve();
  4870. };
  4871. prototype.setLocalDescription = withCallback;
  4872. withCallback = function(description, successCallback, failureCallback) {
  4873. const promise = setRemoteDescription.apply(this, [description]);
  4874. if (!failureCallback) {
  4875. return promise;
  4876. }
  4877. promise.then(successCallback, failureCallback);
  4878. return Promise.resolve();
  4879. };
  4880. prototype.setRemoteDescription = withCallback;
  4881. withCallback = function(candidate, successCallback, failureCallback) {
  4882. const promise = addIceCandidate.apply(this, [candidate]);
  4883. if (!failureCallback) {
  4884. return promise;
  4885. }
  4886. promise.then(successCallback, failureCallback);
  4887. return Promise.resolve();
  4888. };
  4889. prototype.addIceCandidate = withCallback;
  4890. }
  4891. function shimGetUserMedia(window) {
  4892. const navigator = window && window.navigator;
  4893. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  4894. // shim not needed in Safari 12.1
  4895. const mediaDevices = navigator.mediaDevices;
  4896. const _getUserMedia = mediaDevices.getUserMedia.bind(mediaDevices);
  4897. navigator.mediaDevices.getUserMedia = (constraints) => {
  4898. return _getUserMedia(shimConstraints(constraints));
  4899. };
  4900. }
  4901. if (!navigator.getUserMedia && navigator.mediaDevices &&
  4902. navigator.mediaDevices.getUserMedia) {
  4903. navigator.getUserMedia = function getUserMedia(constraints, cb, errcb) {
  4904. navigator.mediaDevices.getUserMedia(constraints)
  4905. .then(cb, errcb);
  4906. }.bind(navigator);
  4907. }
  4908. }
  4909. function shimConstraints(constraints) {
  4910. if (constraints && constraints.video !== undefined) {
  4911. return Object.assign({},
  4912. constraints, {
  4913. video: compactObject(constraints.video)
  4914. }
  4915. );
  4916. }
  4917. return constraints;
  4918. }
  4919. function shimRTCIceServerUrls(window) {
  4920. if (!window.RTCPeerConnection) {
  4921. return;
  4922. }
  4923. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  4924. const OrigPeerConnection = window.RTCPeerConnection;
  4925. window.RTCPeerConnection =
  4926. function RTCPeerConnection(pcConfig, pcConstraints) {
  4927. if (pcConfig && pcConfig.iceServers) {
  4928. const newIceServers = [];
  4929. for (let i = 0; i < pcConfig.iceServers.length; i++) {
  4930. let server = pcConfig.iceServers[i];
  4931. if (!server.hasOwnProperty('urls') &&
  4932. server.hasOwnProperty('url')) {
  4933. deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  4934. server = JSON.parse(JSON.stringify(server));
  4935. server.urls = server.url;
  4936. delete server.url;
  4937. newIceServers.push(server);
  4938. } else {
  4939. newIceServers.push(pcConfig.iceServers[i]);
  4940. }
  4941. }
  4942. pcConfig.iceServers = newIceServers;
  4943. }
  4944. return new OrigPeerConnection(pcConfig, pcConstraints);
  4945. };
  4946. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  4947. // wrap static methods. Currently just generateCertificate.
  4948. if ('generateCertificate' in OrigPeerConnection) {
  4949. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  4950. get() {
  4951. return OrigPeerConnection.generateCertificate;
  4952. }
  4953. });
  4954. }
  4955. }
  4956. function shimTrackEventTransceiver(window) {
  4957. // Add event.transceiver member over deprecated event.receiver
  4958. if (typeof window === 'object' && window.RTCTrackEvent &&
  4959. 'receiver' in window.RTCTrackEvent.prototype &&
  4960. !('transceiver' in window.RTCTrackEvent.prototype)) {
  4961. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  4962. get() {
  4963. return {
  4964. receiver: this.receiver
  4965. };
  4966. }
  4967. });
  4968. }
  4969. }
  4970. function shimCreateOfferLegacy(window) {
  4971. const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  4972. window.RTCPeerConnection.prototype.createOffer =
  4973. function createOffer(offerOptions) {
  4974. if (offerOptions) {
  4975. if (typeof offerOptions.offerToReceiveAudio !== 'undefined') {
  4976. // support bit values
  4977. offerOptions.offerToReceiveAudio = !!offerOptions.offerToReceiveAudio;
  4978. }
  4979. const audioTransceiver = this.getTransceivers().find(transceiver =>
  4980. transceiver.receiver.track.kind === 'audio');
  4981. if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {
  4982. if (audioTransceiver.direction === 'sendrecv') {
  4983. if (audioTransceiver.setDirection) {
  4984. audioTransceiver.setDirection('sendonly');
  4985. } else {
  4986. audioTransceiver.direction = 'sendonly';
  4987. }
  4988. } else if (audioTransceiver.direction === 'recvonly') {
  4989. if (audioTransceiver.setDirection) {
  4990. audioTransceiver.setDirection('inactive');
  4991. } else {
  4992. audioTransceiver.direction = 'inactive';
  4993. }
  4994. }
  4995. } else if (offerOptions.offerToReceiveAudio === true &&
  4996. !audioTransceiver) {
  4997. this.addTransceiver('audio');
  4998. }
  4999. if (typeof offerOptions.offerToReceiveVideo !== 'undefined') {
  5000. // support bit values
  5001. offerOptions.offerToReceiveVideo = !!offerOptions.offerToReceiveVideo;
  5002. }
  5003. const videoTransceiver = this.getTransceivers().find(transceiver =>
  5004. transceiver.receiver.track.kind === 'video');
  5005. if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {
  5006. if (videoTransceiver.direction === 'sendrecv') {
  5007. if (videoTransceiver.setDirection) {
  5008. videoTransceiver.setDirection('sendonly');
  5009. } else {
  5010. videoTransceiver.direction = 'sendonly';
  5011. }
  5012. } else if (videoTransceiver.direction === 'recvonly') {
  5013. if (videoTransceiver.setDirection) {
  5014. videoTransceiver.setDirection('inactive');
  5015. } else {
  5016. videoTransceiver.direction = 'inactive';
  5017. }
  5018. }
  5019. } else if (offerOptions.offerToReceiveVideo === true &&
  5020. !videoTransceiver) {
  5021. this.addTransceiver('video');
  5022. }
  5023. }
  5024. return origCreateOffer.apply(this, arguments);
  5025. };
  5026. }
  5027. function shimAudioContext(window) {
  5028. if (typeof window !== 'object' || window.AudioContext) {
  5029. return;
  5030. }
  5031. window.AudioContext = window.webkitAudioContext;
  5032. }
  5033. var safariShim = /*#__PURE__*/ Object.freeze({
  5034. __proto__: null,
  5035. shimLocalStreamsAPI: shimLocalStreamsAPI,
  5036. shimRemoteStreamsAPI: shimRemoteStreamsAPI,
  5037. shimCallbacksAPI: shimCallbacksAPI,
  5038. shimGetUserMedia: shimGetUserMedia,
  5039. shimConstraints: shimConstraints,
  5040. shimRTCIceServerUrls: shimRTCIceServerUrls,
  5041. shimTrackEventTransceiver: shimTrackEventTransceiver,
  5042. shimCreateOfferLegacy: shimCreateOfferLegacy,
  5043. shimAudioContext: shimAudioContext
  5044. });
  5045. /*
  5046. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  5047. *
  5048. * Use of this source code is governed by a BSD-style license
  5049. * that can be found in the LICENSE file in the root of the source
  5050. * tree.
  5051. */
  5052. function shimRTCIceCandidate(window) {
  5053. // foundation is arbitrarily chosen as an indicator for full support for
  5054. // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
  5055. if (!window.RTCIceCandidate || (window.RTCIceCandidate && 'foundation' in
  5056. window.RTCIceCandidate.prototype)) {
  5057. return;
  5058. }
  5059. const NativeRTCIceCandidate = window.RTCIceCandidate;
  5060. window.RTCIceCandidate = function RTCIceCandidate(args) {
  5061. // Remove the a= which shouldn't be part of the candidate string.
  5062. if (typeof args === 'object' && args.candidate &&
  5063. args.candidate.indexOf('a=') === 0) {
  5064. args = JSON.parse(JSON.stringify(args));
  5065. args.candidate = args.candidate.substr(2);
  5066. }
  5067. if (args.candidate && args.candidate.length) {
  5068. // Augment the native candidate with the parsed fields.
  5069. const nativeCandidate = new NativeRTCIceCandidate(args);
  5070. const parsedCandidate = sdp.parseCandidate(args.candidate);
  5071. const augmentedCandidate = Object.assign(nativeCandidate,
  5072. parsedCandidate);
  5073. // Add a serializer that does not serialize the extra attributes.
  5074. augmentedCandidate.toJSON = function toJSON() {
  5075. return {
  5076. candidate: augmentedCandidate.candidate,
  5077. sdpMid: augmentedCandidate.sdpMid,
  5078. sdpMLineIndex: augmentedCandidate.sdpMLineIndex,
  5079. usernameFragment: augmentedCandidate.usernameFragment,
  5080. };
  5081. };
  5082. return augmentedCandidate;
  5083. }
  5084. return new NativeRTCIceCandidate(args);
  5085. };
  5086. window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;
  5087. // Hook up the augmented candidate in onicecandidate and
  5088. // addEventListener('icecandidate', ...)
  5089. wrapPeerConnectionEvent(window, 'icecandidate', e => {
  5090. if (e.candidate) {
  5091. Object.defineProperty(e, 'candidate', {
  5092. value: new window.RTCIceCandidate(e.candidate),
  5093. writable: 'false'
  5094. });
  5095. }
  5096. return e;
  5097. });
  5098. }
  5099. function shimMaxMessageSize(window, browserDetails) {
  5100. if (!window.RTCPeerConnection) {
  5101. return;
  5102. }
  5103. if (!('sctp' in window.RTCPeerConnection.prototype)) {
  5104. Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {
  5105. get() {
  5106. return typeof this._sctp === 'undefined' ? null : this._sctp;
  5107. }
  5108. });
  5109. }
  5110. const sctpInDescription = function(description) {
  5111. if (!description || !description.sdp) {
  5112. return false;
  5113. }
  5114. const sections = sdp.splitSections(description.sdp);
  5115. sections.shift();
  5116. return sections.some(mediaSection => {
  5117. const mLine = sdp.parseMLine(mediaSection);
  5118. return mLine && mLine.kind === 'application' &&
  5119. mLine.protocol.indexOf('SCTP') !== -1;
  5120. });
  5121. };
  5122. const getRemoteFirefoxVersion = function(description) {
  5123. // TODO: Is there a better solution for detecting Firefox?
  5124. const match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
  5125. if (match === null || match.length < 2) {
  5126. return -1;
  5127. }
  5128. const version = parseInt(match[1], 10);
  5129. // Test for NaN (yes, this is ugly)
  5130. return version !== version ? -1 : version;
  5131. };
  5132. const getCanSendMaxMessageSize = function(remoteIsFirefox) {
  5133. // Every implementation we know can send at least 64 KiB.
  5134. // Note: Although Chrome is technically able to send up to 256 KiB, the
  5135. // data does not reach the other peer reliably.
  5136. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419
  5137. let canSendMaxMessageSize = 65536;
  5138. if (browserDetails.browser === 'firefox') {
  5139. if (browserDetails.version < 57) {
  5140. if (remoteIsFirefox === -1) {
  5141. // FF < 57 will send in 16 KiB chunks using the deprecated PPID
  5142. // fragmentation.
  5143. canSendMaxMessageSize = 16384;
  5144. } else {
  5145. // However, other FF (and RAWRTC) can reassemble PPID-fragmented
  5146. // messages. Thus, supporting ~2 GiB when sending.
  5147. canSendMaxMessageSize = 2147483637;
  5148. }
  5149. } else if (browserDetails.version < 60) {
  5150. // Currently, all FF >= 57 will reset the remote maximum message size
  5151. // to the default value when a data channel is created at a later
  5152. // stage. :(
  5153. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  5154. canSendMaxMessageSize =
  5155. browserDetails.version === 57 ? 65535 : 65536;
  5156. } else {
  5157. // FF >= 60 supports sending ~2 GiB
  5158. canSendMaxMessageSize = 2147483637;
  5159. }
  5160. }
  5161. return canSendMaxMessageSize;
  5162. };
  5163. const getMaxMessageSize = function(description, remoteIsFirefox) {
  5164. // Note: 65536 bytes is the default value from the SDP spec. Also,
  5165. // every implementation we know supports receiving 65536 bytes.
  5166. let maxMessageSize = 65536;
  5167. // FF 57 has a slightly incorrect default remote max message size, so
  5168. // we need to adjust it here to avoid a failure when sending.
  5169. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697
  5170. if (browserDetails.browser === 'firefox' &&
  5171. browserDetails.version === 57) {
  5172. maxMessageSize = 65535;
  5173. }
  5174. const match = sdp.matchPrefix(description.sdp,
  5175. 'a=max-message-size:');
  5176. if (match.length > 0) {
  5177. maxMessageSize = parseInt(match[0].substr(19), 10);
  5178. } else if (browserDetails.browser === 'firefox' &&
  5179. remoteIsFirefox !== -1) {
  5180. // If the maximum message size is not present in the remote SDP and
  5181. // both local and remote are Firefox, the remote peer can receive
  5182. // ~2 GiB.
  5183. maxMessageSize = 2147483637;
  5184. }
  5185. return maxMessageSize;
  5186. };
  5187. const origSetRemoteDescription =
  5188. window.RTCPeerConnection.prototype.setRemoteDescription;
  5189. window.RTCPeerConnection.prototype.setRemoteDescription =
  5190. function setRemoteDescription() {
  5191. this._sctp = null;
  5192. // Chrome decided to not expose .sctp in plan-b mode.
  5193. // As usual, adapter.js has to do an 'ugly worakaround'
  5194. // to cover up the mess.
  5195. if (browserDetails.browser === 'chrome' && browserDetails.version >= 76) {
  5196. const {
  5197. sdpSemantics
  5198. } = this.getConfiguration();
  5199. if (sdpSemantics === 'plan-b') {
  5200. Object.defineProperty(this, 'sctp', {
  5201. get() {
  5202. return typeof this._sctp === 'undefined' ? null : this._sctp;
  5203. },
  5204. enumerable: true,
  5205. configurable: true,
  5206. });
  5207. }
  5208. }
  5209. if (sctpInDescription(arguments[0])) {
  5210. // Check if the remote is FF.
  5211. const isFirefox = getRemoteFirefoxVersion(arguments[0]);
  5212. // Get the maximum message size the local peer is capable of sending
  5213. const canSendMMS = getCanSendMaxMessageSize(isFirefox);
  5214. // Get the maximum message size of the remote peer.
  5215. const remoteMMS = getMaxMessageSize(arguments[0], isFirefox);
  5216. // Determine final maximum message size
  5217. let maxMessageSize;
  5218. if (canSendMMS === 0 && remoteMMS === 0) {
  5219. maxMessageSize = Number.POSITIVE_INFINITY;
  5220. } else if (canSendMMS === 0 || remoteMMS === 0) {
  5221. maxMessageSize = Math.max(canSendMMS, remoteMMS);
  5222. } else {
  5223. maxMessageSize = Math.min(canSendMMS, remoteMMS);
  5224. }
  5225. // Create a dummy RTCSctpTransport object and the 'maxMessageSize'
  5226. // attribute.
  5227. const sctp = {};
  5228. Object.defineProperty(sctp, 'maxMessageSize', {
  5229. get() {
  5230. return maxMessageSize;
  5231. }
  5232. });
  5233. this._sctp = sctp;
  5234. }
  5235. return origSetRemoteDescription.apply(this, arguments);
  5236. };
  5237. }
  5238. function shimSendThrowTypeError(window) {
  5239. if (!(window.RTCPeerConnection &&
  5240. 'createDataChannel' in window.RTCPeerConnection.prototype)) {
  5241. return;
  5242. }
  5243. // Note: Although Firefox >= 57 has a native implementation, the maximum
  5244. // message size can be reset for all data channels at a later stage.
  5245. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  5246. function wrapDcSend(dc, pc) {
  5247. const origDataChannelSend = dc.send;
  5248. dc.send = function send() {
  5249. const data = arguments[0];
  5250. const length = data.length || data.size || data.byteLength;
  5251. if (dc.readyState === 'open' &&
  5252. pc.sctp && length > pc.sctp.maxMessageSize) {
  5253. throw new TypeError('Message too large (can send a maximum of ' +
  5254. pc.sctp.maxMessageSize + ' bytes)');
  5255. }
  5256. return origDataChannelSend.apply(dc, arguments);
  5257. };
  5258. }
  5259. const origCreateDataChannel =
  5260. window.RTCPeerConnection.prototype.createDataChannel;
  5261. window.RTCPeerConnection.prototype.createDataChannel =
  5262. function createDataChannel() {
  5263. const dataChannel = origCreateDataChannel.apply(this, arguments);
  5264. wrapDcSend(dataChannel, this);
  5265. return dataChannel;
  5266. };
  5267. wrapPeerConnectionEvent(window, 'datachannel', e => {
  5268. wrapDcSend(e.channel, e.target);
  5269. return e;
  5270. });
  5271. }
  5272. /* shims RTCConnectionState by pretending it is the same as iceConnectionState.
  5273. * See https://bugs.chromium.org/p/webrtc/issues/detail?id=6145#c12
  5274. * for why this is a valid hack in Chrome. In Firefox it is slightly incorrect
  5275. * since DTLS failures would be hidden. See
  5276. * https://bugzilla.mozilla.org/show_bug.cgi?id=1265827
  5277. * for the Firefox tracking bug.
  5278. */
  5279. function shimConnectionState(window) {
  5280. if (!window.RTCPeerConnection ||
  5281. 'connectionState' in window.RTCPeerConnection.prototype) {
  5282. return;
  5283. }
  5284. const proto = window.RTCPeerConnection.prototype;
  5285. Object.defineProperty(proto, 'connectionState', {
  5286. get() {
  5287. return {
  5288. completed: 'connected',
  5289. checking: 'connecting'
  5290. } [this.iceConnectionState] || this.iceConnectionState;
  5291. },
  5292. enumerable: true,
  5293. configurable: true
  5294. });
  5295. Object.defineProperty(proto, 'onconnectionstatechange', {
  5296. get() {
  5297. return this._onconnectionstatechange || null;
  5298. },
  5299. set(cb) {
  5300. if (this._onconnectionstatechange) {
  5301. this.removeEventListener('connectionstatechange',
  5302. this._onconnectionstatechange);
  5303. delete this._onconnectionstatechange;
  5304. }
  5305. if (cb) {
  5306. this.addEventListener('connectionstatechange',
  5307. this._onconnectionstatechange = cb);
  5308. }
  5309. },
  5310. enumerable: true,
  5311. configurable: true
  5312. });
  5313. ['setLocalDescription', 'setRemoteDescription'].forEach((method) => {
  5314. const origMethod = proto[method];
  5315. proto[method] = function() {
  5316. if (!this._connectionstatechangepoly) {
  5317. this._connectionstatechangepoly = e => {
  5318. const pc = e.target;
  5319. if (pc._lastConnectionState !== pc.connectionState) {
  5320. pc._lastConnectionState = pc.connectionState;
  5321. const newEvent = new Event('connectionstatechange', e);
  5322. pc.dispatchEvent(newEvent);
  5323. }
  5324. return e;
  5325. };
  5326. this.addEventListener('iceconnectionstatechange',
  5327. this._connectionstatechangepoly);
  5328. }
  5329. return origMethod.apply(this, arguments);
  5330. };
  5331. });
  5332. }
  5333. function removeExtmapAllowMixed(window, browserDetails) {
  5334. /* remove a=extmap-allow-mixed for webrtc.org < M71 */
  5335. if (!window.RTCPeerConnection) {
  5336. return;
  5337. }
  5338. if (browserDetails.browser === 'chrome' && browserDetails.version >= 71) {
  5339. return;
  5340. }
  5341. if (browserDetails.browser === 'safari' && browserDetails.version >= 605) {
  5342. return;
  5343. }
  5344. const nativeSRD = window.RTCPeerConnection.prototype.setRemoteDescription;
  5345. window.RTCPeerConnection.prototype.setRemoteDescription =
  5346. function setRemoteDescription(desc) {
  5347. if (desc && desc.sdp && desc.sdp.indexOf('\na=extmap-allow-mixed') !== -1) {
  5348. const sdp = desc.sdp.split('\n').filter((line) => {
  5349. return line.trim() !== 'a=extmap-allow-mixed';
  5350. }).join('\n');
  5351. // Safari enforces read-only-ness of RTCSessionDescription fields.
  5352. if (window.RTCSessionDescription &&
  5353. desc instanceof window.RTCSessionDescription) {
  5354. arguments[0] = new window.RTCSessionDescription({
  5355. type: desc.type,
  5356. sdp,
  5357. });
  5358. } else {
  5359. desc.sdp = sdp;
  5360. }
  5361. }
  5362. return nativeSRD.apply(this, arguments);
  5363. };
  5364. }
  5365. function shimAddIceCandidateNullOrEmpty(window, browserDetails) {
  5366. // Support for addIceCandidate(null or undefined)
  5367. // as well as addIceCandidate({candidate: "", ...})
  5368. // https://bugs.chromium.org/p/chromium/issues/detail?id=978582
  5369. // Note: must be called before other polyfills which change the signature.
  5370. if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {
  5371. return;
  5372. }
  5373. const nativeAddIceCandidate =
  5374. window.RTCPeerConnection.prototype.addIceCandidate;
  5375. if (!nativeAddIceCandidate || nativeAddIceCandidate.length === 0) {
  5376. return;
  5377. }
  5378. window.RTCPeerConnection.prototype.addIceCandidate =
  5379. function addIceCandidate() {
  5380. if (!arguments[0]) {
  5381. if (arguments[1]) {
  5382. arguments[1].apply(null);
  5383. }
  5384. return Promise.resolve();
  5385. }
  5386. // Firefox 68+ emits and processes {candidate: "", ...}, ignore
  5387. // in older versions.
  5388. // Native support for ignoring exists for Chrome M77+.
  5389. // Safari ignores as well, exact version unknown but works in the same
  5390. // version that also ignores addIceCandidate(null).
  5391. if (((browserDetails.browser === 'chrome' && browserDetails.version < 78) ||
  5392. (browserDetails.browser === 'firefox' &&
  5393. browserDetails.version < 68) ||
  5394. (browserDetails.browser === 'safari')) &&
  5395. arguments[0] && arguments[0].candidate === '') {
  5396. return Promise.resolve();
  5397. }
  5398. return nativeAddIceCandidate.apply(this, arguments);
  5399. };
  5400. }
  5401. var commonShim = /*#__PURE__*/ Object.freeze({
  5402. __proto__: null,
  5403. shimRTCIceCandidate: shimRTCIceCandidate,
  5404. shimMaxMessageSize: shimMaxMessageSize,
  5405. shimSendThrowTypeError: shimSendThrowTypeError,
  5406. shimConnectionState: shimConnectionState,
  5407. removeExtmapAllowMixed: removeExtmapAllowMixed,
  5408. shimAddIceCandidateNullOrEmpty: shimAddIceCandidateNullOrEmpty
  5409. });
  5410. /*
  5411. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  5412. *
  5413. * Use of this source code is governed by a BSD-style license
  5414. * that can be found in the LICENSE file in the root of the source
  5415. * tree.
  5416. */
  5417. // Shimming starts here.
  5418. function adapterFactory({
  5419. window
  5420. } = {}, options = {
  5421. shimChrome: true,
  5422. shimFirefox: true,
  5423. shimEdge: true,
  5424. shimSafari: true,
  5425. }) {
  5426. // Utils.
  5427. const logging = log$1;
  5428. const browserDetails = detectBrowser(window);
  5429. const adapter = {
  5430. browserDetails,
  5431. commonShim,
  5432. extractVersion: extractVersion,
  5433. disableLog: disableLog,
  5434. disableWarnings: disableWarnings
  5435. };
  5436. // Shim browser if found.
  5437. switch (browserDetails.browser) {
  5438. case 'chrome':
  5439. if (!chromeShim || !shimPeerConnection$2 ||
  5440. !options.shimChrome) {
  5441. logging('Chrome shim is not included in this adapter release.');
  5442. return adapter;
  5443. }
  5444. if (browserDetails.version === null) {
  5445. logging('Chrome shim can not determine version, not shimming.');
  5446. return adapter;
  5447. }
  5448. logging('adapter.js shimming chrome.');
  5449. // Export to the adapter global object visible in the browser.
  5450. adapter.browserShim = chromeShim;
  5451. // Must be called before shimPeerConnection.
  5452. shimAddIceCandidateNullOrEmpty(window, browserDetails);
  5453. shimGetUserMedia$3(window, browserDetails);
  5454. shimMediaStream(window);
  5455. shimPeerConnection$2(window, browserDetails);
  5456. shimOnTrack$1(window);
  5457. shimAddTrackRemoveTrack(window, browserDetails);
  5458. shimGetSendersWithDtmf(window);
  5459. shimGetStats(window);
  5460. shimSenderReceiverGetStats(window);
  5461. fixNegotiationNeeded(window, browserDetails);
  5462. shimRTCIceCandidate(window);
  5463. shimConnectionState(window);
  5464. shimMaxMessageSize(window, browserDetails);
  5465. shimSendThrowTypeError(window);
  5466. removeExtmapAllowMixed(window, browserDetails);
  5467. break;
  5468. case 'firefox':
  5469. if (!firefoxShim || !shimPeerConnection ||
  5470. !options.shimFirefox) {
  5471. logging('Firefox shim is not included in this adapter release.');
  5472. return adapter;
  5473. }
  5474. logging('adapter.js shimming firefox.');
  5475. // Export to the adapter global object visible in the browser.
  5476. adapter.browserShim = firefoxShim;
  5477. // Must be called before shimPeerConnection.
  5478. shimAddIceCandidateNullOrEmpty(window, browserDetails);
  5479. shimGetUserMedia$1(window, browserDetails);
  5480. shimPeerConnection(window, browserDetails);
  5481. shimOnTrack(window);
  5482. shimRemoveStream(window);
  5483. shimSenderGetStats(window);
  5484. shimReceiverGetStats(window);
  5485. shimRTCDataChannel(window);
  5486. shimAddTransceiver(window);
  5487. shimGetParameters(window);
  5488. shimCreateOffer(window);
  5489. shimCreateAnswer(window);
  5490. shimRTCIceCandidate(window);
  5491. shimConnectionState(window);
  5492. shimMaxMessageSize(window, browserDetails);
  5493. shimSendThrowTypeError(window);
  5494. break;
  5495. case 'edge':
  5496. if (!edgeShim || !shimPeerConnection$1 || !options.shimEdge) {
  5497. logging('MS edge shim is not included in this adapter release.');
  5498. return adapter;
  5499. }
  5500. logging('adapter.js shimming edge.');
  5501. // Export to the adapter global object visible in the browser.
  5502. adapter.browserShim = edgeShim;
  5503. shimGetUserMedia$2(window);
  5504. shimGetDisplayMedia$1(window);
  5505. shimPeerConnection$1(window, browserDetails);
  5506. shimReplaceTrack(window);
  5507. // the edge shim implements the full RTCIceCandidate object.
  5508. shimMaxMessageSize(window, browserDetails);
  5509. shimSendThrowTypeError(window);
  5510. break;
  5511. case 'safari':
  5512. if (!safariShim || !options.shimSafari) {
  5513. logging('Safari shim is not included in this adapter release.');
  5514. return adapter;
  5515. }
  5516. logging('adapter.js shimming safari.');
  5517. // Export to the adapter global object visible in the browser.
  5518. adapter.browserShim = safariShim;
  5519. // Must be called before shimCallbackAPI.
  5520. shimAddIceCandidateNullOrEmpty(window, browserDetails);
  5521. shimRTCIceServerUrls(window);
  5522. shimCreateOfferLegacy(window);
  5523. shimCallbacksAPI(window);
  5524. shimLocalStreamsAPI(window);
  5525. shimRemoteStreamsAPI(window);
  5526. shimTrackEventTransceiver(window);
  5527. shimGetUserMedia(window);
  5528. shimAudioContext(window);
  5529. shimRTCIceCandidate(window);
  5530. shimMaxMessageSize(window, browserDetails);
  5531. shimSendThrowTypeError(window);
  5532. removeExtmapAllowMixed(window, browserDetails);
  5533. break;
  5534. default:
  5535. logging('Unsupported browser!');
  5536. break;
  5537. }
  5538. return adapter;
  5539. }
  5540. /*
  5541. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  5542. *
  5543. * Use of this source code is governed by a BSD-style license
  5544. * that can be found in the LICENSE file in the root of the source
  5545. * tree.
  5546. */
  5547. adapterFactory({
  5548. window: typeof window === 'undefined' ? undefined : window
  5549. });
  5550. /**
  5551. * @class AudioTrackConstraints
  5552. * @classDesc Constraints for creating an audio MediaStreamTrack.
  5553. * @memberof Owt.Base
  5554. * @constructor
  5555. * @param {Owt.Base.AudioSourceInfo} source Source info of this audio track.
  5556. */
  5557. class AudioTrackConstraints {
  5558. // eslint-disable-next-line require-jsdoc
  5559. constructor(source) {
  5560. if (!Object.values(AudioSourceInfo).some(v => v === source)) {
  5561. throw new TypeError('Invalid source.');
  5562. }
  5563. /**
  5564. * @member {string} source
  5565. * @memberof Owt.Base.AudioTrackConstraints
  5566. * @desc Values could be "mic", "screen-cast", "file" or "mixed".
  5567. * @instance
  5568. */
  5569. this.source = source;
  5570. /**
  5571. * @member {string} deviceId
  5572. * @memberof Owt.Base.AudioTrackConstraints
  5573. * @desc Do not provide deviceId if source is not "mic".
  5574. * @instance
  5575. * @see https://w3c.github.io/mediacapture-main/#def-constraint-deviceId
  5576. */
  5577. this.deviceId = undefined;
  5578. }
  5579. }
  5580. /**
  5581. * @class VideoTrackConstraints
  5582. * @classDesc Constraints for creating a video MediaStreamTrack.
  5583. * @memberof Owt.Base
  5584. * @constructor
  5585. * @param {Owt.Base.VideoSourceInfo} source Source info of this video track.
  5586. */
  5587. class VideoTrackConstraints {
  5588. // eslint-disable-next-line require-jsdoc
  5589. constructor(source) {
  5590. if (!Object.values(VideoSourceInfo).some(v => v === source)) {
  5591. throw new TypeError('Invalid source.');
  5592. }
  5593. /**
  5594. * @member {string} source
  5595. * @memberof Owt.Base.VideoTrackConstraints
  5596. * @desc Values could be "camera", "screen-cast", "file" or "mixed".
  5597. * @instance
  5598. */
  5599. this.source = source;
  5600. /**
  5601. * @member {string} deviceId
  5602. * @memberof Owt.Base.VideoTrackConstraints
  5603. * @desc Do not provide deviceId if source is not "camera".
  5604. * @instance
  5605. * @see https://w3c.github.io/mediacapture-main/#def-constraint-deviceId
  5606. */
  5607. this.deviceId = undefined;
  5608. /**
  5609. * @member {Owt.Base.Resolution} resolution
  5610. * @memberof Owt.Base.VideoTrackConstraints
  5611. * @instance
  5612. */
  5613. this.resolution = undefined;
  5614. /**
  5615. * @member {number} frameRate
  5616. * @memberof Owt.Base.VideoTrackConstraints
  5617. * @instance
  5618. */
  5619. this.frameRate = undefined;
  5620. }
  5621. }
  5622. /**
  5623. * @class StreamConstraints
  5624. * @classDesc Constraints for creating a MediaStream from screen mic and camera.
  5625. * @memberof Owt.Base
  5626. * @constructor
  5627. * @param {?Owt.Base.AudioTrackConstraints} audioConstraints
  5628. * @param {?Owt.Base.VideoTrackConstraints} videoConstraints
  5629. */
  5630. class StreamConstraints {
  5631. // eslint-disable-next-line require-jsdoc
  5632. constructor(audioConstraints = false, videoConstraints = false) {
  5633. /**
  5634. * @member {Owt.Base.MediaStreamTrackDeviceConstraintsForAudio} audio
  5635. * @memberof Owt.Base.MediaStreamDeviceConstraints
  5636. * @instance
  5637. */
  5638. this.audio = audioConstraints;
  5639. /**
  5640. * @member {Owt.Base.MediaStreamTrackDeviceConstraintsForVideo} Video
  5641. * @memberof Owt.Base.MediaStreamDeviceConstraints
  5642. * @instance
  5643. */
  5644. this.video = videoConstraints;
  5645. }
  5646. } // eslint-disable-next-line require-jsdoc
  5647. function isVideoConstrainsForScreenCast(constraints) {
  5648. return typeof constraints.video === 'object' && constraints.video.source === VideoSourceInfo.SCREENCAST;
  5649. }
  5650. /**
  5651. * @class MediaStreamFactory
  5652. * @classDesc A factory to create MediaStream. You can also create MediaStream by yourself.
  5653. * @memberof Owt.Base
  5654. */
  5655. class MediaStreamFactory {
  5656. /**
  5657. * @function createMediaStream
  5658. * @static
  5659. * @desc Create a MediaStream with given constraints. If you want to create a MediaStream for screen cast, please make sure both audio and video's source are "screen-cast".
  5660. * @memberof Owt.Base.MediaStreamFactory
  5661. * @return {Promise<MediaStream, Error>} Return a promise that is resolved when stream is successfully created, or rejected if one of the following error happened:
  5662. * - One or more parameters cannot be satisfied.
  5663. * - Specified device is busy.
  5664. * - Cannot obtain necessary permission or operation is canceled by user.
  5665. * - Video source is screen cast, while audio source is not.
  5666. * - Audio source is screen cast, while video source is disabled.
  5667. * @param {Owt.Base.StreamConstraints} constraints
  5668. */
  5669. static createMediaStream(constraints) {
  5670. if (typeof constraints !== 'object' || !constraints.audio && !constraints.video) {
  5671. return Promise.reject(new TypeError('Invalid constrains'));
  5672. }
  5673. if (!isVideoConstrainsForScreenCast(constraints) && typeof constraints.audio === 'object' && constraints
  5674. .audio.source === AudioSourceInfo.SCREENCAST) {
  5675. return Promise.reject(new TypeError('Cannot share screen without video.'));
  5676. }
  5677. if (isVideoConstrainsForScreenCast(constraints) && !isChrome() && !isFirefox()) {
  5678. return Promise.reject(new TypeError('Screen sharing only supports Chrome and Firefox.'));
  5679. }
  5680. if (isVideoConstrainsForScreenCast(constraints) && typeof constraints.audio === 'object' && constraints
  5681. .audio.source !== AudioSourceInfo.SCREENCAST) {
  5682. return Promise.reject(new TypeError('Cannot capture video from screen cast while capture audio from' +
  5683. ' other source.'));
  5684. } // Check and convert constraints.
  5685. if (!constraints.audio && !constraints.video) {
  5686. return Promise.reject(new TypeError('At least one of audio and video must be requested.'));
  5687. }
  5688. const mediaConstraints = Object.create({});
  5689. if (typeof constraints.audio === 'object' && constraints.audio.source === AudioSourceInfo.MIC) {
  5690. mediaConstraints.audio = Object.create({});
  5691. if (isEdge()) {
  5692. mediaConstraints.audio.deviceId = constraints.audio.deviceId;
  5693. } else {
  5694. mediaConstraints.audio.deviceId = {
  5695. exact: constraints.audio.deviceId
  5696. };
  5697. }
  5698. } else {
  5699. if (constraints.audio.source === AudioSourceInfo.SCREENCAST) {
  5700. mediaConstraints.audio = true;
  5701. } else {
  5702. mediaConstraints.audio = constraints.audio;
  5703. }
  5704. }
  5705. if (typeof constraints.video === 'object') {
  5706. mediaConstraints.video = Object.create({});
  5707. if (typeof constraints.video.frameRate === 'number') {
  5708. mediaConstraints.video.frameRate = constraints.video.frameRate;
  5709. }
  5710. if (constraints.video.resolution && constraints.video.resolution.width && constraints.video.resolution
  5711. .height) {
  5712. if (constraints.video.source === VideoSourceInfo.SCREENCAST) {
  5713. mediaConstraints.video.width = constraints.video.resolution.width;
  5714. mediaConstraints.video.height = constraints.video.resolution.height;
  5715. } else {
  5716. mediaConstraints.video.width = Object.create({});
  5717. mediaConstraints.video.width.exact = constraints.video.resolution.width;
  5718. mediaConstraints.video.height = Object.create({});
  5719. mediaConstraints.video.height.exact = constraints.video.resolution.height;
  5720. }
  5721. }
  5722. if (typeof constraints.video.deviceId === 'string') {
  5723. mediaConstraints.video.deviceId = {
  5724. exact: constraints.video.deviceId
  5725. };
  5726. }
  5727. if (isFirefox() && constraints.video.source === VideoSourceInfo.SCREENCAST) {
  5728. mediaConstraints.video.mediaSource = 'screen';
  5729. }
  5730. } else {
  5731. mediaConstraints.video = constraints.video;
  5732. }
  5733. if (isVideoConstrainsForScreenCast(constraints)) {
  5734. return navigator.mediaDevices.getDisplayMedia(mediaConstraints);
  5735. } else {
  5736. return navigator.mediaDevices.getUserMedia(mediaConstraints);
  5737. }
  5738. }
  5739. }
  5740. let logger;
  5741. let errorLogger;
  5742. function setLogger() {
  5743. /*eslint-disable */
  5744. logger = console.log;
  5745. errorLogger = console.error;
  5746. /*eslint-enable */
  5747. }
  5748. function log(message, ...optionalParams) {
  5749. if (logger) {
  5750. logger(message, ...optionalParams);
  5751. }
  5752. }
  5753. function error(message, ...optionalParams) {
  5754. if (errorLogger) {
  5755. errorLogger(message, ...optionalParams);
  5756. }
  5757. }
  5758. class Event$1 {
  5759. constructor(type) {
  5760. this.listener = {};
  5761. this.type = type | '';
  5762. }
  5763. on(event, fn) {
  5764. if (!this.listener[event]) {
  5765. this.listener[event] = [];
  5766. }
  5767. this.listener[event].push(fn);
  5768. return true;
  5769. }
  5770. off(event, fn) {
  5771. if (this.listener[event]) {
  5772. var index = this.listener[event].indexOf(fn);
  5773. if (index > -1) {
  5774. this.listener[event].splice(index, 1);
  5775. }
  5776. return true;
  5777. }
  5778. return false;
  5779. }
  5780. offAll() {
  5781. this.listener = {};
  5782. }
  5783. dispatch(event, data) {
  5784. if (this.listener[event]) {
  5785. this.listener[event].map(each => {
  5786. each.apply(null, [data]);
  5787. });
  5788. return true;
  5789. }
  5790. return false;
  5791. }
  5792. }
  5793. var bind = function bind(fn, thisArg) {
  5794. return function wrap() {
  5795. var args = new Array(arguments.length);
  5796. for (var i = 0; i < args.length; i++) {
  5797. args[i] = arguments[i];
  5798. }
  5799. return fn.apply(thisArg, args);
  5800. };
  5801. };
  5802. // utils is a library of generic helper functions non-specific to axios
  5803. var toString = Object.prototype.toString;
  5804. // eslint-disable-next-line func-names
  5805. var kindOf = (function(cache) {
  5806. // eslint-disable-next-line func-names
  5807. return function(thing) {
  5808. var str = toString.call(thing);
  5809. return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
  5810. };
  5811. })(Object.create(null));
  5812. function kindOfTest(type) {
  5813. type = type.toLowerCase();
  5814. return function isKindOf(thing) {
  5815. return kindOf(thing) === type;
  5816. };
  5817. }
  5818. /**
  5819. * Determine if a value is an Array
  5820. *
  5821. * @param {Object} val The value to test
  5822. * @returns {boolean} True if value is an Array, otherwise false
  5823. */
  5824. function isArray(val) {
  5825. return Array.isArray(val);
  5826. }
  5827. /**
  5828. * Determine if a value is undefined
  5829. *
  5830. * @param {Object} val The value to test
  5831. * @returns {boolean} True if the value is undefined, otherwise false
  5832. */
  5833. function isUndefined(val) {
  5834. return typeof val === 'undefined';
  5835. }
  5836. /**
  5837. * Determine if a value is a Buffer
  5838. *
  5839. * @param {Object} val The value to test
  5840. * @returns {boolean} True if value is a Buffer, otherwise false
  5841. */
  5842. function isBuffer(val) {
  5843. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) &&
  5844. typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
  5845. }
  5846. /**
  5847. * Determine if a value is an ArrayBuffer
  5848. *
  5849. * @function
  5850. * @param {Object} val The value to test
  5851. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  5852. */
  5853. var isArrayBuffer = kindOfTest('ArrayBuffer');
  5854. /**
  5855. * Determine if a value is a view on an ArrayBuffer
  5856. *
  5857. * @param {Object} val The value to test
  5858. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  5859. */
  5860. function isArrayBufferView(val) {
  5861. var result;
  5862. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  5863. result = ArrayBuffer.isView(val);
  5864. } else {
  5865. result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
  5866. }
  5867. return result;
  5868. }
  5869. /**
  5870. * Determine if a value is a String
  5871. *
  5872. * @param {Object} val The value to test
  5873. * @returns {boolean} True if value is a String, otherwise false
  5874. */
  5875. function isString(val) {
  5876. return typeof val === 'string';
  5877. }
  5878. /**
  5879. * Determine if a value is a Number
  5880. *
  5881. * @param {Object} val The value to test
  5882. * @returns {boolean} True if value is a Number, otherwise false
  5883. */
  5884. function isNumber(val) {
  5885. return typeof val === 'number';
  5886. }
  5887. /**
  5888. * Determine if a value is an Object
  5889. *
  5890. * @param {Object} val The value to test
  5891. * @returns {boolean} True if value is an Object, otherwise false
  5892. */
  5893. function isObject(val) {
  5894. return val !== null && typeof val === 'object';
  5895. }
  5896. /**
  5897. * Determine if a value is a plain Object
  5898. *
  5899. * @param {Object} val The value to test
  5900. * @return {boolean} True if value is a plain Object, otherwise false
  5901. */
  5902. function isPlainObject(val) {
  5903. if (kindOf(val) !== 'object') {
  5904. return false;
  5905. }
  5906. var prototype = Object.getPrototypeOf(val);
  5907. return prototype === null || prototype === Object.prototype;
  5908. }
  5909. /**
  5910. * Determine if a value is a Date
  5911. *
  5912. * @function
  5913. * @param {Object} val The value to test
  5914. * @returns {boolean} True if value is a Date, otherwise false
  5915. */
  5916. var isDate = kindOfTest('Date');
  5917. /**
  5918. * Determine if a value is a File
  5919. *
  5920. * @function
  5921. * @param {Object} val The value to test
  5922. * @returns {boolean} True if value is a File, otherwise false
  5923. */
  5924. var isFile = kindOfTest('File');
  5925. /**
  5926. * Determine if a value is a Blob
  5927. *
  5928. * @function
  5929. * @param {Object} val The value to test
  5930. * @returns {boolean} True if value is a Blob, otherwise false
  5931. */
  5932. var isBlob = kindOfTest('Blob');
  5933. /**
  5934. * Determine if a value is a FileList
  5935. *
  5936. * @function
  5937. * @param {Object} val The value to test
  5938. * @returns {boolean} True if value is a File, otherwise false
  5939. */
  5940. var isFileList = kindOfTest('FileList');
  5941. /**
  5942. * Determine if a value is a Function
  5943. *
  5944. * @param {Object} val The value to test
  5945. * @returns {boolean} True if value is a Function, otherwise false
  5946. */
  5947. function isFunction(val) {
  5948. return toString.call(val) === '[object Function]';
  5949. }
  5950. /**
  5951. * Determine if a value is a Stream
  5952. *
  5953. * @param {Object} val The value to test
  5954. * @returns {boolean} True if value is a Stream, otherwise false
  5955. */
  5956. function isStream(val) {
  5957. return isObject(val) && isFunction(val.pipe);
  5958. }
  5959. /**
  5960. * Determine if a value is a FormData
  5961. *
  5962. * @param {Object} thing The value to test
  5963. * @returns {boolean} True if value is an FormData, otherwise false
  5964. */
  5965. function isFormData(thing) {
  5966. var pattern = '[object FormData]';
  5967. return thing && (
  5968. (typeof FormData === 'function' && thing instanceof FormData) ||
  5969. toString.call(thing) === pattern ||
  5970. (isFunction(thing.toString) && thing.toString() === pattern)
  5971. );
  5972. }
  5973. /**
  5974. * Determine if a value is a URLSearchParams object
  5975. * @function
  5976. * @param {Object} val The value to test
  5977. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  5978. */
  5979. var isURLSearchParams = kindOfTest('URLSearchParams');
  5980. /**
  5981. * Trim excess whitespace off the beginning and end of a string
  5982. *
  5983. * @param {String} str The String to trim
  5984. * @returns {String} The String freed of excess whitespace
  5985. */
  5986. function trim(str) {
  5987. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  5988. }
  5989. /**
  5990. * Determine if we're running in a standard browser environment
  5991. *
  5992. * This allows axios to run in a web worker, and react-native.
  5993. * Both environments support XMLHttpRequest, but not fully standard globals.
  5994. *
  5995. * web workers:
  5996. * typeof window -> undefined
  5997. * typeof document -> undefined
  5998. *
  5999. * react-native:
  6000. * navigator.product -> 'ReactNative'
  6001. * nativescript
  6002. * navigator.product -> 'NativeScript' or 'NS'
  6003. */
  6004. function isStandardBrowserEnv() {
  6005. if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
  6006. navigator.product === 'NativeScript' ||
  6007. navigator.product === 'NS')) {
  6008. return false;
  6009. }
  6010. return (
  6011. typeof window !== 'undefined' &&
  6012. typeof document !== 'undefined'
  6013. );
  6014. }
  6015. /**
  6016. * Iterate over an Array or an Object invoking a function for each item.
  6017. *
  6018. * If `obj` is an Array callback will be called passing
  6019. * the value, index, and complete array for each item.
  6020. *
  6021. * If 'obj' is an Object callback will be called passing
  6022. * the value, key, and complete object for each property.
  6023. *
  6024. * @param {Object|Array} obj The object to iterate
  6025. * @param {Function} fn The callback to invoke for each item
  6026. */
  6027. function forEach(obj, fn) {
  6028. // Don't bother if no value provided
  6029. if (obj === null || typeof obj === 'undefined') {
  6030. return;
  6031. }
  6032. // Force an array if not already something iterable
  6033. if (typeof obj !== 'object') {
  6034. /*eslint no-param-reassign:0*/
  6035. obj = [obj];
  6036. }
  6037. if (isArray(obj)) {
  6038. // Iterate over array values
  6039. for (var i = 0, l = obj.length; i < l; i++) {
  6040. fn.call(null, obj[i], i, obj);
  6041. }
  6042. } else {
  6043. // Iterate over object keys
  6044. for (var key in obj) {
  6045. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  6046. fn.call(null, obj[key], key, obj);
  6047. }
  6048. }
  6049. }
  6050. }
  6051. /**
  6052. * Accepts varargs expecting each argument to be an object, then
  6053. * immutably merges the properties of each object and returns result.
  6054. *
  6055. * When multiple objects contain the same key the later object in
  6056. * the arguments list will take precedence.
  6057. *
  6058. * Example:
  6059. *
  6060. * ```js
  6061. * var result = merge({foo: 123}, {foo: 456});
  6062. * console.log(result.foo); // outputs 456
  6063. * ```
  6064. *
  6065. * @param {Object} obj1 Object to merge
  6066. * @returns {Object} Result of all merge properties
  6067. */
  6068. function merge( /* obj1, obj2, obj3, ... */ ) {
  6069. var result = {};
  6070. function assignValue(val, key) {
  6071. if (isPlainObject(result[key]) && isPlainObject(val)) {
  6072. result[key] = merge(result[key], val);
  6073. } else if (isPlainObject(val)) {
  6074. result[key] = merge({}, val);
  6075. } else if (isArray(val)) {
  6076. result[key] = val.slice();
  6077. } else {
  6078. result[key] = val;
  6079. }
  6080. }
  6081. for (var i = 0, l = arguments.length; i < l; i++) {
  6082. forEach(arguments[i], assignValue);
  6083. }
  6084. return result;
  6085. }
  6086. /**
  6087. * Extends object a by mutably adding to it the properties of object b.
  6088. *
  6089. * @param {Object} a The object to be extended
  6090. * @param {Object} b The object to copy properties from
  6091. * @param {Object} thisArg The object to bind function to
  6092. * @return {Object} The resulting value of object a
  6093. */
  6094. function extend(a, b, thisArg) {
  6095. forEach(b, function assignValue(val, key) {
  6096. if (thisArg && typeof val === 'function') {
  6097. a[key] = bind(val, thisArg);
  6098. } else {
  6099. a[key] = val;
  6100. }
  6101. });
  6102. return a;
  6103. }
  6104. /**
  6105. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  6106. *
  6107. * @param {string} content with BOM
  6108. * @return {string} content value without BOM
  6109. */
  6110. function stripBOM(content) {
  6111. if (content.charCodeAt(0) === 0xFEFF) {
  6112. content = content.slice(1);
  6113. }
  6114. return content;
  6115. }
  6116. /**
  6117. * Inherit the prototype methods from one constructor into another
  6118. * @param {function} constructor
  6119. * @param {function} superConstructor
  6120. * @param {object} [props]
  6121. * @param {object} [descriptors]
  6122. */
  6123. function inherits(constructor, superConstructor, props, descriptors) {
  6124. constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  6125. constructor.prototype.constructor = constructor;
  6126. props && Object.assign(constructor.prototype, props);
  6127. }
  6128. /**
  6129. * Resolve object with deep prototype chain to a flat object
  6130. * @param {Object} sourceObj source object
  6131. * @param {Object} [destObj]
  6132. * @param {Function} [filter]
  6133. * @returns {Object}
  6134. */
  6135. function toFlatObject(sourceObj, destObj, filter) {
  6136. var props;
  6137. var i;
  6138. var prop;
  6139. var merged = {};
  6140. destObj = destObj || {};
  6141. do {
  6142. props = Object.getOwnPropertyNames(sourceObj);
  6143. i = props.length;
  6144. while (i-- > 0) {
  6145. prop = props[i];
  6146. if (!merged[prop]) {
  6147. destObj[prop] = sourceObj[prop];
  6148. merged[prop] = true;
  6149. }
  6150. }
  6151. sourceObj = Object.getPrototypeOf(sourceObj);
  6152. } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
  6153. return destObj;
  6154. }
  6155. /*
  6156. * determines whether a string ends with the characters of a specified string
  6157. * @param {String} str
  6158. * @param {String} searchString
  6159. * @param {Number} [position= 0]
  6160. * @returns {boolean}
  6161. */
  6162. function endsWith(str, searchString, position) {
  6163. str = String(str);
  6164. if (position === undefined || position > str.length) {
  6165. position = str.length;
  6166. }
  6167. position -= searchString.length;
  6168. var lastIndex = str.indexOf(searchString, position);
  6169. return lastIndex !== -1 && lastIndex === position;
  6170. }
  6171. /**
  6172. * Returns new array from array like object
  6173. * @param {*} [thing]
  6174. * @returns {Array}
  6175. */
  6176. function toArray(thing) {
  6177. if (!thing) return null;
  6178. var i = thing.length;
  6179. if (isUndefined(i)) return null;
  6180. var arr = new Array(i);
  6181. while (i-- > 0) {
  6182. arr[i] = thing[i];
  6183. }
  6184. return arr;
  6185. }
  6186. // eslint-disable-next-line func-names
  6187. var isTypedArray = (function(TypedArray) {
  6188. // eslint-disable-next-line func-names
  6189. return function(thing) {
  6190. return TypedArray && thing instanceof TypedArray;
  6191. };
  6192. })(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
  6193. var utils = {
  6194. isArray: isArray,
  6195. isArrayBuffer: isArrayBuffer,
  6196. isBuffer: isBuffer,
  6197. isFormData: isFormData,
  6198. isArrayBufferView: isArrayBufferView,
  6199. isString: isString,
  6200. isNumber: isNumber,
  6201. isObject: isObject,
  6202. isPlainObject: isPlainObject,
  6203. isUndefined: isUndefined,
  6204. isDate: isDate,
  6205. isFile: isFile,
  6206. isBlob: isBlob,
  6207. isFunction: isFunction,
  6208. isStream: isStream,
  6209. isURLSearchParams: isURLSearchParams,
  6210. isStandardBrowserEnv: isStandardBrowserEnv,
  6211. forEach: forEach,
  6212. merge: merge,
  6213. extend: extend,
  6214. trim: trim,
  6215. stripBOM: stripBOM,
  6216. inherits: inherits,
  6217. toFlatObject: toFlatObject,
  6218. kindOf: kindOf,
  6219. kindOfTest: kindOfTest,
  6220. endsWith: endsWith,
  6221. toArray: toArray,
  6222. isTypedArray: isTypedArray,
  6223. isFileList: isFileList
  6224. };
  6225. function encode(val) {
  6226. return encodeURIComponent(val).
  6227. replace(/%3A/gi, ':').
  6228. replace(/%24/g, '$').
  6229. replace(/%2C/gi, ',').
  6230. replace(/%20/g, '+').
  6231. replace(/%5B/gi, '[').
  6232. replace(/%5D/gi, ']');
  6233. }
  6234. /**
  6235. * Build a URL by appending params to the end
  6236. *
  6237. * @param {string} url The base of the url (e.g., http://www.google.com)
  6238. * @param {object} [params] The params to be appended
  6239. * @returns {string} The formatted url
  6240. */
  6241. var buildURL = function buildURL(url, params, paramsSerializer) {
  6242. /*eslint no-param-reassign:0*/
  6243. if (!params) {
  6244. return url;
  6245. }
  6246. var serializedParams;
  6247. if (paramsSerializer) {
  6248. serializedParams = paramsSerializer(params);
  6249. } else if (utils.isURLSearchParams(params)) {
  6250. serializedParams = params.toString();
  6251. } else {
  6252. var parts = [];
  6253. utils.forEach(params, function serialize(val, key) {
  6254. if (val === null || typeof val === 'undefined') {
  6255. return;
  6256. }
  6257. if (utils.isArray(val)) {
  6258. key = key + '[]';
  6259. } else {
  6260. val = [val];
  6261. }
  6262. utils.forEach(val, function parseValue(v) {
  6263. if (utils.isDate(v)) {
  6264. v = v.toISOString();
  6265. } else if (utils.isObject(v)) {
  6266. v = JSON.stringify(v);
  6267. }
  6268. parts.push(encode(key) + '=' + encode(v));
  6269. });
  6270. });
  6271. serializedParams = parts.join('&');
  6272. }
  6273. if (serializedParams) {
  6274. var hashmarkIndex = url.indexOf('#');
  6275. if (hashmarkIndex !== -1) {
  6276. url = url.slice(0, hashmarkIndex);
  6277. }
  6278. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  6279. }
  6280. return url;
  6281. };
  6282. function InterceptorManager() {
  6283. this.handlers = [];
  6284. }
  6285. /**
  6286. * Add a new interceptor to the stack
  6287. *
  6288. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  6289. * @param {Function} rejected The function to handle `reject` for a `Promise`
  6290. *
  6291. * @return {Number} An ID used to remove interceptor later
  6292. */
  6293. InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
  6294. this.handlers.push({
  6295. fulfilled: fulfilled,
  6296. rejected: rejected,
  6297. synchronous: options ? options.synchronous : false,
  6298. runWhen: options ? options.runWhen : null
  6299. });
  6300. return this.handlers.length - 1;
  6301. };
  6302. /**
  6303. * Remove an interceptor from the stack
  6304. *
  6305. * @param {Number} id The ID that was returned by `use`
  6306. */
  6307. InterceptorManager.prototype.eject = function eject(id) {
  6308. if (this.handlers[id]) {
  6309. this.handlers[id] = null;
  6310. }
  6311. };
  6312. /**
  6313. * Iterate over all the registered interceptors
  6314. *
  6315. * This method is particularly useful for skipping over any
  6316. * interceptors that may have become `null` calling `eject`.
  6317. *
  6318. * @param {Function} fn The function to call for each interceptor
  6319. */
  6320. InterceptorManager.prototype.forEach = function forEach(fn) {
  6321. utils.forEach(this.handlers, function forEachHandler(h) {
  6322. if (h !== null) {
  6323. fn(h);
  6324. }
  6325. });
  6326. };
  6327. var InterceptorManager_1 = InterceptorManager;
  6328. var normalizeHeaderName = function normalizeHeaderName(headers, normalizedName) {
  6329. utils.forEach(headers, function processHeader(value, name) {
  6330. if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
  6331. headers[normalizedName] = value;
  6332. delete headers[name];
  6333. }
  6334. });
  6335. };
  6336. /**
  6337. * Create an Error with the specified message, config, error code, request and response.
  6338. *
  6339. * @param {string} message The error message.
  6340. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  6341. * @param {Object} [config] The config.
  6342. * @param {Object} [request] The request.
  6343. * @param {Object} [response] The response.
  6344. * @returns {Error} The created error.
  6345. */
  6346. function AxiosError(message, code, config, request, response) {
  6347. Error.call(this);
  6348. this.message = message;
  6349. this.name = 'AxiosError';
  6350. code && (this.code = code);
  6351. config && (this.config = config);
  6352. request && (this.request = request);
  6353. response && (this.response = response);
  6354. }
  6355. utils.inherits(AxiosError, Error, {
  6356. toJSON: function toJSON() {
  6357. return {
  6358. // Standard
  6359. message: this.message,
  6360. name: this.name,
  6361. // Microsoft
  6362. description: this.description,
  6363. number: this.number,
  6364. // Mozilla
  6365. fileName: this.fileName,
  6366. lineNumber: this.lineNumber,
  6367. columnNumber: this.columnNumber,
  6368. stack: this.stack,
  6369. // Axios
  6370. config: this.config,
  6371. code: this.code,
  6372. status: this.response && this.response.status ? this.response.status : null
  6373. };
  6374. }
  6375. });
  6376. var prototype = AxiosError.prototype;
  6377. var descriptors = {};
  6378. [
  6379. 'ERR_BAD_OPTION_VALUE',
  6380. 'ERR_BAD_OPTION',
  6381. 'ECONNABORTED',
  6382. 'ETIMEDOUT',
  6383. 'ERR_NETWORK',
  6384. 'ERR_FR_TOO_MANY_REDIRECTS',
  6385. 'ERR_DEPRECATED',
  6386. 'ERR_BAD_RESPONSE',
  6387. 'ERR_BAD_REQUEST',
  6388. 'ERR_CANCELED'
  6389. // eslint-disable-next-line func-names
  6390. ].forEach(function(code) {
  6391. descriptors[code] = {
  6392. value: code
  6393. };
  6394. });
  6395. Object.defineProperties(AxiosError, descriptors);
  6396. Object.defineProperty(prototype, 'isAxiosError', {
  6397. value: true
  6398. });
  6399. // eslint-disable-next-line func-names
  6400. AxiosError.from = function(error, code, config, request, response, customProps) {
  6401. var axiosError = Object.create(prototype);
  6402. utils.toFlatObject(error, axiosError, function filter(obj) {
  6403. return obj !== Error.prototype;
  6404. });
  6405. AxiosError.call(axiosError, error.message, code, config, request, response);
  6406. axiosError.name = error.name;
  6407. customProps && Object.assign(axiosError, customProps);
  6408. return axiosError;
  6409. };
  6410. var AxiosError_1 = AxiosError;
  6411. var transitional = {
  6412. silentJSONParsing: true,
  6413. forcedJSONParsing: true,
  6414. clarifyTimeoutError: false
  6415. };
  6416. /**
  6417. * Convert a data object to FormData
  6418. * @param {Object} obj
  6419. * @param {?Object} [formData]
  6420. * @returns {Object}
  6421. **/
  6422. function toFormData(obj, formData) {
  6423. // eslint-disable-next-line no-param-reassign
  6424. formData = formData || new FormData();
  6425. var stack = [];
  6426. function convertValue(value) {
  6427. if (value === null) return '';
  6428. if (utils.isDate(value)) {
  6429. return value.toISOString();
  6430. }
  6431. if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
  6432. return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
  6433. }
  6434. return value;
  6435. }
  6436. function build(data, parentKey) {
  6437. if (utils.isPlainObject(data) || utils.isArray(data)) {
  6438. if (stack.indexOf(data) !== -1) {
  6439. throw Error('Circular reference detected in ' + parentKey);
  6440. }
  6441. stack.push(data);
  6442. utils.forEach(data, function each(value, key) {
  6443. if (utils.isUndefined(value)) return;
  6444. var fullKey = parentKey ? parentKey + '.' + key : key;
  6445. var arr;
  6446. if (value && !parentKey && typeof value === 'object') {
  6447. if (utils.endsWith(key, '{}')) {
  6448. // eslint-disable-next-line no-param-reassign
  6449. value = JSON.stringify(value);
  6450. } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {
  6451. // eslint-disable-next-line func-names
  6452. arr.forEach(function(el) {
  6453. !utils.isUndefined(el) && formData.append(fullKey, convertValue(el));
  6454. });
  6455. return;
  6456. }
  6457. }
  6458. build(value, fullKey);
  6459. });
  6460. stack.pop();
  6461. } else {
  6462. formData.append(parentKey, convertValue(data));
  6463. }
  6464. }
  6465. build(obj);
  6466. return formData;
  6467. }
  6468. var toFormData_1 = toFormData;
  6469. /**
  6470. * Resolve or reject a Promise based on response status.
  6471. *
  6472. * @param {Function} resolve A function that resolves the promise.
  6473. * @param {Function} reject A function that rejects the promise.
  6474. * @param {object} response The response.
  6475. */
  6476. var settle = function settle(resolve, reject, response) {
  6477. var validateStatus = response.config.validateStatus;
  6478. if (!response.status || !validateStatus || validateStatus(response.status)) {
  6479. resolve(response);
  6480. } else {
  6481. reject(new AxiosError_1(
  6482. 'Request failed with status code ' + response.status,
  6483. [AxiosError_1.ERR_BAD_REQUEST, AxiosError_1.ERR_BAD_RESPONSE][Math.floor(response.status /
  6484. 100) - 4],
  6485. response.config,
  6486. response.request,
  6487. response
  6488. ));
  6489. }
  6490. };
  6491. var cookies = (
  6492. utils.isStandardBrowserEnv() ?
  6493. // Standard browser envs support document.cookie
  6494. (function standardBrowserEnv() {
  6495. return {
  6496. write: function write(name, value, expires, path, domain, secure) {
  6497. var cookie = [];
  6498. cookie.push(name + '=' + encodeURIComponent(value));
  6499. if (utils.isNumber(expires)) {
  6500. cookie.push('expires=' + new Date(expires).toGMTString());
  6501. }
  6502. if (utils.isString(path)) {
  6503. cookie.push('path=' + path);
  6504. }
  6505. if (utils.isString(domain)) {
  6506. cookie.push('domain=' + domain);
  6507. }
  6508. if (secure === true) {
  6509. cookie.push('secure');
  6510. }
  6511. document.cookie = cookie.join('; ');
  6512. },
  6513. read: function read(name) {
  6514. var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  6515. return (match ? decodeURIComponent(match[3]) : null);
  6516. },
  6517. remove: function remove(name) {
  6518. this.write(name, '', Date.now() - 86400000);
  6519. }
  6520. };
  6521. })() :
  6522. // Non standard browser env (web workers, react-native) lack needed support.
  6523. (function nonStandardBrowserEnv() {
  6524. return {
  6525. write: function write() {},
  6526. read: function read() {
  6527. return null;
  6528. },
  6529. remove: function remove() {}
  6530. };
  6531. })()
  6532. );
  6533. /**
  6534. * Determines whether the specified URL is absolute
  6535. *
  6536. * @param {string} url The URL to test
  6537. * @returns {boolean} True if the specified URL is absolute, otherwise false
  6538. */
  6539. var isAbsoluteURL = function isAbsoluteURL(url) {
  6540. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  6541. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  6542. // by any combination of letters, digits, plus, period, or hyphen.
  6543. return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
  6544. };
  6545. /**
  6546. * Creates a new URL by combining the specified URLs
  6547. *
  6548. * @param {string} baseURL The base URL
  6549. * @param {string} relativeURL The relative URL
  6550. * @returns {string} The combined URL
  6551. */
  6552. var combineURLs = function combineURLs(baseURL, relativeURL) {
  6553. return relativeURL ?
  6554. baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') :
  6555. baseURL;
  6556. };
  6557. /**
  6558. * Creates a new URL by combining the baseURL with the requestedURL,
  6559. * only when the requestedURL is not already an absolute URL.
  6560. * If the requestURL is absolute, this function returns the requestedURL untouched.
  6561. *
  6562. * @param {string} baseURL The base URL
  6563. * @param {string} requestedURL Absolute or relative URL to combine
  6564. * @returns {string} The combined full path
  6565. */
  6566. var buildFullPath = function buildFullPath(baseURL, requestedURL) {
  6567. if (baseURL && !isAbsoluteURL(requestedURL)) {
  6568. return combineURLs(baseURL, requestedURL);
  6569. }
  6570. return requestedURL;
  6571. };
  6572. // Headers whose duplicates are ignored by node
  6573. // c.f. https://nodejs.org/api/http.html#http_message_headers
  6574. var ignoreDuplicateOf = [
  6575. 'age', 'authorization', 'content-length', 'content-type', 'etag',
  6576. 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  6577. 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  6578. 'referer', 'retry-after', 'user-agent'
  6579. ];
  6580. /**
  6581. * Parse headers into an object
  6582. *
  6583. * ```
  6584. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  6585. * Content-Type: application/json
  6586. * Connection: keep-alive
  6587. * Transfer-Encoding: chunked
  6588. * ```
  6589. *
  6590. * @param {String} headers Headers needing to be parsed
  6591. * @returns {Object} Headers parsed into an object
  6592. */
  6593. var parseHeaders = function parseHeaders(headers) {
  6594. var parsed = {};
  6595. var key;
  6596. var val;
  6597. var i;
  6598. if (!headers) {
  6599. return parsed;
  6600. }
  6601. utils.forEach(headers.split('\n'), function parser(line) {
  6602. i = line.indexOf(':');
  6603. key = utils.trim(line.substr(0, i)).toLowerCase();
  6604. val = utils.trim(line.substr(i + 1));
  6605. if (key) {
  6606. if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
  6607. return;
  6608. }
  6609. if (key === 'set-cookie') {
  6610. parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
  6611. } else {
  6612. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  6613. }
  6614. }
  6615. });
  6616. return parsed;
  6617. };
  6618. var isURLSameOrigin = (
  6619. utils.isStandardBrowserEnv() ?
  6620. // Standard browser envs have full support of the APIs needed to test
  6621. // whether the request URL is of the same origin as current location.
  6622. (function standardBrowserEnv() {
  6623. var msie = /(msie|trident)/i.test(navigator.userAgent);
  6624. var urlParsingNode = document.createElement('a');
  6625. var originURL;
  6626. /**
  6627. * Parse a URL to discover it's components
  6628. *
  6629. * @param {String} url The URL to be parsed
  6630. * @returns {Object}
  6631. */
  6632. function resolveURL(url) {
  6633. var href = url;
  6634. if (msie) {
  6635. // IE needs attribute set twice to normalize properties
  6636. urlParsingNode.setAttribute('href', href);
  6637. href = urlParsingNode.href;
  6638. }
  6639. urlParsingNode.setAttribute('href', href);
  6640. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  6641. return {
  6642. href: urlParsingNode.href,
  6643. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  6644. host: urlParsingNode.host,
  6645. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  6646. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  6647. hostname: urlParsingNode.hostname,
  6648. port: urlParsingNode.port,
  6649. pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
  6650. urlParsingNode.pathname : '/' + urlParsingNode.pathname
  6651. };
  6652. }
  6653. originURL = resolveURL(window.location.href);
  6654. /**
  6655. * Determine if a URL shares the same origin as the current location
  6656. *
  6657. * @param {String} requestURL The URL to test
  6658. * @returns {boolean} True if URL shares the same origin, otherwise false
  6659. */
  6660. return function isURLSameOrigin(requestURL) {
  6661. var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
  6662. return (parsed.protocol === originURL.protocol &&
  6663. parsed.host === originURL.host);
  6664. };
  6665. })() :
  6666. // Non standard browser envs (web workers, react-native) lack needed support.
  6667. (function nonStandardBrowserEnv() {
  6668. return function isURLSameOrigin() {
  6669. return true;
  6670. };
  6671. })()
  6672. );
  6673. /**
  6674. * A `CanceledError` is an object that is thrown when an operation is canceled.
  6675. *
  6676. * @class
  6677. * @param {string=} message The message.
  6678. */
  6679. function CanceledError(message) {
  6680. // eslint-disable-next-line no-eq-null,eqeqeq
  6681. AxiosError_1.call(this, message == null ? 'canceled' : message, AxiosError_1.ERR_CANCELED);
  6682. this.name = 'CanceledError';
  6683. }
  6684. utils.inherits(CanceledError, AxiosError_1, {
  6685. __CANCEL__: true
  6686. });
  6687. var CanceledError_1 = CanceledError;
  6688. var parseProtocol = function parseProtocol(url) {
  6689. var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
  6690. return match && match[1] || '';
  6691. };
  6692. var xhr = function xhrAdapter(config) {
  6693. return new Promise(function dispatchXhrRequest(resolve, reject) {
  6694. var requestData = config.data;
  6695. var requestHeaders = config.headers;
  6696. var responseType = config.responseType;
  6697. var onCanceled;
  6698. function done() {
  6699. if (config.cancelToken) {
  6700. config.cancelToken.unsubscribe(onCanceled);
  6701. }
  6702. if (config.signal) {
  6703. config.signal.removeEventListener('abort', onCanceled);
  6704. }
  6705. }
  6706. if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
  6707. delete requestHeaders['Content-Type']; // Let the browser set it
  6708. }
  6709. var request = new XMLHttpRequest();
  6710. // HTTP basic authentication
  6711. if (config.auth) {
  6712. var username = config.auth.username || '';
  6713. var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
  6714. requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
  6715. }
  6716. var fullPath = buildFullPath(config.baseURL, config.url);
  6717. request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config
  6718. .paramsSerializer), true);
  6719. // Set the request timeout in MS
  6720. request.timeout = config.timeout;
  6721. function onloadend() {
  6722. if (!request) {
  6723. return;
  6724. }
  6725. // Prepare the response
  6726. var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request
  6727. .getAllResponseHeaders()) : null;
  6728. var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
  6729. request.responseText : request.response;
  6730. var response = {
  6731. data: responseData,
  6732. status: request.status,
  6733. statusText: request.statusText,
  6734. headers: responseHeaders,
  6735. config: config,
  6736. request: request
  6737. };
  6738. settle(function _resolve(value) {
  6739. resolve(value);
  6740. done();
  6741. }, function _reject(err) {
  6742. reject(err);
  6743. done();
  6744. }, response);
  6745. // Clean up request
  6746. request = null;
  6747. }
  6748. if ('onloadend' in request) {
  6749. // Use onloadend if available
  6750. request.onloadend = onloadend;
  6751. } else {
  6752. // Listen for ready state to emulate onloadend
  6753. request.onreadystatechange = function handleLoad() {
  6754. if (!request || request.readyState !== 4) {
  6755. return;
  6756. }
  6757. // The request errored out and we didn't get a response, this will be
  6758. // handled by onerror instead
  6759. // With one exception: request that using file: protocol, most browsers
  6760. // will return status as 0 even though it's a successful request
  6761. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf(
  6762. 'file:') === 0)) {
  6763. return;
  6764. }
  6765. // readystate handler is calling before onerror or ontimeout handlers,
  6766. // so we should call onloadend on the next 'tick'
  6767. setTimeout(onloadend);
  6768. };
  6769. }
  6770. // Handle browser request cancellation (as opposed to a manual cancellation)
  6771. request.onabort = function handleAbort() {
  6772. if (!request) {
  6773. return;
  6774. }
  6775. reject(new AxiosError_1('Request aborted', AxiosError_1.ECONNABORTED, config, request));
  6776. // Clean up request
  6777. request = null;
  6778. };
  6779. // Handle low level network errors
  6780. request.onerror = function handleError() {
  6781. // Real errors are hidden from us by the browser
  6782. // onerror should only fire if it's a network error
  6783. reject(new AxiosError_1('Network Error', AxiosError_1.ERR_NETWORK, config, request,
  6784. request));
  6785. // Clean up request
  6786. request = null;
  6787. };
  6788. // Handle timeout
  6789. request.ontimeout = function handleTimeout() {
  6790. var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' :
  6791. 'timeout exceeded';
  6792. var transitional$1 = config.transitional || transitional;
  6793. if (config.timeoutErrorMessage) {
  6794. timeoutErrorMessage = config.timeoutErrorMessage;
  6795. }
  6796. reject(new AxiosError_1(
  6797. timeoutErrorMessage,
  6798. transitional$1.clarifyTimeoutError ? AxiosError_1.ETIMEDOUT : AxiosError_1
  6799. .ECONNABORTED,
  6800. config,
  6801. request));
  6802. // Clean up request
  6803. request = null;
  6804. };
  6805. // Add xsrf header
  6806. // This is only done if running in a standard browser environment.
  6807. // Specifically not if we're in a web worker, or react-native.
  6808. if (utils.isStandardBrowserEnv()) {
  6809. // Add xsrf header
  6810. var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
  6811. cookies.read(config.xsrfCookieName) :
  6812. undefined;
  6813. if (xsrfValue) {
  6814. requestHeaders[config.xsrfHeaderName] = xsrfValue;
  6815. }
  6816. }
  6817. // Add headers to the request
  6818. if ('setRequestHeader' in request) {
  6819. utils.forEach(requestHeaders, function setRequestHeader(val, key) {
  6820. if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
  6821. // Remove Content-Type if data is undefined
  6822. delete requestHeaders[key];
  6823. } else {
  6824. // Otherwise add header to the request
  6825. request.setRequestHeader(key, val);
  6826. }
  6827. });
  6828. }
  6829. // Add withCredentials to request if needed
  6830. if (!utils.isUndefined(config.withCredentials)) {
  6831. request.withCredentials = !!config.withCredentials;
  6832. }
  6833. // Add responseType to request if needed
  6834. if (responseType && responseType !== 'json') {
  6835. request.responseType = config.responseType;
  6836. }
  6837. // Handle progress if needed
  6838. if (typeof config.onDownloadProgress === 'function') {
  6839. request.addEventListener('progress', config.onDownloadProgress);
  6840. }
  6841. // Not all browsers support upload events
  6842. if (typeof config.onUploadProgress === 'function' && request.upload) {
  6843. request.upload.addEventListener('progress', config.onUploadProgress);
  6844. }
  6845. if (config.cancelToken || config.signal) {
  6846. // Handle cancellation
  6847. // eslint-disable-next-line func-names
  6848. onCanceled = function(cancel) {
  6849. if (!request) {
  6850. return;
  6851. }
  6852. reject(!cancel || (cancel && cancel.type) ? new CanceledError_1() : cancel);
  6853. request.abort();
  6854. request = null;
  6855. };
  6856. config.cancelToken && config.cancelToken.subscribe(onCanceled);
  6857. if (config.signal) {
  6858. config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
  6859. }
  6860. }
  6861. if (!requestData) {
  6862. requestData = null;
  6863. }
  6864. var protocol = parseProtocol(fullPath);
  6865. if (protocol && ['http', 'https', 'file'].indexOf(protocol) === -1) {
  6866. reject(new AxiosError_1('Unsupported protocol ' + protocol + ':', AxiosError_1.ERR_BAD_REQUEST,
  6867. config));
  6868. return;
  6869. }
  6870. // Send the request
  6871. request.send(requestData);
  6872. });
  6873. };
  6874. // eslint-disable-next-line strict
  6875. var _null = null;
  6876. var DEFAULT_CONTENT_TYPE = {
  6877. 'Content-Type': 'application/x-www-form-urlencoded'
  6878. };
  6879. function setContentTypeIfUnset(headers, value) {
  6880. if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
  6881. headers['Content-Type'] = value;
  6882. }
  6883. }
  6884. function getDefaultAdapter() {
  6885. var adapter;
  6886. if (typeof XMLHttpRequest !== 'undefined') {
  6887. // For browsers use XHR adapter
  6888. adapter = xhr;
  6889. } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
  6890. // For node use HTTP adapter
  6891. adapter = xhr;
  6892. }
  6893. return adapter;
  6894. }
  6895. function stringifySafely(rawValue, parser, encoder) {
  6896. if (utils.isString(rawValue)) {
  6897. try {
  6898. (parser || JSON.parse)(rawValue);
  6899. return utils.trim(rawValue);
  6900. } catch (e) {
  6901. if (e.name !== 'SyntaxError') {
  6902. throw e;
  6903. }
  6904. }
  6905. }
  6906. return (encoder || JSON.stringify)(rawValue);
  6907. }
  6908. var defaults = {
  6909. transitional: transitional,
  6910. adapter: getDefaultAdapter(),
  6911. transformRequest: [function transformRequest(data, headers) {
  6912. normalizeHeaderName(headers, 'Accept');
  6913. normalizeHeaderName(headers, 'Content-Type');
  6914. if (utils.isFormData(data) ||
  6915. utils.isArrayBuffer(data) ||
  6916. utils.isBuffer(data) ||
  6917. utils.isStream(data) ||
  6918. utils.isFile(data) ||
  6919. utils.isBlob(data)
  6920. ) {
  6921. return data;
  6922. }
  6923. if (utils.isArrayBufferView(data)) {
  6924. return data.buffer;
  6925. }
  6926. if (utils.isURLSearchParams(data)) {
  6927. setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
  6928. return data.toString();
  6929. }
  6930. var isObjectPayload = utils.isObject(data);
  6931. var contentType = headers && headers['Content-Type'];
  6932. var isFileList;
  6933. if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType ===
  6934. 'multipart/form-data')) {
  6935. var _FormData = this.env && this.env.FormData;
  6936. return toFormData_1(isFileList ? {
  6937. 'files[]': data
  6938. } : data, _FormData && new _FormData());
  6939. } else if (isObjectPayload || contentType === 'application/json') {
  6940. setContentTypeIfUnset(headers, 'application/json');
  6941. return stringifySafely(data);
  6942. }
  6943. return data;
  6944. }],
  6945. transformResponse: [function transformResponse(data) {
  6946. var transitional = this.transitional || defaults.transitional;
  6947. var silentJSONParsing = transitional && transitional.silentJSONParsing;
  6948. var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
  6949. var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
  6950. if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
  6951. try {
  6952. return JSON.parse(data);
  6953. } catch (e) {
  6954. if (strictJSONParsing) {
  6955. if (e.name === 'SyntaxError') {
  6956. throw AxiosError_1.from(e, AxiosError_1.ERR_BAD_RESPONSE, this, null, this
  6957. .response);
  6958. }
  6959. throw e;
  6960. }
  6961. }
  6962. }
  6963. return data;
  6964. }],
  6965. /**
  6966. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  6967. * timeout is not created.
  6968. */
  6969. timeout: 0,
  6970. xsrfCookieName: 'XSRF-TOKEN',
  6971. xsrfHeaderName: 'X-XSRF-TOKEN',
  6972. maxContentLength: -1,
  6973. maxBodyLength: -1,
  6974. env: {
  6975. FormData: _null
  6976. },
  6977. validateStatus: function validateStatus(status) {
  6978. return status >= 200 && status < 300;
  6979. },
  6980. headers: {
  6981. common: {
  6982. 'Accept': 'application/json, text/plain, */*'
  6983. }
  6984. }
  6985. };
  6986. utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
  6987. defaults.headers[method] = {};
  6988. });
  6989. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  6990. defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  6991. });
  6992. var defaults_1 = defaults;
  6993. /**
  6994. * Transform the data for a request or a response
  6995. *
  6996. * @param {Object|String} data The data to be transformed
  6997. * @param {Array} headers The headers for the request or response
  6998. * @param {Array|Function} fns A single function or Array of functions
  6999. * @returns {*} The resulting transformed data
  7000. */
  7001. var transformData = function transformData(data, headers, fns) {
  7002. var context = this || defaults_1;
  7003. /*eslint no-param-reassign:0*/
  7004. utils.forEach(fns, function transform(fn) {
  7005. data = fn.call(context, data, headers);
  7006. });
  7007. return data;
  7008. };
  7009. var isCancel = function isCancel(value) {
  7010. return !!(value && value.__CANCEL__);
  7011. };
  7012. /**
  7013. * Throws a `CanceledError` if cancellation has been requested.
  7014. */
  7015. function throwIfCancellationRequested(config) {
  7016. if (config.cancelToken) {
  7017. config.cancelToken.throwIfRequested();
  7018. }
  7019. if (config.signal && config.signal.aborted) {
  7020. throw new CanceledError_1();
  7021. }
  7022. }
  7023. /**
  7024. * Dispatch a request to the server using the configured adapter.
  7025. *
  7026. * @param {object} config The config that is to be used for the request
  7027. * @returns {Promise} The Promise to be fulfilled
  7028. */
  7029. var dispatchRequest = function dispatchRequest(config) {
  7030. throwIfCancellationRequested(config);
  7031. // Ensure headers exist
  7032. config.headers = config.headers || {};
  7033. // Transform request data
  7034. config.data = transformData.call(
  7035. config,
  7036. config.data,
  7037. config.headers,
  7038. config.transformRequest
  7039. );
  7040. // Flatten headers
  7041. config.headers = utils.merge(
  7042. config.headers.common || {},
  7043. config.headers[config.method] || {},
  7044. config.headers
  7045. );
  7046. utils.forEach(
  7047. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  7048. function cleanHeaderConfig(method) {
  7049. delete config.headers[method];
  7050. }
  7051. );
  7052. var adapter = config.adapter || defaults_1.adapter;
  7053. return adapter(config).then(function onAdapterResolution(response) {
  7054. throwIfCancellationRequested(config);
  7055. // Transform response data
  7056. response.data = transformData.call(
  7057. config,
  7058. response.data,
  7059. response.headers,
  7060. config.transformResponse
  7061. );
  7062. return response;
  7063. }, function onAdapterRejection(reason) {
  7064. if (!isCancel(reason)) {
  7065. throwIfCancellationRequested(config);
  7066. // Transform response data
  7067. if (reason && reason.response) {
  7068. reason.response.data = transformData.call(
  7069. config,
  7070. reason.response.data,
  7071. reason.response.headers,
  7072. config.transformResponse
  7073. );
  7074. }
  7075. }
  7076. return Promise.reject(reason);
  7077. });
  7078. };
  7079. /**
  7080. * Config-specific merge-function which creates a new config-object
  7081. * by merging two configuration objects together.
  7082. *
  7083. * @param {Object} config1
  7084. * @param {Object} config2
  7085. * @returns {Object} New object resulting from merging config2 to config1
  7086. */
  7087. var mergeConfig = function mergeConfig(config1, config2) {
  7088. // eslint-disable-next-line no-param-reassign
  7089. config2 = config2 || {};
  7090. var config = {};
  7091. function getMergedValue(target, source) {
  7092. if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
  7093. return utils.merge(target, source);
  7094. } else if (utils.isPlainObject(source)) {
  7095. return utils.merge({}, source);
  7096. } else if (utils.isArray(source)) {
  7097. return source.slice();
  7098. }
  7099. return source;
  7100. }
  7101. // eslint-disable-next-line consistent-return
  7102. function mergeDeepProperties(prop) {
  7103. if (!utils.isUndefined(config2[prop])) {
  7104. return getMergedValue(config1[prop], config2[prop]);
  7105. } else if (!utils.isUndefined(config1[prop])) {
  7106. return getMergedValue(undefined, config1[prop]);
  7107. }
  7108. }
  7109. // eslint-disable-next-line consistent-return
  7110. function valueFromConfig2(prop) {
  7111. if (!utils.isUndefined(config2[prop])) {
  7112. return getMergedValue(undefined, config2[prop]);
  7113. }
  7114. }
  7115. // eslint-disable-next-line consistent-return
  7116. function defaultToConfig2(prop) {
  7117. if (!utils.isUndefined(config2[prop])) {
  7118. return getMergedValue(undefined, config2[prop]);
  7119. } else if (!utils.isUndefined(config1[prop])) {
  7120. return getMergedValue(undefined, config1[prop]);
  7121. }
  7122. }
  7123. // eslint-disable-next-line consistent-return
  7124. function mergeDirectKeys(prop) {
  7125. if (prop in config2) {
  7126. return getMergedValue(config1[prop], config2[prop]);
  7127. } else if (prop in config1) {
  7128. return getMergedValue(undefined, config1[prop]);
  7129. }
  7130. }
  7131. var mergeMap = {
  7132. 'url': valueFromConfig2,
  7133. 'method': valueFromConfig2,
  7134. 'data': valueFromConfig2,
  7135. 'baseURL': defaultToConfig2,
  7136. 'transformRequest': defaultToConfig2,
  7137. 'transformResponse': defaultToConfig2,
  7138. 'paramsSerializer': defaultToConfig2,
  7139. 'timeout': defaultToConfig2,
  7140. 'timeoutMessage': defaultToConfig2,
  7141. 'withCredentials': defaultToConfig2,
  7142. 'adapter': defaultToConfig2,
  7143. 'responseType': defaultToConfig2,
  7144. 'xsrfCookieName': defaultToConfig2,
  7145. 'xsrfHeaderName': defaultToConfig2,
  7146. 'onUploadProgress': defaultToConfig2,
  7147. 'onDownloadProgress': defaultToConfig2,
  7148. 'decompress': defaultToConfig2,
  7149. 'maxContentLength': defaultToConfig2,
  7150. 'maxBodyLength': defaultToConfig2,
  7151. 'beforeRedirect': defaultToConfig2,
  7152. 'transport': defaultToConfig2,
  7153. 'httpAgent': defaultToConfig2,
  7154. 'httpsAgent': defaultToConfig2,
  7155. 'cancelToken': defaultToConfig2,
  7156. 'socketPath': defaultToConfig2,
  7157. 'responseEncoding': defaultToConfig2,
  7158. 'validateStatus': mergeDirectKeys
  7159. };
  7160. utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
  7161. var merge = mergeMap[prop] || mergeDeepProperties;
  7162. var configValue = merge(prop);
  7163. (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
  7164. });
  7165. return config;
  7166. };
  7167. var data = {
  7168. "version": "0.27.2"
  7169. };
  7170. var VERSION = data.version;
  7171. var validators$1 = {};
  7172. // eslint-disable-next-line func-names
  7173. ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
  7174. validators$1[type] = function validator(thing) {
  7175. return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  7176. };
  7177. });
  7178. var deprecatedWarnings = {};
  7179. /**
  7180. * Transitional option validator
  7181. * @param {function|boolean?} validator - set to false if the transitional option has been removed
  7182. * @param {string?} version - deprecated version / removed since version
  7183. * @param {string?} message - some message with additional info
  7184. * @returns {function}
  7185. */
  7186. validators$1.transitional = function transitional(validator, version, message) {
  7187. function formatMessage(opt, desc) {
  7188. return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message :
  7189. '');
  7190. }
  7191. // eslint-disable-next-line func-names
  7192. return function(value, opt, opts) {
  7193. if (validator === false) {
  7194. throw new AxiosError_1(
  7195. formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
  7196. AxiosError_1.ERR_DEPRECATED
  7197. );
  7198. }
  7199. if (version && !deprecatedWarnings[opt]) {
  7200. deprecatedWarnings[opt] = true;
  7201. // eslint-disable-next-line no-console
  7202. console.warn(
  7203. formatMessage(
  7204. opt,
  7205. ' has been deprecated since v' + version + ' and will be removed in the near future'
  7206. )
  7207. );
  7208. }
  7209. return validator ? validator(value, opt, opts) : true;
  7210. };
  7211. };
  7212. /**
  7213. * Assert object's properties type
  7214. * @param {object} options
  7215. * @param {object} schema
  7216. * @param {boolean?} allowUnknown
  7217. */
  7218. function assertOptions(options, schema, allowUnknown) {
  7219. if (typeof options !== 'object') {
  7220. throw new AxiosError_1('options must be an object', AxiosError_1.ERR_BAD_OPTION_VALUE);
  7221. }
  7222. var keys = Object.keys(options);
  7223. var i = keys.length;
  7224. while (i-- > 0) {
  7225. var opt = keys[i];
  7226. var validator = schema[opt];
  7227. if (validator) {
  7228. var value = options[opt];
  7229. var result = value === undefined || validator(value, opt, options);
  7230. if (result !== true) {
  7231. throw new AxiosError_1('option ' + opt + ' must be ' + result, AxiosError_1.ERR_BAD_OPTION_VALUE);
  7232. }
  7233. continue;
  7234. }
  7235. if (allowUnknown !== true) {
  7236. throw new AxiosError_1('Unknown option ' + opt, AxiosError_1.ERR_BAD_OPTION);
  7237. }
  7238. }
  7239. }
  7240. var validator = {
  7241. assertOptions: assertOptions,
  7242. validators: validators$1
  7243. };
  7244. var validators = validator.validators;
  7245. /**
  7246. * Create a new instance of Axios
  7247. *
  7248. * @param {Object} instanceConfig The default config for the instance
  7249. */
  7250. function Axios(instanceConfig) {
  7251. this.defaults = instanceConfig;
  7252. this.interceptors = {
  7253. request: new InterceptorManager_1(),
  7254. response: new InterceptorManager_1()
  7255. };
  7256. }
  7257. /**
  7258. * Dispatch a request
  7259. *
  7260. * @param {Object} config The config specific for this request (merged with this.defaults)
  7261. */
  7262. Axios.prototype.request = function request(configOrUrl, config) {
  7263. /*eslint no-param-reassign:0*/
  7264. // Allow for axios('example/url'[, config]) a la fetch API
  7265. if (typeof configOrUrl === 'string') {
  7266. config = config || {};
  7267. config.url = configOrUrl;
  7268. } else {
  7269. config = configOrUrl || {};
  7270. }
  7271. config = mergeConfig(this.defaults, config);
  7272. // Set config.method
  7273. if (config.method) {
  7274. config.method = config.method.toLowerCase();
  7275. } else if (this.defaults.method) {
  7276. config.method = this.defaults.method.toLowerCase();
  7277. } else {
  7278. config.method = 'get';
  7279. }
  7280. var transitional = config.transitional;
  7281. if (transitional !== undefined) {
  7282. validator.assertOptions(transitional, {
  7283. silentJSONParsing: validators.transitional(validators.boolean),
  7284. forcedJSONParsing: validators.transitional(validators.boolean),
  7285. clarifyTimeoutError: validators.transitional(validators.boolean)
  7286. }, false);
  7287. }
  7288. // filter out skipped interceptors
  7289. var requestInterceptorChain = [];
  7290. var synchronousRequestInterceptors = true;
  7291. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  7292. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  7293. return;
  7294. }
  7295. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  7296. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  7297. });
  7298. var responseInterceptorChain = [];
  7299. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  7300. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  7301. });
  7302. var promise;
  7303. if (!synchronousRequestInterceptors) {
  7304. var chain = [dispatchRequest, undefined];
  7305. Array.prototype.unshift.apply(chain, requestInterceptorChain);
  7306. chain = chain.concat(responseInterceptorChain);
  7307. promise = Promise.resolve(config);
  7308. while (chain.length) {
  7309. promise = promise.then(chain.shift(), chain.shift());
  7310. }
  7311. return promise;
  7312. }
  7313. var newConfig = config;
  7314. while (requestInterceptorChain.length) {
  7315. var onFulfilled = requestInterceptorChain.shift();
  7316. var onRejected = requestInterceptorChain.shift();
  7317. try {
  7318. newConfig = onFulfilled(newConfig);
  7319. } catch (error) {
  7320. onRejected(error);
  7321. break;
  7322. }
  7323. }
  7324. try {
  7325. promise = dispatchRequest(newConfig);
  7326. } catch (error) {
  7327. return Promise.reject(error);
  7328. }
  7329. while (responseInterceptorChain.length) {
  7330. promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
  7331. }
  7332. return promise;
  7333. };
  7334. Axios.prototype.getUri = function getUri(config) {
  7335. config = mergeConfig(this.defaults, config);
  7336. var fullPath = buildFullPath(config.baseURL, config.url);
  7337. return buildURL(fullPath, config.params, config.paramsSerializer);
  7338. };
  7339. // Provide aliases for supported request methods
  7340. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  7341. /*eslint func-names:0*/
  7342. Axios.prototype[method] = function(url, config) {
  7343. return this.request(mergeConfig(config || {}, {
  7344. method: method,
  7345. url: url,
  7346. data: (config || {}).data
  7347. }));
  7348. };
  7349. });
  7350. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  7351. /*eslint func-names:0*/
  7352. function generateHTTPMethod(isForm) {
  7353. return function httpMethod(url, data, config) {
  7354. return this.request(mergeConfig(config || {}, {
  7355. method: method,
  7356. headers: isForm ? {
  7357. 'Content-Type': 'multipart/form-data'
  7358. } : {},
  7359. url: url,
  7360. data: data
  7361. }));
  7362. };
  7363. }
  7364. Axios.prototype[method] = generateHTTPMethod();
  7365. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  7366. });
  7367. var Axios_1 = Axios;
  7368. /**
  7369. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  7370. *
  7371. * @class
  7372. * @param {Function} executor The executor function.
  7373. */
  7374. function CancelToken(executor) {
  7375. if (typeof executor !== 'function') {
  7376. throw new TypeError('executor must be a function.');
  7377. }
  7378. var resolvePromise;
  7379. this.promise = new Promise(function promiseExecutor(resolve) {
  7380. resolvePromise = resolve;
  7381. });
  7382. var token = this;
  7383. // eslint-disable-next-line func-names
  7384. this.promise.then(function(cancel) {
  7385. if (!token._listeners) return;
  7386. var i;
  7387. var l = token._listeners.length;
  7388. for (i = 0; i < l; i++) {
  7389. token._listeners[i](cancel);
  7390. }
  7391. token._listeners = null;
  7392. });
  7393. // eslint-disable-next-line func-names
  7394. this.promise.then = function(onfulfilled) {
  7395. var _resolve;
  7396. // eslint-disable-next-line func-names
  7397. var promise = new Promise(function(resolve) {
  7398. token.subscribe(resolve);
  7399. _resolve = resolve;
  7400. }).then(onfulfilled);
  7401. promise.cancel = function reject() {
  7402. token.unsubscribe(_resolve);
  7403. };
  7404. return promise;
  7405. };
  7406. executor(function cancel(message) {
  7407. if (token.reason) {
  7408. // Cancellation has already been requested
  7409. return;
  7410. }
  7411. token.reason = new CanceledError_1(message);
  7412. resolvePromise(token.reason);
  7413. });
  7414. }
  7415. /**
  7416. * Throws a `CanceledError` if cancellation has been requested.
  7417. */
  7418. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  7419. if (this.reason) {
  7420. throw this.reason;
  7421. }
  7422. };
  7423. /**
  7424. * Subscribe to the cancel signal
  7425. */
  7426. CancelToken.prototype.subscribe = function subscribe(listener) {
  7427. if (this.reason) {
  7428. listener(this.reason);
  7429. return;
  7430. }
  7431. if (this._listeners) {
  7432. this._listeners.push(listener);
  7433. } else {
  7434. this._listeners = [listener];
  7435. }
  7436. };
  7437. /**
  7438. * Unsubscribe from the cancel signal
  7439. */
  7440. CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
  7441. if (!this._listeners) {
  7442. return;
  7443. }
  7444. var index = this._listeners.indexOf(listener);
  7445. if (index !== -1) {
  7446. this._listeners.splice(index, 1);
  7447. }
  7448. };
  7449. /**
  7450. * Returns an object that contains a new `CancelToken` and a function that, when called,
  7451. * cancels the `CancelToken`.
  7452. */
  7453. CancelToken.source = function source() {
  7454. var cancel;
  7455. var token = new CancelToken(function executor(c) {
  7456. cancel = c;
  7457. });
  7458. return {
  7459. token: token,
  7460. cancel: cancel
  7461. };
  7462. };
  7463. var CancelToken_1 = CancelToken;
  7464. /**
  7465. * Syntactic sugar for invoking a function and expanding an array for arguments.
  7466. *
  7467. * Common use case would be to use `Function.prototype.apply`.
  7468. *
  7469. * ```js
  7470. * function f(x, y, z) {}
  7471. * var args = [1, 2, 3];
  7472. * f.apply(null, args);
  7473. * ```
  7474. *
  7475. * With `spread` this example can be re-written.
  7476. *
  7477. * ```js
  7478. * spread(function(x, y, z) {})([1, 2, 3]);
  7479. * ```
  7480. *
  7481. * @param {Function} callback
  7482. * @returns {Function}
  7483. */
  7484. var spread = function spread(callback) {
  7485. return function wrap(arr) {
  7486. return callback.apply(null, arr);
  7487. };
  7488. };
  7489. /**
  7490. * Determines whether the payload is an error thrown by Axios
  7491. *
  7492. * @param {*} payload The value to test
  7493. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  7494. */
  7495. var isAxiosError = function isAxiosError(payload) {
  7496. return utils.isObject(payload) && (payload.isAxiosError === true);
  7497. };
  7498. /**
  7499. * Create an instance of Axios
  7500. *
  7501. * @param {Object} defaultConfig The default config for the instance
  7502. * @return {Axios} A new instance of Axios
  7503. */
  7504. function createInstance(defaultConfig) {
  7505. var context = new Axios_1(defaultConfig);
  7506. var instance = bind(Axios_1.prototype.request, context);
  7507. // Copy axios.prototype to instance
  7508. utils.extend(instance, Axios_1.prototype, context);
  7509. // Copy context to instance
  7510. utils.extend(instance, context);
  7511. // Factory for creating new instances
  7512. instance.create = function create(instanceConfig) {
  7513. return createInstance(mergeConfig(defaultConfig, instanceConfig));
  7514. };
  7515. return instance;
  7516. }
  7517. // Create the default instance to be exported
  7518. var axios$1 = createInstance(defaults_1);
  7519. // Expose Axios class to allow class inheritance
  7520. axios$1.Axios = Axios_1;
  7521. // Expose Cancel & CancelToken
  7522. axios$1.CanceledError = CanceledError_1;
  7523. axios$1.CancelToken = CancelToken_1;
  7524. axios$1.isCancel = isCancel;
  7525. axios$1.VERSION = data.version;
  7526. axios$1.toFormData = toFormData_1;
  7527. // Expose AxiosError class
  7528. axios$1.AxiosError = AxiosError_1;
  7529. // alias for CanceledError for backward compatibility
  7530. axios$1.Cancel = axios$1.CanceledError;
  7531. // Expose all/spread
  7532. axios$1.all = function all(promises) {
  7533. return Promise.all(promises);
  7534. };
  7535. axios$1.spread = spread;
  7536. // Expose isAxiosError
  7537. axios$1.isAxiosError = isAxiosError;
  7538. var axios_1 = axios$1;
  7539. // Allow use of default import syntax in TypeScript
  7540. var _default = axios$1;
  7541. axios_1.default = _default;
  7542. var axios = axios_1;
  7543. class RTCEndpoint extends Event$1 {
  7544. constructor(options) {
  7545. super('RTCPusherPlayer');
  7546. this.TAG = '[RTCPusherPlayer]';
  7547. let defaults = {
  7548. element: '',
  7549. // html video element
  7550. debug: false,
  7551. // if output debug log
  7552. zlmsdpUrl: '',
  7553. simulcast: false,
  7554. useCamera: true,
  7555. audioEnable: true,
  7556. videoEnable: true,
  7557. recvOnly: false,
  7558. resolution: {
  7559. w: 0,
  7560. h: 0
  7561. },
  7562. usedatachannel: false
  7563. };
  7564. this.options = Object.assign({}, defaults, options);
  7565. if (this.options.debug) {
  7566. setLogger();
  7567. }
  7568. this.e = {
  7569. onicecandidate: this._onIceCandidate.bind(this),
  7570. ontrack: this._onTrack.bind(this),
  7571. onicecandidateerror: this._onIceCandidateError.bind(this),
  7572. onconnectionstatechange: this._onconnectionstatechange.bind(this),
  7573. ondatachannelopen: this._onDataChannelOpen.bind(this),
  7574. ondatachannelmsg: this._onDataChannelMsg.bind(this),
  7575. ondatachannelerr: this._onDataChannelErr.bind(this),
  7576. ondatachannelclose: this._onDataChannelClose.bind(this)
  7577. };
  7578. this._remoteStream = null;
  7579. this._localStream = null;
  7580. this.pc = new RTCPeerConnection(null);
  7581. this.pc.onicecandidate = this.e.onicecandidate;
  7582. this.pc.onicecandidateerror = this.e.onicecandidateerror;
  7583. this.pc.ontrack = this.e.ontrack;
  7584. this.pc.onconnectionstatechange = this.e.onconnectionstatechange;
  7585. this.datachannel = null;
  7586. if (this.options.usedatachannel) {
  7587. this.datachannel = this.pc.createDataChannel('chat');
  7588. this.datachannel.onclose = this.e.ondatachannelclose;
  7589. this.datachannel.onerror = this.e.ondatachannelerr;
  7590. this.datachannel.onmessage = this.e.ondatachannelmsg;
  7591. this.datachannel.onopen = this.e.ondatachannelopen;
  7592. }
  7593. if (!this.options.recvOnly && (this.options.audioEnable || this.options.videoEnable)) this.start();
  7594. else this.receive();
  7595. }
  7596. receive() {
  7597. const AudioTransceiverInit = {
  7598. direction: 'recvonly',
  7599. sendEncodings: []
  7600. };
  7601. const VideoTransceiverInit = {
  7602. direction: 'recvonly',
  7603. sendEncodings: []
  7604. };
  7605. if (this.options.videoEnable) {
  7606. this.pc.addTransceiver('video', VideoTransceiverInit);
  7607. }
  7608. if (this.options.audioEnable) {
  7609. this.pc.addTransceiver('audio', AudioTransceiverInit);
  7610. }
  7611. this.pc.createOffer().then(desc => {
  7612. log(this.TAG, 'offer:', desc.sdp);
  7613. this.pc.setLocalDescription(desc).then(() => {
  7614. axios({
  7615. method: 'post',
  7616. url: this.options.zlmsdpUrl,
  7617. responseType: 'json',
  7618. data: desc.sdp,
  7619. headers: {
  7620. 'Content-Type': 'text/plain;charset=utf-8'
  7621. }
  7622. }).then(response => {
  7623. let ret = response.data; //JSON.parse(response.data);
  7624. if (ret.code != 0) {
  7625. // mean failed for offer/anwser exchange
  7626. this.dispatch(Events$1.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, ret);
  7627. return;
  7628. }
  7629. let anwser = {};
  7630. var re = this.replaceCandidate(ret.sdp);
  7631. anwser.sdp = re;
  7632. anwser.type = 'answer';
  7633. log(this.TAG, 'answer:', ret.sdp);
  7634. this.pc.setRemoteDescription(anwser).then(() => {
  7635. this.options.successCallback()
  7636. log(this.TAG, 'set remote sucess');
  7637. }).catch(e => {
  7638. error(this.TAG, e);
  7639. });
  7640. }).catch(err => {
  7641. clearInterval(heartBeatFlag)
  7642. ws.close()
  7643. });
  7644. });
  7645. }).catch(e => {
  7646. error(this.TAG, e);
  7647. });
  7648. }
  7649. splitSections(blob) {
  7650. var parts = blob.split('\nm=');
  7651. return parts.map(function(part, index) {
  7652. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  7653. });
  7654. }
  7655. splitLines(blob) {
  7656. return blob.trim().split('\n').map(function(line) {
  7657. return line.trim();
  7658. });
  7659. }
  7660. matchPrefixExt(blob, prefix) {
  7661. return this.splitLines(blob).filter(function(line) {
  7662. return line.indexOf(prefix) === 0;
  7663. });
  7664. }
  7665. replaceCandidate(sdp) {
  7666. var sections = this.splitSections(sdp);
  7667. var cands;
  7668. sections.forEach(e => {
  7669. // console.log('==========eee',e)
  7670. cands = this.matchPrefixExt(e, 'a=candidate:');
  7671. // console.log(cands[0]);
  7672. });
  7673. // console.log("=======ip---------", window.cloudgame_sdk.extraData.remainingTimeData.data.extranetIp, window.cloudgame_sdk.extraData.remainingTimeData.data.extranetPort);
  7674. let aaa =
  7675. `a=candidate:udpcandidate 1 udp 120 typ host`;
  7676. var data = '';
  7677. // const deviceInline = CLOUD_GAME_SDK.getQueryVariable("deviceInline")
  7678. if (window.location.protocol === 'http:') {
  7679. data = sdp;
  7680. } else {
  7681. // data = sdp.replaceAll(cands[0], aaa);
  7682. // data = sdp.replace(/cands[0]/g, aaa);
  7683. data = sdp.replace(new RegExp(cands[0], 'g'), aaa);
  7684. }
  7685. // const data = sdp
  7686. return data
  7687. // console.log(sections);
  7688. }
  7689. start() {
  7690. let videoConstraints = false;
  7691. let audioConstraints = false;
  7692. if (this.options.useCamera) {
  7693. if (this.options.videoEnable) videoConstraints = new VideoTrackConstraints(VideoSourceInfo.CAMERA);
  7694. if (this.options.audioEnable) audioConstraints = new AudioTrackConstraints(AudioSourceInfo.MIC);
  7695. } else {
  7696. if (this.options.videoEnable) {
  7697. videoConstraints = new VideoTrackConstraints(VideoSourceInfo.SCREENCAST);
  7698. if (this.options.audioEnable) audioConstraints = new AudioTrackConstraints(AudioSourceInfo
  7699. .SCREENCAST);
  7700. } else {
  7701. if (this.options.audioEnable) audioConstraints = new AudioTrackConstraints(AudioSourceInfo.MIC);
  7702. else {
  7703. // error shared display media not only audio
  7704. error(this.TAG, 'error paramter');
  7705. }
  7706. }
  7707. }
  7708. if (this.options.resolution.w != 0 && this.options.resolution.h != 0 && typeof videoConstraints ==
  7709. 'object') {
  7710. videoConstraints.resolution = new Resolution(this.options.resolution.w, this.options.resolution.h);
  7711. }
  7712. MediaStreamFactory.createMediaStream(new StreamConstraints(audioConstraints, videoConstraints)).then(
  7713. stream => {
  7714. this._localStream = stream;
  7715. this.dispatch(Events$1.WEBRTC_ON_LOCAL_STREAM, stream);
  7716. const AudioTransceiverInit = {
  7717. direction: 'sendrecv',
  7718. sendEncodings: []
  7719. };
  7720. const VideoTransceiverInit = {
  7721. direction: 'sendrecv',
  7722. sendEncodings: []
  7723. };
  7724. if (this.options.simulcast && stream.getVideoTracks().length > 0) {
  7725. VideoTransceiverInit.sendEncodings = [{
  7726. rid: 'h',
  7727. active: true,
  7728. maxBitrate: 1000000
  7729. }, {
  7730. rid: 'm',
  7731. active: true,
  7732. maxBitrate: 500000,
  7733. scaleResolutionDownBy: 2
  7734. }, {
  7735. rid: 'l',
  7736. active: true,
  7737. maxBitrate: 200000,
  7738. scaleResolutionDownBy: 4
  7739. }];
  7740. }
  7741. if (this.options.audioEnable) {
  7742. if (stream.getAudioTracks().length > 0) {
  7743. this.pc.addTransceiver(stream.getAudioTracks()[0], AudioTransceiverInit);
  7744. } else {
  7745. AudioTransceiverInit.direction = 'recvonly';
  7746. this.pc.addTransceiver('audio', AudioTransceiverInit);
  7747. }
  7748. }
  7749. if (this.options.videoEnable) {
  7750. if (stream.getVideoTracks().length > 0) {
  7751. this.pc.addTransceiver(stream.getVideoTracks()[0], VideoTransceiverInit);
  7752. } else {
  7753. VideoTransceiverInit.direction = 'recvonly';
  7754. this.pc.addTransceiver('video', VideoTransceiverInit);
  7755. }
  7756. }
  7757. /*
  7758. stream.getTracks().forEach((track,idx)=>{
  7759. debug.log(this.TAG,track);
  7760. this.pc.addTrack(track);
  7761. });
  7762. */
  7763. this.pc.createOffer().then(desc => {
  7764. log(this.TAG, 'offer:', desc.sdp);
  7765. this.pc.setLocalDescription(desc).then(() => {
  7766. axios({
  7767. method: 'post',
  7768. url: this.options.zlmsdpUrl,
  7769. responseType: 'json',
  7770. data: desc.sdp,
  7771. headers: {
  7772. 'Content-Type': 'text/plain;charset=utf-8'
  7773. }
  7774. }).then(response => {
  7775. let ret = response.data; //JSON.parse(response.data);
  7776. if (ret.code != 0) {
  7777. // mean failed for offer/anwser exchange
  7778. this.dispatch(Events$1
  7779. .WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, ret);
  7780. return;
  7781. }
  7782. let anwser = {};
  7783. anwser.sdp = ret.sdp;
  7784. anwser.type = 'answer';
  7785. log(this.TAG, 'answer:', ret.sdp);
  7786. this.pc.setRemoteDescription(anwser).then(() => {
  7787. log(this.TAG, 'set remote sucess');
  7788. }).catch(e => {
  7789. error(this.TAG, e);
  7790. });
  7791. });
  7792. });
  7793. }).catch(e => {
  7794. error(this.TAG, e);
  7795. });
  7796. }).catch(e => {
  7797. this.dispatch(Events$1.CAPTURE_STREAM_FAILED); //debug.error(this.TAG,e);
  7798. }); //const offerOptions = {};
  7799. /*
  7800. if (typeof this.pc.addTransceiver === 'function') {
  7801. // |direction| seems not working on Safari.
  7802. this.pc.addTransceiver('audio', { direction: 'recvonly' });
  7803. this.pc.addTransceiver('video', { direction: 'recvonly' });
  7804. } else {
  7805. offerOptions.offerToReceiveAudio = true;
  7806. offerOptions.offerToReceiveVideo = true;
  7807. }
  7808. */
  7809. }
  7810. _onIceCandidate(event) {
  7811. if (event.candidate) {
  7812. log('Remote ICE candidate: \n ' + event.candidate.candidate); // Send the candidate to the remote peer
  7813. }
  7814. }
  7815. _onTrack(event) {
  7816. if (this.options.element && event.streams && event.streams.length > 0) {
  7817. this.options.element.srcObject = event.streams[0];
  7818. this._remoteStream = event.streams[0];
  7819. this.dispatch(Events$1.WEBRTC_ON_REMOTE_STREAMS, event);
  7820. } else {
  7821. error('element pararm is failed');
  7822. }
  7823. }
  7824. _onIceCandidateError(event) {
  7825. this.dispatch(Events$1.WEBRTC_ICE_CANDIDATE_ERROR, event);
  7826. }
  7827. _onconnectionstatechange(event) {
  7828. this.dispatch(Events$1.WEBRTC_ON_CONNECTION_STATE_CHANGE, this.pc.connectionState);
  7829. }
  7830. _onDataChannelOpen(event) {
  7831. log(this.TAG, 'ondatachannel open:', event);
  7832. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_OPEN, event);
  7833. }
  7834. _onDataChannelMsg(event) {
  7835. log(this.TAG, 'ondatachannel msg:', event);
  7836. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_MSG, event);
  7837. }
  7838. _onDataChannelErr(event) {
  7839. log(this.TAG, 'ondatachannel err:', event);
  7840. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_ERR, event);
  7841. }
  7842. _onDataChannelClose(event) {
  7843. log(this.TAG, 'ondatachannel close:', event);
  7844. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_CLOSE, event);
  7845. }
  7846. sendMsg(data) {
  7847. if (this.datachannel != null) {
  7848. this.datachannel.send(data);
  7849. } else {
  7850. error(this.TAG, 'data channel is null');
  7851. }
  7852. }
  7853. closeDataChannel() {
  7854. if (this.datachannel) {
  7855. this.datachannel.close();
  7856. this.datachannel = null;
  7857. }
  7858. }
  7859. close() {
  7860. this.closeDataChannel();
  7861. if (this.pc) {
  7862. this.pc.close();
  7863. this.pc = null;
  7864. }
  7865. if (this.options) {
  7866. this.options = null;
  7867. }
  7868. if (this._localStream) {
  7869. this._localStream.getTracks().forEach((track, idx) => {
  7870. track.stop();
  7871. });
  7872. }
  7873. if (this._remoteStream) {
  7874. this._remoteStream.getTracks().forEach((track, idx) => {
  7875. track.stop();
  7876. });
  7877. }
  7878. }
  7879. get remoteStream() {
  7880. return this._remoteStream;
  7881. }
  7882. get localStream() {
  7883. return this._localStream;
  7884. }
  7885. }
  7886. console.log('build date:', BUILD_DATE);
  7887. console.log('version:', VERSION$1);
  7888. const Events = Events$1;
  7889. const Endpoint = RTCEndpoint;
  7890. //连接webrtc
  7891. class ZLMConnect {
  7892. constructor(option) {
  7893. this.token = option.token;
  7894. this.callback = option.callback;
  7895. this.url = option.url;
  7896. this.videoId = option.videoId;
  7897. this.rtcUrl = option.rtcUrl;
  7898. this.successCallback = option.successCallback;
  7899. }
  7900. stateCallBack(eventName, value, desc) {
  7901. let info = {
  7902. type:eventName,
  7903. val: value,
  7904. description:desc
  7905. };
  7906. this.callback(info);
  7907. }
  7908. connect() {
  7909. this.wsOnMessage = this.wsOnMessage.bind(this);
  7910. this.wsOnClose = this.wsOnClose.bind(this);
  7911. this.wsOpen = this.wsOpen.bind(this);
  7912. this.heartBeat = this.heartBeat.bind(this);
  7913. this.startPlay = this.startPlay.bind(this);
  7914. this.ws = new WebSocket(this.url);
  7915. ws = this.ws
  7916. this.ws.binaryType = 'arraybuffer';
  7917. this.ws.onmessage = this.wsOnMessage;
  7918. this.ws.onopen = this.wsOpen;
  7919. this.ws.onclose = this.wsOnClose;
  7920. //this.connectRtc();
  7921. }
  7922. pause() {
  7923. let videoElement = document.getElementById(this.videoId);
  7924. videoElement.pause();
  7925. console.log("webrtc暂停");
  7926. }
  7927. resume() {
  7928. let videoElement = document.getElementById(this.videoId);
  7929. videoElement.play();
  7930. console.log("webrtc继续播放");
  7931. }
  7932. connectRtc() {
  7933. this.player = new Endpoint(
  7934. {
  7935. element: document.getElementById(this.videoId),// video 标签
  7936. debug: true,// 是否打印日志
  7937. zlmsdpUrl:this.rtcUrl,//流地址
  7938. simulcast:false,
  7939. useCamera:false,
  7940. audioEnable:true,
  7941. videoEnable:true,
  7942. recvOnly:true,
  7943. usedatachannel:false,
  7944. successCallback: this.successCallback
  7945. });
  7946. this.player.on(Events.WEBRTC_ON_REMOTE_STREAMS,function(e)
  7947. {//获取到了远端流,可以播放
  7948. console.log('播放成功',e.streams);
  7949. });
  7950. this.player.on(Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED,function(e)
  7951. {// offer anwser 交换失败
  7952. console.log('offer anwser 交换失败',e);
  7953. stop();
  7954. });
  7955. this.player.on(Events.WEBRTC_ON_CONNECTION_STATE_CHANGE,function(state)
  7956. {// RTC 状态变化 ,详情参考 https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
  7957. console.log('当前状态==>',state);
  7958. });
  7959. this.player.on(Events.WEBRTC_ON_DATA_CHANNEL_OPEN,function(event)
  7960. {
  7961. console.log('rtc datachannel 打开 :',event);
  7962. });
  7963. this.player.on(Events.WEBRTC_ON_DATA_CHANNEL_MSG,function(event)
  7964. {
  7965. console.log('rtc datachannel 消息 :',event.data);
  7966. document.getElementById('msgrecv').value = event.data;
  7967. });
  7968. this.player.on(Events.WEBRTC_ON_DATA_CHANNEL_ERR,function(event)
  7969. {
  7970. console.log('rtc datachannel 错误 :',event);
  7971. });
  7972. this.player.on(Events.WEBRTC_ON_DATA_CHANNEL_CLOSE,function(event)
  7973. {
  7974. console.log('rtc datachannel 关闭 :',event);
  7975. });
  7976. let videoElement = document.getElementById(this.videoId);
  7977. videoElement.onplay = this.startPlay;
  7978. }
  7979. startPlay() {
  7980. this.stateCallBack("open", OPEN_SUCCESS, "拉流成功");
  7981. }
  7982. wsOnMessage(event) {
  7983. this.parseProto(event.data);
  7984. }
  7985. switchShapness(level) {
  7986. this.ws.send(makeSharpness(level));
  7987. }
  7988. parseProto (data) {
  7989. let input = new Uint8Array(data);
  7990. if(input[0] == Porto_Header_ID) {
  7991. if(input[23] == MultiLogin_ID) ;
  7992. if(input[23] == Authen_ID) {
  7993. if(CheckVerifyCode(input)) {
  7994. this.connectRtc();
  7995. }
  7996. else {
  7997. console.log("鉴权失败:" + input);
  7998. this.stateCallBack("verifyFailed", verify_Failed, "鉴权失败");
  7999. }
  8000. }
  8001. if(input[23] == ScreenDirection_ID) {
  8002. let direction = CheckScreenDirection(input.slice(24, 24 + 8));
  8003. if(direction == Vertica_ID) {
  8004. this.stateCallBack("screenChange", direction, "安卓卡竖屏");
  8005. }
  8006. if(direction == Landscape_ID) {
  8007. this.stateCallBack("screenChange", direction, "安卓卡横屏");
  8008. }
  8009. }
  8010. }
  8011. }
  8012. heartBeat() {
  8013. this.ws.send("ping");
  8014. }
  8015. wsOpen(event) {
  8016. let sn = "RK3923C1201900139";
  8017. let verifyBuffer = VerifyCode(sn, this.token);
  8018. this.ws.send(verifyBuffer);
  8019. this.switchShapness(4)
  8020. this.heartBeatFlag = setInterval(this.heartBeat, 2000);
  8021. heartBeatFlag = this.heartBeatFlag
  8022. }
  8023. wsOnClose(event) {
  8024. this.stateCallBack("closeEvent", event.code, "WS关闭事件");
  8025. }
  8026. disconnect() {
  8027. if(this.player) {
  8028. this.player.close();
  8029. this.player = null;
  8030. }
  8031. clearInterval(this.heartBeatFlag);
  8032. this.ws.close();
  8033. let videoElement = document.getElementById(this.videoId);
  8034. videoElement.srcObject = null;
  8035. videoElement.load();
  8036. }
  8037. }
  8038. class RtcEngine {
  8039. constructor(options) {
  8040. this.callback = options.callback;
  8041. this.url = options.url;
  8042. this.token = options.token;
  8043. this.videoId = options.videoId;
  8044. this.rtcUrl = options.rtcUrl;
  8045. this.mode = options.mode;
  8046. this.debug = options.debug;
  8047. this.successCallback = options.successCallback;
  8048. }
  8049. checkSupportLevel() {
  8050. let isWebrtcSupported = DetectRTC.isWebRTCSupported;
  8051. let isMseSupported = !!window.MediaSource;
  8052. let isWasmSupported = false;
  8053. if(isWebrtcSupported) {
  8054. console.log("支持webrtc--yes");
  8055. }
  8056. if(isMseSupported) {
  8057. console.log("支持MSE--yes");
  8058. }
  8059. return {
  8060. webrtcSupported:isWebrtcSupported,
  8061. mseSupported:isMseSupported,
  8062. webCodecSupported:isMseSupported,
  8063. wasmSupported:isWasmSupported
  8064. }
  8065. }
  8066. getMode() {
  8067. return this.mode;
  8068. }
  8069. switchShapness(level) {
  8070. if(this.connector != undefined) {
  8071. this.connector.switchShapness(level);
  8072. }
  8073. }
  8074. //优先级webrtc > webcodec > mse > wasm
  8075. checkAndConnect() {
  8076. let supportLevel = this.checkSupportLevel();
  8077. if(supportLevel.webrtcSupported) {
  8078. this.connector = new ZLMConnect(this.rtcOption);
  8079. this.mode = "webrtc";
  8080. }
  8081. else
  8082. if(supportLevel.mseSupported) {
  8083. this.connector = new MseConnect(this.rtcOption);
  8084. this.mode = "mse";
  8085. }
  8086. else
  8087. if(supportLevel.webCodecSupported) {
  8088. this.mode = "webcodec";
  8089. console.log("暂时不支持webcodec");
  8090. }
  8091. else
  8092. if(supportLevel.wasmSupported) {
  8093. this.mode = "wasm";
  8094. console.log("暂时不支持wasm");
  8095. }
  8096. if(this.connector != undefined)
  8097. this.connector.connect();
  8098. }
  8099. connect() {
  8100. this.rtcOption = {
  8101. url:this.url,
  8102. token:this.token,
  8103. videoId:this.videoId,
  8104. callback:this.callback,
  8105. rtcUrl:this.rtcUrl,
  8106. debug:this.debug,
  8107. successCallback: this.successCallback
  8108. };
  8109. if(this.mode != undefined) {
  8110. switch(this.mode) {
  8111. case "mse":this.connector = new MseConnect(this.rtcOption);break;
  8112. case "webrtc":this.connector = new ZLMConnect(this.rtcOption);break;
  8113. default:console.log("暂时不支持的流媒体协议:" + this.mode);break;
  8114. }
  8115. if(this.connector != undefined)
  8116. this.connector.connect();
  8117. }
  8118. else {
  8119. this.checkAndConnect();
  8120. }
  8121. }
  8122. pause() {
  8123. if(this.connector.pause != undefined) {
  8124. this.connector.pause();
  8125. }
  8126. }
  8127. resume() {
  8128. if(this.connector.resume != undefined) {
  8129. this.connector.resume();
  8130. }
  8131. }
  8132. disconnect() {
  8133. this.connector.disconnect();
  8134. }
  8135. }
  8136. return RtcEngine;
  8137. }));