peerjs.js 305 KB

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