peer.js 267 KB

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