peer.js 267 KB

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