simplewebrtc.bundle.js 542 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.SimpleWebRTC = f()}})(function(){var define,module,exports;return (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. module.exports = after
  3. function after(count, callback, err_cb) {
  4. var bail = false
  5. err_cb = err_cb || noop
  6. proxy.count = count
  7. return (count === 0) ? callback() : proxy
  8. function proxy(err, result) {
  9. if (proxy.count <= 0) {
  10. throw new Error('after called too many times')
  11. }
  12. --proxy.count
  13. // after first error, rest are passed to err_cb
  14. if (err) {
  15. bail = true
  16. callback(err)
  17. // future error callbacks will go to error handler
  18. callback = err_cb
  19. } else if (proxy.count === 0 && !bail) {
  20. callback(null, result)
  21. }
  22. }
  23. }
  24. function noop() {}
  25. },{}],2:[function(require,module,exports){
  26. /**
  27. * An abstraction for slicing an arraybuffer even when
  28. * ArrayBuffer.prototype.slice is not supported
  29. *
  30. * @api public
  31. */
  32. module.exports = function(arraybuffer, start, end) {
  33. var bytes = arraybuffer.byteLength;
  34. start = start || 0;
  35. end = end || bytes;
  36. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  37. if (start < 0) { start += bytes; }
  38. if (end < 0) { end += bytes; }
  39. if (end > bytes) { end = bytes; }
  40. if (start >= bytes || start >= end || bytes === 0) {
  41. return new ArrayBuffer(0);
  42. }
  43. var abv = new Uint8Array(arraybuffer);
  44. var result = new Uint8Array(end - start);
  45. for (var i = start, ii = 0; i < end; i++, ii++) {
  46. result[ii] = abv[i];
  47. }
  48. return result.buffer;
  49. };
  50. },{}],3:[function(require,module,exports){
  51. var adapter = require('webrtc-adapter');
  52. module.exports = function (stream, el, options) {
  53. var item;
  54. var URL = window.URL;
  55. var element = el;
  56. var opts = {
  57. autoplay: true,
  58. mirror: false,
  59. muted: false,
  60. audio: false,
  61. disableContextMenu: false
  62. };
  63. if (options) {
  64. for (item in options) {
  65. opts[item] = options[item];
  66. }
  67. }
  68. if (!element) {
  69. element = document.createElement(opts.audio ? 'audio' : 'video');
  70. } else if (element.tagName.toLowerCase() === 'audio') {
  71. opts.audio = true;
  72. }
  73. if (opts.disableContextMenu) {
  74. element.oncontextmenu = function (e) {
  75. e.preventDefault();
  76. };
  77. }
  78. if (opts.autoplay) element.autoplay = 'autoplay';
  79. if (opts.muted) element.muted = true;
  80. if (!opts.audio && opts.mirror) {
  81. ['', 'moz', 'webkit', 'o', 'ms'].forEach(function (prefix) {
  82. var styleName = prefix ? prefix + 'Transform' : 'transform';
  83. element.style[styleName] = 'scaleX(-1)';
  84. });
  85. }
  86. element.srcObject = stream;
  87. return element;
  88. };
  89. },{"webrtc-adapter":90}],4:[function(require,module,exports){
  90. /**
  91. * Expose `Backoff`.
  92. */
  93. module.exports = Backoff;
  94. /**
  95. * Initialize backoff timer with `opts`.
  96. *
  97. * - `min` initial timeout in milliseconds [100]
  98. * - `max` max timeout [10000]
  99. * - `jitter` [0]
  100. * - `factor` [2]
  101. *
  102. * @param {Object} opts
  103. * @api public
  104. */
  105. function Backoff(opts) {
  106. opts = opts || {};
  107. this.ms = opts.min || 100;
  108. this.max = opts.max || 10000;
  109. this.factor = opts.factor || 2;
  110. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  111. this.attempts = 0;
  112. }
  113. /**
  114. * Return the backoff duration.
  115. *
  116. * @return {Number}
  117. * @api public
  118. */
  119. Backoff.prototype.duration = function(){
  120. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  121. if (this.jitter) {
  122. var rand = Math.random();
  123. var deviation = Math.floor(rand * this.jitter * ms);
  124. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  125. }
  126. return Math.min(ms, this.max) | 0;
  127. };
  128. /**
  129. * Reset the number of attempts.
  130. *
  131. * @api public
  132. */
  133. Backoff.prototype.reset = function(){
  134. this.attempts = 0;
  135. };
  136. /**
  137. * Set the minimum duration
  138. *
  139. * @api public
  140. */
  141. Backoff.prototype.setMin = function(min){
  142. this.ms = min;
  143. };
  144. /**
  145. * Set the maximum duration
  146. *
  147. * @api public
  148. */
  149. Backoff.prototype.setMax = function(max){
  150. this.max = max;
  151. };
  152. /**
  153. * Set the jitter
  154. *
  155. * @api public
  156. */
  157. Backoff.prototype.setJitter = function(jitter){
  158. this.jitter = jitter;
  159. };
  160. },{}],5:[function(require,module,exports){
  161. /*
  162. * base64-arraybuffer
  163. * https://github.com/niklasvh/base64-arraybuffer
  164. *
  165. * Copyright (c) 2012 Niklas von Hertzen
  166. * Licensed under the MIT license.
  167. */
  168. (function(chars){
  169. "use strict";
  170. exports.encode = function(arraybuffer) {
  171. var bytes = new Uint8Array(arraybuffer),
  172. i, len = bytes.length, base64 = "";
  173. for (i = 0; i < len; i+=3) {
  174. base64 += chars[bytes[i] >> 2];
  175. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  176. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  177. base64 += chars[bytes[i + 2] & 63];
  178. }
  179. if ((len % 3) === 2) {
  180. base64 = base64.substring(0, base64.length - 1) + "=";
  181. } else if (len % 3 === 1) {
  182. base64 = base64.substring(0, base64.length - 2) + "==";
  183. }
  184. return base64;
  185. };
  186. exports.decode = function(base64) {
  187. var bufferLength = base64.length * 0.75,
  188. len = base64.length, i, p = 0,
  189. encoded1, encoded2, encoded3, encoded4;
  190. if (base64[base64.length - 1] === "=") {
  191. bufferLength--;
  192. if (base64[base64.length - 2] === "=") {
  193. bufferLength--;
  194. }
  195. }
  196. var arraybuffer = new ArrayBuffer(bufferLength),
  197. bytes = new Uint8Array(arraybuffer);
  198. for (i = 0; i < len; i+=4) {
  199. encoded1 = chars.indexOf(base64[i]);
  200. encoded2 = chars.indexOf(base64[i+1]);
  201. encoded3 = chars.indexOf(base64[i+2]);
  202. encoded4 = chars.indexOf(base64[i+3]);
  203. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  204. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  205. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  206. }
  207. return arraybuffer;
  208. };
  209. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  210. },{}],6:[function(require,module,exports){
  211. (function (global){
  212. /**
  213. * Create a blob builder even when vendor prefixes exist
  214. */
  215. var BlobBuilder = global.BlobBuilder
  216. || global.WebKitBlobBuilder
  217. || global.MSBlobBuilder
  218. || global.MozBlobBuilder;
  219. /**
  220. * Check if Blob constructor is supported
  221. */
  222. var blobSupported = (function() {
  223. try {
  224. var a = new Blob(['hi']);
  225. return a.size === 2;
  226. } catch(e) {
  227. return false;
  228. }
  229. })();
  230. /**
  231. * Check if Blob constructor supports ArrayBufferViews
  232. * Fails in Safari 6, so we need to map to ArrayBuffers there.
  233. */
  234. var blobSupportsArrayBufferView = blobSupported && (function() {
  235. try {
  236. var b = new Blob([new Uint8Array([1,2])]);
  237. return b.size === 2;
  238. } catch(e) {
  239. return false;
  240. }
  241. })();
  242. /**
  243. * Check if BlobBuilder is supported
  244. */
  245. var blobBuilderSupported = BlobBuilder
  246. && BlobBuilder.prototype.append
  247. && BlobBuilder.prototype.getBlob;
  248. /**
  249. * Helper function that maps ArrayBufferViews to ArrayBuffers
  250. * Used by BlobBuilder constructor and old browsers that didn't
  251. * support it in the Blob constructor.
  252. */
  253. function mapArrayBufferViews(ary) {
  254. for (var i = 0; i < ary.length; i++) {
  255. var chunk = ary[i];
  256. if (chunk.buffer instanceof ArrayBuffer) {
  257. var buf = chunk.buffer;
  258. // if this is a subarray, make a copy so we only
  259. // include the subarray region from the underlying buffer
  260. if (chunk.byteLength !== buf.byteLength) {
  261. var copy = new Uint8Array(chunk.byteLength);
  262. copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
  263. buf = copy.buffer;
  264. }
  265. ary[i] = buf;
  266. }
  267. }
  268. }
  269. function BlobBuilderConstructor(ary, options) {
  270. options = options || {};
  271. var bb = new BlobBuilder();
  272. mapArrayBufferViews(ary);
  273. for (var i = 0; i < ary.length; i++) {
  274. bb.append(ary[i]);
  275. }
  276. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  277. };
  278. function BlobConstructor(ary, options) {
  279. mapArrayBufferViews(ary);
  280. return new Blob(ary, options || {});
  281. };
  282. module.exports = (function() {
  283. if (blobSupported) {
  284. return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
  285. } else if (blobBuilderSupported) {
  286. return BlobBuilderConstructor;
  287. } else {
  288. return undefined;
  289. }
  290. })();
  291. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  292. },{}],7:[function(require,module,exports){
  293. /**
  294. * Slice reference.
  295. */
  296. var slice = [].slice;
  297. /**
  298. * Bind `obj` to `fn`.
  299. *
  300. * @param {Object} obj
  301. * @param {Function|String} fn or string
  302. * @return {Function}
  303. * @api public
  304. */
  305. module.exports = function(obj, fn){
  306. if ('string' == typeof fn) fn = obj[fn];
  307. if ('function' != typeof fn) throw new Error('bind() requires a function');
  308. var args = slice.call(arguments, 2);
  309. return function(){
  310. return fn.apply(obj, args.concat(slice.call(arguments)));
  311. }
  312. };
  313. },{}],8:[function(require,module,exports){
  314. /**
  315. * Expose `Emitter`.
  316. */
  317. module.exports = Emitter;
  318. /**
  319. * Initialize a new `Emitter`.
  320. *
  321. * @api public
  322. */
  323. function Emitter(obj) {
  324. if (obj) return mixin(obj);
  325. };
  326. /**
  327. * Mixin the emitter properties.
  328. *
  329. * @param {Object} obj
  330. * @return {Object}
  331. * @api private
  332. */
  333. function mixin(obj) {
  334. for (var key in Emitter.prototype) {
  335. obj[key] = Emitter.prototype[key];
  336. }
  337. return obj;
  338. }
  339. /**
  340. * Listen on the given `event` with `fn`.
  341. *
  342. * @param {String} event
  343. * @param {Function} fn
  344. * @return {Emitter}
  345. * @api public
  346. */
  347. Emitter.prototype.on =
  348. Emitter.prototype.addEventListener = function(event, fn){
  349. this._callbacks = this._callbacks || {};
  350. (this._callbacks[event] = this._callbacks[event] || [])
  351. .push(fn);
  352. return this;
  353. };
  354. /**
  355. * Adds an `event` listener that will be invoked a single
  356. * time then automatically removed.
  357. *
  358. * @param {String} event
  359. * @param {Function} fn
  360. * @return {Emitter}
  361. * @api public
  362. */
  363. Emitter.prototype.once = function(event, fn){
  364. var self = this;
  365. this._callbacks = this._callbacks || {};
  366. function on() {
  367. self.off(event, on);
  368. fn.apply(this, arguments);
  369. }
  370. on.fn = fn;
  371. this.on(event, on);
  372. return this;
  373. };
  374. /**
  375. * Remove the given callback for `event` or all
  376. * registered callbacks.
  377. *
  378. * @param {String} event
  379. * @param {Function} fn
  380. * @return {Emitter}
  381. * @api public
  382. */
  383. Emitter.prototype.off =
  384. Emitter.prototype.removeListener =
  385. Emitter.prototype.removeAllListeners =
  386. Emitter.prototype.removeEventListener = function(event, fn){
  387. this._callbacks = this._callbacks || {};
  388. // all
  389. if (0 == arguments.length) {
  390. this._callbacks = {};
  391. return this;
  392. }
  393. // specific event
  394. var callbacks = this._callbacks[event];
  395. if (!callbacks) return this;
  396. // remove all handlers
  397. if (1 == arguments.length) {
  398. delete this._callbacks[event];
  399. return this;
  400. }
  401. // remove specific handler
  402. var cb;
  403. for (var i = 0; i < callbacks.length; i++) {
  404. cb = callbacks[i];
  405. if (cb === fn || cb.fn === fn) {
  406. callbacks.splice(i, 1);
  407. break;
  408. }
  409. }
  410. return this;
  411. };
  412. /**
  413. * Emit `event` with the given args.
  414. *
  415. * @param {String} event
  416. * @param {Mixed} ...
  417. * @return {Emitter}
  418. */
  419. Emitter.prototype.emit = function(event){
  420. this._callbacks = this._callbacks || {};
  421. var args = [].slice.call(arguments, 1)
  422. , callbacks = this._callbacks[event];
  423. if (callbacks) {
  424. callbacks = callbacks.slice(0);
  425. for (var i = 0, len = callbacks.length; i < len; ++i) {
  426. callbacks[i].apply(this, args);
  427. }
  428. }
  429. return this;
  430. };
  431. /**
  432. * Return array of callbacks for `event`.
  433. *
  434. * @param {String} event
  435. * @return {Array}
  436. * @api public
  437. */
  438. Emitter.prototype.listeners = function(event){
  439. this._callbacks = this._callbacks || {};
  440. return this._callbacks[event] || [];
  441. };
  442. /**
  443. * Check if this emitter has `event` handlers.
  444. *
  445. * @param {String} event
  446. * @return {Boolean}
  447. * @api public
  448. */
  449. Emitter.prototype.hasListeners = function(event){
  450. return !! this.listeners(event).length;
  451. };
  452. },{}],9:[function(require,module,exports){
  453. module.exports = function(a, b){
  454. var fn = function(){};
  455. fn.prototype = b.prototype;
  456. a.prototype = new fn;
  457. a.prototype.constructor = a;
  458. };
  459. },{}],10:[function(require,module,exports){
  460. module.exports = require('./lib/');
  461. },{"./lib/":11}],11:[function(require,module,exports){
  462. module.exports = require('./socket');
  463. /**
  464. * Exports parser
  465. *
  466. * @api public
  467. *
  468. */
  469. module.exports.parser = require('engine.io-parser');
  470. },{"./socket":12,"engine.io-parser":24}],12:[function(require,module,exports){
  471. (function (global){
  472. /**
  473. * Module dependencies.
  474. */
  475. var transports = require('./transports');
  476. var Emitter = require('component-emitter');
  477. var debug = require('debug')('engine.io-client:socket');
  478. var index = require('indexof');
  479. var parser = require('engine.io-parser');
  480. var parseuri = require('parseuri');
  481. var parsejson = require('parsejson');
  482. var parseqs = require('parseqs');
  483. /**
  484. * Module exports.
  485. */
  486. module.exports = Socket;
  487. /**
  488. * Noop function.
  489. *
  490. * @api private
  491. */
  492. function noop(){}
  493. /**
  494. * Socket constructor.
  495. *
  496. * @param {String|Object} uri or options
  497. * @param {Object} options
  498. * @api public
  499. */
  500. function Socket(uri, opts){
  501. if (!(this instanceof Socket)) return new Socket(uri, opts);
  502. opts = opts || {};
  503. if (uri && 'object' == typeof uri) {
  504. opts = uri;
  505. uri = null;
  506. }
  507. if (uri) {
  508. uri = parseuri(uri);
  509. opts.host = uri.host;
  510. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  511. opts.port = uri.port;
  512. if (uri.query) opts.query = uri.query;
  513. }
  514. this.secure = null != opts.secure ? opts.secure :
  515. (global.location && 'https:' == location.protocol);
  516. if (opts.host) {
  517. var pieces = opts.host.split(':');
  518. opts.hostname = pieces.shift();
  519. if (pieces.length) {
  520. opts.port = pieces.pop();
  521. } else if (!opts.port) {
  522. // if no port is specified manually, use the protocol default
  523. opts.port = this.secure ? '443' : '80';
  524. }
  525. }
  526. this.agent = opts.agent || false;
  527. this.hostname = opts.hostname ||
  528. (global.location ? location.hostname : 'localhost');
  529. this.port = opts.port || (global.location && location.port ?
  530. location.port :
  531. (this.secure ? 443 : 80));
  532. this.query = opts.query || {};
  533. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  534. this.upgrade = false !== opts.upgrade;
  535. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  536. this.forceJSONP = !!opts.forceJSONP;
  537. this.jsonp = false !== opts.jsonp;
  538. this.forceBase64 = !!opts.forceBase64;
  539. this.enablesXDR = !!opts.enablesXDR;
  540. this.timestampParam = opts.timestampParam || 't';
  541. this.timestampRequests = opts.timestampRequests;
  542. this.transports = opts.transports || ['polling', 'websocket'];
  543. this.readyState = '';
  544. this.writeBuffer = [];
  545. this.callbackBuffer = [];
  546. this.policyPort = opts.policyPort || 843;
  547. this.rememberUpgrade = opts.rememberUpgrade || false;
  548. this.binaryType = null;
  549. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  550. // SSL options for Node.js client
  551. this.pfx = opts.pfx || null;
  552. this.key = opts.key || null;
  553. this.passphrase = opts.passphrase || null;
  554. this.cert = opts.cert || null;
  555. this.ca = opts.ca || null;
  556. this.ciphers = opts.ciphers || null;
  557. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  558. this.open();
  559. }
  560. Socket.priorWebsocketSuccess = false;
  561. /**
  562. * Mix in `Emitter`.
  563. */
  564. Emitter(Socket.prototype);
  565. /**
  566. * Protocol version.
  567. *
  568. * @api public
  569. */
  570. Socket.protocol = parser.protocol; // this is an int
  571. /**
  572. * Expose deps for legacy compatibility
  573. * and standalone browser access.
  574. */
  575. Socket.Socket = Socket;
  576. Socket.Transport = require('./transport');
  577. Socket.transports = require('./transports');
  578. Socket.parser = require('engine.io-parser');
  579. /**
  580. * Creates transport of the given type.
  581. *
  582. * @param {String} transport name
  583. * @return {Transport}
  584. * @api private
  585. */
  586. Socket.prototype.createTransport = function (name) {
  587. debug('creating transport "%s"', name);
  588. var query = clone(this.query);
  589. // append engine.io protocol identifier
  590. query.EIO = parser.protocol;
  591. // transport name
  592. query.transport = name;
  593. // session id if we already have one
  594. if (this.id) query.sid = this.id;
  595. var transport = new transports[name]({
  596. agent: this.agent,
  597. hostname: this.hostname,
  598. port: this.port,
  599. secure: this.secure,
  600. path: this.path,
  601. query: query,
  602. forceJSONP: this.forceJSONP,
  603. jsonp: this.jsonp,
  604. forceBase64: this.forceBase64,
  605. enablesXDR: this.enablesXDR,
  606. timestampRequests: this.timestampRequests,
  607. timestampParam: this.timestampParam,
  608. policyPort: this.policyPort,
  609. socket: this,
  610. pfx: this.pfx,
  611. key: this.key,
  612. passphrase: this.passphrase,
  613. cert: this.cert,
  614. ca: this.ca,
  615. ciphers: this.ciphers,
  616. rejectUnauthorized: this.rejectUnauthorized
  617. });
  618. return transport;
  619. };
  620. function clone (obj) {
  621. var o = {};
  622. for (var i in obj) {
  623. if (obj.hasOwnProperty(i)) {
  624. o[i] = obj[i];
  625. }
  626. }
  627. return o;
  628. }
  629. /**
  630. * Initializes transport to use and starts probe.
  631. *
  632. * @api private
  633. */
  634. Socket.prototype.open = function () {
  635. var transport;
  636. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  637. transport = 'websocket';
  638. } else if (0 == this.transports.length) {
  639. // Emit error on next tick so it can be listened to
  640. var self = this;
  641. setTimeout(function() {
  642. self.emit('error', 'No transports available');
  643. }, 0);
  644. return;
  645. } else {
  646. transport = this.transports[0];
  647. }
  648. this.readyState = 'opening';
  649. // Retry with the next transport if the transport is disabled (jsonp: false)
  650. var transport;
  651. try {
  652. transport = this.createTransport(transport);
  653. } catch (e) {
  654. this.transports.shift();
  655. this.open();
  656. return;
  657. }
  658. transport.open();
  659. this.setTransport(transport);
  660. };
  661. /**
  662. * Sets the current transport. Disables the existing one (if any).
  663. *
  664. * @api private
  665. */
  666. Socket.prototype.setTransport = function(transport){
  667. debug('setting transport %s', transport.name);
  668. var self = this;
  669. if (this.transport) {
  670. debug('clearing existing transport %s', this.transport.name);
  671. this.transport.removeAllListeners();
  672. }
  673. // set up transport
  674. this.transport = transport;
  675. // set up transport listeners
  676. transport
  677. .on('drain', function(){
  678. self.onDrain();
  679. })
  680. .on('packet', function(packet){
  681. self.onPacket(packet);
  682. })
  683. .on('error', function(e){
  684. self.onError(e);
  685. })
  686. .on('close', function(){
  687. self.onClose('transport close');
  688. });
  689. };
  690. /**
  691. * Probes a transport.
  692. *
  693. * @param {String} transport name
  694. * @api private
  695. */
  696. Socket.prototype.probe = function (name) {
  697. debug('probing transport "%s"', name);
  698. var transport = this.createTransport(name, { probe: 1 })
  699. , failed = false
  700. , self = this;
  701. Socket.priorWebsocketSuccess = false;
  702. function onTransportOpen(){
  703. if (self.onlyBinaryUpgrades) {
  704. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  705. failed = failed || upgradeLosesBinary;
  706. }
  707. if (failed) return;
  708. debug('probe transport "%s" opened', name);
  709. transport.send([{ type: 'ping', data: 'probe' }]);
  710. transport.once('packet', function (msg) {
  711. if (failed) return;
  712. if ('pong' == msg.type && 'probe' == msg.data) {
  713. debug('probe transport "%s" pong', name);
  714. self.upgrading = true;
  715. self.emit('upgrading', transport);
  716. if (!transport) return;
  717. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  718. debug('pausing current transport "%s"', self.transport.name);
  719. self.transport.pause(function () {
  720. if (failed) return;
  721. if ('closed' == self.readyState) return;
  722. debug('changing transport and sending upgrade packet');
  723. cleanup();
  724. self.setTransport(transport);
  725. transport.send([{ type: 'upgrade' }]);
  726. self.emit('upgrade', transport);
  727. transport = null;
  728. self.upgrading = false;
  729. self.flush();
  730. });
  731. } else {
  732. debug('probe transport "%s" failed', name);
  733. var err = new Error('probe error');
  734. err.transport = transport.name;
  735. self.emit('upgradeError', err);
  736. }
  737. });
  738. }
  739. function freezeTransport() {
  740. if (failed) return;
  741. // Any callback called by transport should be ignored since now
  742. failed = true;
  743. cleanup();
  744. transport.close();
  745. transport = null;
  746. }
  747. //Handle any error that happens while probing
  748. function onerror(err) {
  749. var error = new Error('probe error: ' + err);
  750. error.transport = transport.name;
  751. freezeTransport();
  752. debug('probe transport "%s" failed because of error: %s', name, err);
  753. self.emit('upgradeError', error);
  754. }
  755. function onTransportClose(){
  756. onerror("transport closed");
  757. }
  758. //When the socket is closed while we're probing
  759. function onclose(){
  760. onerror("socket closed");
  761. }
  762. //When the socket is upgraded while we're probing
  763. function onupgrade(to){
  764. if (transport && to.name != transport.name) {
  765. debug('"%s" works - aborting "%s"', to.name, transport.name);
  766. freezeTransport();
  767. }
  768. }
  769. //Remove all listeners on the transport and on self
  770. function cleanup(){
  771. transport.removeListener('open', onTransportOpen);
  772. transport.removeListener('error', onerror);
  773. transport.removeListener('close', onTransportClose);
  774. self.removeListener('close', onclose);
  775. self.removeListener('upgrading', onupgrade);
  776. }
  777. transport.once('open', onTransportOpen);
  778. transport.once('error', onerror);
  779. transport.once('close', onTransportClose);
  780. this.once('close', onclose);
  781. this.once('upgrading', onupgrade);
  782. transport.open();
  783. };
  784. /**
  785. * Called when connection is deemed open.
  786. *
  787. * @api public
  788. */
  789. Socket.prototype.onOpen = function () {
  790. debug('socket open');
  791. this.readyState = 'open';
  792. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  793. this.emit('open');
  794. this.flush();
  795. // we check for `readyState` in case an `open`
  796. // listener already closed the socket
  797. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  798. debug('starting upgrade probes');
  799. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  800. this.probe(this.upgrades[i]);
  801. }
  802. }
  803. };
  804. /**
  805. * Handles a packet.
  806. *
  807. * @api private
  808. */
  809. Socket.prototype.onPacket = function (packet) {
  810. if ('opening' == this.readyState || 'open' == this.readyState) {
  811. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  812. this.emit('packet', packet);
  813. // Socket is live - any packet counts
  814. this.emit('heartbeat');
  815. switch (packet.type) {
  816. case 'open':
  817. this.onHandshake(parsejson(packet.data));
  818. break;
  819. case 'pong':
  820. this.setPing();
  821. break;
  822. case 'error':
  823. var err = new Error('server error');
  824. err.code = packet.data;
  825. this.emit('error', err);
  826. break;
  827. case 'message':
  828. this.emit('data', packet.data);
  829. this.emit('message', packet.data);
  830. break;
  831. }
  832. } else {
  833. debug('packet received with socket readyState "%s"', this.readyState);
  834. }
  835. };
  836. /**
  837. * Called upon handshake completion.
  838. *
  839. * @param {Object} handshake obj
  840. * @api private
  841. */
  842. Socket.prototype.onHandshake = function (data) {
  843. this.emit('handshake', data);
  844. this.id = data.sid;
  845. this.transport.query.sid = data.sid;
  846. this.upgrades = this.filterUpgrades(data.upgrades);
  847. this.pingInterval = data.pingInterval;
  848. this.pingTimeout = data.pingTimeout;
  849. this.onOpen();
  850. // In case open handler closes socket
  851. if ('closed' == this.readyState) return;
  852. this.setPing();
  853. // Prolong liveness of socket on heartbeat
  854. this.removeListener('heartbeat', this.onHeartbeat);
  855. this.on('heartbeat', this.onHeartbeat);
  856. };
  857. /**
  858. * Resets ping timeout.
  859. *
  860. * @api private
  861. */
  862. Socket.prototype.onHeartbeat = function (timeout) {
  863. clearTimeout(this.pingTimeoutTimer);
  864. var self = this;
  865. self.pingTimeoutTimer = setTimeout(function () {
  866. if ('closed' == self.readyState) return;
  867. self.onClose('ping timeout');
  868. }, timeout || (self.pingInterval + self.pingTimeout));
  869. };
  870. /**
  871. * Pings server every `this.pingInterval` and expects response
  872. * within `this.pingTimeout` or closes connection.
  873. *
  874. * @api private
  875. */
  876. Socket.prototype.setPing = function () {
  877. var self = this;
  878. clearTimeout(self.pingIntervalTimer);
  879. self.pingIntervalTimer = setTimeout(function () {
  880. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  881. self.ping();
  882. self.onHeartbeat(self.pingTimeout);
  883. }, self.pingInterval);
  884. };
  885. /**
  886. * Sends a ping packet.
  887. *
  888. * @api public
  889. */
  890. Socket.prototype.ping = function () {
  891. this.sendPacket('ping');
  892. };
  893. /**
  894. * Called on `drain` event
  895. *
  896. * @api private
  897. */
  898. Socket.prototype.onDrain = function() {
  899. for (var i = 0; i < this.prevBufferLen; i++) {
  900. if (this.callbackBuffer[i]) {
  901. this.callbackBuffer[i]();
  902. }
  903. }
  904. this.writeBuffer.splice(0, this.prevBufferLen);
  905. this.callbackBuffer.splice(0, this.prevBufferLen);
  906. // setting prevBufferLen = 0 is very important
  907. // for example, when upgrading, upgrade packet is sent over,
  908. // and a nonzero prevBufferLen could cause problems on `drain`
  909. this.prevBufferLen = 0;
  910. if (this.writeBuffer.length == 0) {
  911. this.emit('drain');
  912. } else {
  913. this.flush();
  914. }
  915. };
  916. /**
  917. * Flush write buffers.
  918. *
  919. * @api private
  920. */
  921. Socket.prototype.flush = function () {
  922. if ('closed' != this.readyState && this.transport.writable &&
  923. !this.upgrading && this.writeBuffer.length) {
  924. debug('flushing %d packets in socket', this.writeBuffer.length);
  925. this.transport.send(this.writeBuffer);
  926. // keep track of current length of writeBuffer
  927. // splice writeBuffer and callbackBuffer on `drain`
  928. this.prevBufferLen = this.writeBuffer.length;
  929. this.emit('flush');
  930. }
  931. };
  932. /**
  933. * Sends a message.
  934. *
  935. * @param {String} message.
  936. * @param {Function} callback function.
  937. * @return {Socket} for chaining.
  938. * @api public
  939. */
  940. Socket.prototype.write =
  941. Socket.prototype.send = function (msg, fn) {
  942. this.sendPacket('message', msg, fn);
  943. return this;
  944. };
  945. /**
  946. * Sends a packet.
  947. *
  948. * @param {String} packet type.
  949. * @param {String} data.
  950. * @param {Function} callback function.
  951. * @api private
  952. */
  953. Socket.prototype.sendPacket = function (type, data, fn) {
  954. if ('closing' == this.readyState || 'closed' == this.readyState) {
  955. return;
  956. }
  957. var packet = { type: type, data: data };
  958. this.emit('packetCreate', packet);
  959. this.writeBuffer.push(packet);
  960. this.callbackBuffer.push(fn);
  961. this.flush();
  962. };
  963. /**
  964. * Closes the connection.
  965. *
  966. * @api private
  967. */
  968. Socket.prototype.close = function () {
  969. if ('opening' == this.readyState || 'open' == this.readyState) {
  970. this.readyState = 'closing';
  971. var self = this;
  972. function close() {
  973. self.onClose('forced close');
  974. debug('socket closing - telling transport to close');
  975. self.transport.close();
  976. }
  977. function cleanupAndClose() {
  978. self.removeListener('upgrade', cleanupAndClose);
  979. self.removeListener('upgradeError', cleanupAndClose);
  980. close();
  981. }
  982. function waitForUpgrade() {
  983. // wait for upgrade to finish since we can't send packets while pausing a transport
  984. self.once('upgrade', cleanupAndClose);
  985. self.once('upgradeError', cleanupAndClose);
  986. }
  987. if (this.writeBuffer.length) {
  988. this.once('drain', function() {
  989. if (this.upgrading) {
  990. waitForUpgrade();
  991. } else {
  992. close();
  993. }
  994. });
  995. } else if (this.upgrading) {
  996. waitForUpgrade();
  997. } else {
  998. close();
  999. }
  1000. }
  1001. return this;
  1002. };
  1003. /**
  1004. * Called upon transport error
  1005. *
  1006. * @api private
  1007. */
  1008. Socket.prototype.onError = function (err) {
  1009. debug('socket error %j', err);
  1010. Socket.priorWebsocketSuccess = false;
  1011. this.emit('error', err);
  1012. this.onClose('transport error', err);
  1013. };
  1014. /**
  1015. * Called upon transport close.
  1016. *
  1017. * @api private
  1018. */
  1019. Socket.prototype.onClose = function (reason, desc) {
  1020. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  1021. debug('socket close with reason: "%s"', reason);
  1022. var self = this;
  1023. // clear timers
  1024. clearTimeout(this.pingIntervalTimer);
  1025. clearTimeout(this.pingTimeoutTimer);
  1026. // clean buffers in next tick, so developers can still
  1027. // grab the buffers on `close` event
  1028. setTimeout(function() {
  1029. self.writeBuffer = [];
  1030. self.callbackBuffer = [];
  1031. self.prevBufferLen = 0;
  1032. }, 0);
  1033. // stop event from firing again for transport
  1034. this.transport.removeAllListeners('close');
  1035. // ensure transport won't stay open
  1036. this.transport.close();
  1037. // ignore further transport communication
  1038. this.transport.removeAllListeners();
  1039. // set ready state
  1040. this.readyState = 'closed';
  1041. // clear session id
  1042. this.id = null;
  1043. // emit close event
  1044. this.emit('close', reason, desc);
  1045. }
  1046. };
  1047. /**
  1048. * Filters upgrades, returning only those matching client transports.
  1049. *
  1050. * @param {Array} server upgrades
  1051. * @api private
  1052. *
  1053. */
  1054. Socket.prototype.filterUpgrades = function (upgrades) {
  1055. var filteredUpgrades = [];
  1056. for (var i = 0, j = upgrades.length; i<j; i++) {
  1057. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  1058. }
  1059. return filteredUpgrades;
  1060. };
  1061. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1062. },{"./transport":13,"./transports":14,"component-emitter":8,"debug":20,"engine.io-parser":24,"indexof":44,"parsejson":52,"parseqs":53,"parseuri":23}],13:[function(require,module,exports){
  1063. /**
  1064. * Module dependencies.
  1065. */
  1066. var parser = require('engine.io-parser');
  1067. var Emitter = require('component-emitter');
  1068. /**
  1069. * Module exports.
  1070. */
  1071. module.exports = Transport;
  1072. /**
  1073. * Transport abstract constructor.
  1074. *
  1075. * @param {Object} options.
  1076. * @api private
  1077. */
  1078. function Transport (opts) {
  1079. this.path = opts.path;
  1080. this.hostname = opts.hostname;
  1081. this.port = opts.port;
  1082. this.secure = opts.secure;
  1083. this.query = opts.query;
  1084. this.timestampParam = opts.timestampParam;
  1085. this.timestampRequests = opts.timestampRequests;
  1086. this.readyState = '';
  1087. this.agent = opts.agent || false;
  1088. this.socket = opts.socket;
  1089. this.enablesXDR = opts.enablesXDR;
  1090. // SSL options for Node.js client
  1091. this.pfx = opts.pfx;
  1092. this.key = opts.key;
  1093. this.passphrase = opts.passphrase;
  1094. this.cert = opts.cert;
  1095. this.ca = opts.ca;
  1096. this.ciphers = opts.ciphers;
  1097. this.rejectUnauthorized = opts.rejectUnauthorized;
  1098. }
  1099. /**
  1100. * Mix in `Emitter`.
  1101. */
  1102. Emitter(Transport.prototype);
  1103. /**
  1104. * A counter used to prevent collisions in the timestamps used
  1105. * for cache busting.
  1106. */
  1107. Transport.timestamps = 0;
  1108. /**
  1109. * Emits an error.
  1110. *
  1111. * @param {String} str
  1112. * @return {Transport} for chaining
  1113. * @api public
  1114. */
  1115. Transport.prototype.onError = function (msg, desc) {
  1116. var err = new Error(msg);
  1117. err.type = 'TransportError';
  1118. err.description = desc;
  1119. this.emit('error', err);
  1120. return this;
  1121. };
  1122. /**
  1123. * Opens the transport.
  1124. *
  1125. * @api public
  1126. */
  1127. Transport.prototype.open = function () {
  1128. if ('closed' == this.readyState || '' == this.readyState) {
  1129. this.readyState = 'opening';
  1130. this.doOpen();
  1131. }
  1132. return this;
  1133. };
  1134. /**
  1135. * Closes the transport.
  1136. *
  1137. * @api private
  1138. */
  1139. Transport.prototype.close = function () {
  1140. if ('opening' == this.readyState || 'open' == this.readyState) {
  1141. this.doClose();
  1142. this.onClose();
  1143. }
  1144. return this;
  1145. };
  1146. /**
  1147. * Sends multiple packets.
  1148. *
  1149. * @param {Array} packets
  1150. * @api private
  1151. */
  1152. Transport.prototype.send = function(packets){
  1153. if ('open' == this.readyState) {
  1154. this.write(packets);
  1155. } else {
  1156. throw new Error('Transport not open');
  1157. }
  1158. };
  1159. /**
  1160. * Called upon open
  1161. *
  1162. * @api private
  1163. */
  1164. Transport.prototype.onOpen = function () {
  1165. this.readyState = 'open';
  1166. this.writable = true;
  1167. this.emit('open');
  1168. };
  1169. /**
  1170. * Called with data.
  1171. *
  1172. * @param {String} data
  1173. * @api private
  1174. */
  1175. Transport.prototype.onData = function(data){
  1176. var packet = parser.decodePacket(data, this.socket.binaryType);
  1177. this.onPacket(packet);
  1178. };
  1179. /**
  1180. * Called with a decoded packet.
  1181. */
  1182. Transport.prototype.onPacket = function (packet) {
  1183. this.emit('packet', packet);
  1184. };
  1185. /**
  1186. * Called upon close.
  1187. *
  1188. * @api private
  1189. */
  1190. Transport.prototype.onClose = function () {
  1191. this.readyState = 'closed';
  1192. this.emit('close');
  1193. };
  1194. },{"component-emitter":8,"engine.io-parser":24}],14:[function(require,module,exports){
  1195. (function (global){
  1196. /**
  1197. * Module dependencies
  1198. */
  1199. var XMLHttpRequest = require('xmlhttprequest');
  1200. var XHR = require('./polling-xhr');
  1201. var JSONP = require('./polling-jsonp');
  1202. var websocket = require('./websocket');
  1203. /**
  1204. * Export transports.
  1205. */
  1206. exports.polling = polling;
  1207. exports.websocket = websocket;
  1208. /**
  1209. * Polling transport polymorphic constructor.
  1210. * Decides on xhr vs jsonp based on feature detection.
  1211. *
  1212. * @api private
  1213. */
  1214. function polling(opts){
  1215. var xhr;
  1216. var xd = false;
  1217. var xs = false;
  1218. var jsonp = false !== opts.jsonp;
  1219. if (global.location) {
  1220. var isSSL = 'https:' == location.protocol;
  1221. var port = location.port;
  1222. // some user agents have empty `location.port`
  1223. if (!port) {
  1224. port = isSSL ? 443 : 80;
  1225. }
  1226. xd = opts.hostname != location.hostname || port != opts.port;
  1227. xs = opts.secure != isSSL;
  1228. }
  1229. opts.xdomain = xd;
  1230. opts.xscheme = xs;
  1231. xhr = new XMLHttpRequest(opts);
  1232. if ('open' in xhr && !opts.forceJSONP) {
  1233. return new XHR(opts);
  1234. } else {
  1235. if (!jsonp) throw new Error('JSONP disabled');
  1236. return new JSONP(opts);
  1237. }
  1238. }
  1239. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1240. },{"./polling-jsonp":15,"./polling-xhr":16,"./websocket":18,"xmlhttprequest":19}],15:[function(require,module,exports){
  1241. (function (global){
  1242. /**
  1243. * Module requirements.
  1244. */
  1245. var Polling = require('./polling');
  1246. var inherit = require('component-inherit');
  1247. /**
  1248. * Module exports.
  1249. */
  1250. module.exports = JSONPPolling;
  1251. /**
  1252. * Cached regular expressions.
  1253. */
  1254. var rNewline = /\n/g;
  1255. var rEscapedNewline = /\\n/g;
  1256. /**
  1257. * Global JSONP callbacks.
  1258. */
  1259. var callbacks;
  1260. /**
  1261. * Callbacks count.
  1262. */
  1263. var index = 0;
  1264. /**
  1265. * Noop.
  1266. */
  1267. function empty () { }
  1268. /**
  1269. * JSONP Polling constructor.
  1270. *
  1271. * @param {Object} opts.
  1272. * @api public
  1273. */
  1274. function JSONPPolling (opts) {
  1275. Polling.call(this, opts);
  1276. this.query = this.query || {};
  1277. // define global callbacks array if not present
  1278. // we do this here (lazily) to avoid unneeded global pollution
  1279. if (!callbacks) {
  1280. // we need to consider multiple engines in the same page
  1281. if (!global.___eio) global.___eio = [];
  1282. callbacks = global.___eio;
  1283. }
  1284. // callback identifier
  1285. this.index = callbacks.length;
  1286. // add callback to jsonp global
  1287. var self = this;
  1288. callbacks.push(function (msg) {
  1289. self.onData(msg);
  1290. });
  1291. // append to query string
  1292. this.query.j = this.index;
  1293. // prevent spurious errors from being emitted when the window is unloaded
  1294. if (global.document && global.addEventListener) {
  1295. global.addEventListener('beforeunload', function () {
  1296. if (self.script) self.script.onerror = empty;
  1297. }, false);
  1298. }
  1299. }
  1300. /**
  1301. * Inherits from Polling.
  1302. */
  1303. inherit(JSONPPolling, Polling);
  1304. /*
  1305. * JSONP only supports binary as base64 encoded strings
  1306. */
  1307. JSONPPolling.prototype.supportsBinary = false;
  1308. /**
  1309. * Closes the socket.
  1310. *
  1311. * @api private
  1312. */
  1313. JSONPPolling.prototype.doClose = function () {
  1314. if (this.script) {
  1315. this.script.parentNode.removeChild(this.script);
  1316. this.script = null;
  1317. }
  1318. if (this.form) {
  1319. this.form.parentNode.removeChild(this.form);
  1320. this.form = null;
  1321. this.iframe = null;
  1322. }
  1323. Polling.prototype.doClose.call(this);
  1324. };
  1325. /**
  1326. * Starts a poll cycle.
  1327. *
  1328. * @api private
  1329. */
  1330. JSONPPolling.prototype.doPoll = function () {
  1331. var self = this;
  1332. var script = document.createElement('script');
  1333. if (this.script) {
  1334. this.script.parentNode.removeChild(this.script);
  1335. this.script = null;
  1336. }
  1337. script.async = true;
  1338. script.src = this.uri();
  1339. script.onerror = function(e){
  1340. self.onError('jsonp poll error',e);
  1341. };
  1342. var insertAt = document.getElementsByTagName('script')[0];
  1343. insertAt.parentNode.insertBefore(script, insertAt);
  1344. this.script = script;
  1345. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  1346. if (isUAgecko) {
  1347. setTimeout(function () {
  1348. var iframe = document.createElement('iframe');
  1349. document.body.appendChild(iframe);
  1350. document.body.removeChild(iframe);
  1351. }, 100);
  1352. }
  1353. };
  1354. /**
  1355. * Writes with a hidden iframe.
  1356. *
  1357. * @param {String} data to send
  1358. * @param {Function} called upon flush.
  1359. * @api private
  1360. */
  1361. JSONPPolling.prototype.doWrite = function (data, fn) {
  1362. var self = this;
  1363. if (!this.form) {
  1364. var form = document.createElement('form');
  1365. var area = document.createElement('textarea');
  1366. var id = this.iframeId = 'eio_iframe_' + this.index;
  1367. var iframe;
  1368. form.className = 'socketio';
  1369. form.style.position = 'absolute';
  1370. form.style.top = '-1000px';
  1371. form.style.left = '-1000px';
  1372. form.target = id;
  1373. form.method = 'POST';
  1374. form.setAttribute('accept-charset', 'utf-8');
  1375. area.name = 'd';
  1376. form.appendChild(area);
  1377. document.body.appendChild(form);
  1378. this.form = form;
  1379. this.area = area;
  1380. }
  1381. this.form.action = this.uri();
  1382. function complete () {
  1383. initIframe();
  1384. fn();
  1385. }
  1386. function initIframe () {
  1387. if (self.iframe) {
  1388. try {
  1389. self.form.removeChild(self.iframe);
  1390. } catch (e) {
  1391. self.onError('jsonp polling iframe removal error', e);
  1392. }
  1393. }
  1394. try {
  1395. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  1396. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  1397. iframe = document.createElement(html);
  1398. } catch (e) {
  1399. iframe = document.createElement('iframe');
  1400. iframe.name = self.iframeId;
  1401. iframe.src = 'javascript:0';
  1402. }
  1403. iframe.id = self.iframeId;
  1404. self.form.appendChild(iframe);
  1405. self.iframe = iframe;
  1406. }
  1407. initIframe();
  1408. // escape \n to prevent it from being converted into \r\n by some UAs
  1409. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  1410. data = data.replace(rEscapedNewline, '\\\n');
  1411. this.area.value = data.replace(rNewline, '\\n');
  1412. try {
  1413. this.form.submit();
  1414. } catch(e) {}
  1415. if (this.iframe.attachEvent) {
  1416. this.iframe.onreadystatechange = function(){
  1417. if (self.iframe.readyState == 'complete') {
  1418. complete();
  1419. }
  1420. };
  1421. } else {
  1422. this.iframe.onload = complete;
  1423. }
  1424. };
  1425. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1426. },{"./polling":17,"component-inherit":9}],16:[function(require,module,exports){
  1427. (function (global){
  1428. /**
  1429. * Module requirements.
  1430. */
  1431. var XMLHttpRequest = require('xmlhttprequest');
  1432. var Polling = require('./polling');
  1433. var Emitter = require('component-emitter');
  1434. var inherit = require('component-inherit');
  1435. var debug = require('debug')('engine.io-client:polling-xhr');
  1436. /**
  1437. * Module exports.
  1438. */
  1439. module.exports = XHR;
  1440. module.exports.Request = Request;
  1441. /**
  1442. * Empty function
  1443. */
  1444. function empty(){}
  1445. /**
  1446. * XHR Polling constructor.
  1447. *
  1448. * @param {Object} opts
  1449. * @api public
  1450. */
  1451. function XHR(opts){
  1452. Polling.call(this, opts);
  1453. if (global.location) {
  1454. var isSSL = 'https:' == location.protocol;
  1455. var port = location.port;
  1456. // some user agents have empty `location.port`
  1457. if (!port) {
  1458. port = isSSL ? 443 : 80;
  1459. }
  1460. this.xd = opts.hostname != global.location.hostname ||
  1461. port != opts.port;
  1462. this.xs = opts.secure != isSSL;
  1463. }
  1464. }
  1465. /**
  1466. * Inherits from Polling.
  1467. */
  1468. inherit(XHR, Polling);
  1469. /**
  1470. * XHR supports binary
  1471. */
  1472. XHR.prototype.supportsBinary = true;
  1473. /**
  1474. * Creates a request.
  1475. *
  1476. * @param {String} method
  1477. * @api private
  1478. */
  1479. XHR.prototype.request = function(opts){
  1480. opts = opts || {};
  1481. opts.uri = this.uri();
  1482. opts.xd = this.xd;
  1483. opts.xs = this.xs;
  1484. opts.agent = this.agent || false;
  1485. opts.supportsBinary = this.supportsBinary;
  1486. opts.enablesXDR = this.enablesXDR;
  1487. // SSL options for Node.js client
  1488. opts.pfx = this.pfx;
  1489. opts.key = this.key;
  1490. opts.passphrase = this.passphrase;
  1491. opts.cert = this.cert;
  1492. opts.ca = this.ca;
  1493. opts.ciphers = this.ciphers;
  1494. opts.rejectUnauthorized = this.rejectUnauthorized;
  1495. return new Request(opts);
  1496. };
  1497. /**
  1498. * Sends data.
  1499. *
  1500. * @param {String} data to send.
  1501. * @param {Function} called upon flush.
  1502. * @api private
  1503. */
  1504. XHR.prototype.doWrite = function(data, fn){
  1505. var isBinary = typeof data !== 'string' && data !== undefined;
  1506. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  1507. var self = this;
  1508. req.on('success', fn);
  1509. req.on('error', function(err){
  1510. self.onError('xhr post error', err);
  1511. });
  1512. this.sendXhr = req;
  1513. };
  1514. /**
  1515. * Starts a poll cycle.
  1516. *
  1517. * @api private
  1518. */
  1519. XHR.prototype.doPoll = function(){
  1520. debug('xhr poll');
  1521. var req = this.request();
  1522. var self = this;
  1523. req.on('data', function(data){
  1524. self.onData(data);
  1525. });
  1526. req.on('error', function(err){
  1527. self.onError('xhr poll error', err);
  1528. });
  1529. this.pollXhr = req;
  1530. };
  1531. /**
  1532. * Request constructor
  1533. *
  1534. * @param {Object} options
  1535. * @api public
  1536. */
  1537. function Request(opts){
  1538. this.method = opts.method || 'GET';
  1539. this.uri = opts.uri;
  1540. this.xd = !!opts.xd;
  1541. this.xs = !!opts.xs;
  1542. this.async = false !== opts.async;
  1543. this.data = undefined != opts.data ? opts.data : null;
  1544. this.agent = opts.agent;
  1545. this.isBinary = opts.isBinary;
  1546. this.supportsBinary = opts.supportsBinary;
  1547. this.enablesXDR = opts.enablesXDR;
  1548. // SSL options for Node.js client
  1549. this.pfx = opts.pfx;
  1550. this.key = opts.key;
  1551. this.passphrase = opts.passphrase;
  1552. this.cert = opts.cert;
  1553. this.ca = opts.ca;
  1554. this.ciphers = opts.ciphers;
  1555. this.rejectUnauthorized = opts.rejectUnauthorized;
  1556. this.create();
  1557. }
  1558. /**
  1559. * Mix in `Emitter`.
  1560. */
  1561. Emitter(Request.prototype);
  1562. /**
  1563. * Creates the XHR object and sends the request.
  1564. *
  1565. * @api private
  1566. */
  1567. Request.prototype.create = function(){
  1568. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  1569. // SSL options for Node.js client
  1570. opts.pfx = this.pfx;
  1571. opts.key = this.key;
  1572. opts.passphrase = this.passphrase;
  1573. opts.cert = this.cert;
  1574. opts.ca = this.ca;
  1575. opts.ciphers = this.ciphers;
  1576. opts.rejectUnauthorized = this.rejectUnauthorized;
  1577. var xhr = this.xhr = new XMLHttpRequest(opts);
  1578. var self = this;
  1579. try {
  1580. debug('xhr open %s: %s', this.method, this.uri);
  1581. xhr.open(this.method, this.uri, this.async);
  1582. if (this.supportsBinary) {
  1583. // This has to be done after open because Firefox is stupid
  1584. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  1585. xhr.responseType = 'arraybuffer';
  1586. }
  1587. if ('POST' == this.method) {
  1588. try {
  1589. if (this.isBinary) {
  1590. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  1591. } else {
  1592. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  1593. }
  1594. } catch (e) {}
  1595. }
  1596. // ie6 check
  1597. if ('withCredentials' in xhr) {
  1598. xhr.withCredentials = true;
  1599. }
  1600. if (this.hasXDR()) {
  1601. xhr.onload = function(){
  1602. self.onLoad();
  1603. };
  1604. xhr.onerror = function(){
  1605. self.onError(xhr.responseText);
  1606. };
  1607. } else {
  1608. xhr.onreadystatechange = function(){
  1609. if (4 != xhr.readyState) return;
  1610. if (200 == xhr.status || 1223 == xhr.status) {
  1611. self.onLoad();
  1612. } else {
  1613. // make sure the `error` event handler that's user-set
  1614. // does not throw in the same tick and gets caught here
  1615. setTimeout(function(){
  1616. self.onError(xhr.status);
  1617. }, 0);
  1618. }
  1619. };
  1620. }
  1621. debug('xhr data %s', this.data);
  1622. xhr.send(this.data);
  1623. } catch (e) {
  1624. // Need to defer since .create() is called directly fhrom the constructor
  1625. // and thus the 'error' event can only be only bound *after* this exception
  1626. // occurs. Therefore, also, we cannot throw here at all.
  1627. setTimeout(function() {
  1628. self.onError(e);
  1629. }, 0);
  1630. return;
  1631. }
  1632. if (global.document) {
  1633. this.index = Request.requestsCount++;
  1634. Request.requests[this.index] = this;
  1635. }
  1636. };
  1637. /**
  1638. * Called upon successful response.
  1639. *
  1640. * @api private
  1641. */
  1642. Request.prototype.onSuccess = function(){
  1643. this.emit('success');
  1644. this.cleanup();
  1645. };
  1646. /**
  1647. * Called if we have data.
  1648. *
  1649. * @api private
  1650. */
  1651. Request.prototype.onData = function(data){
  1652. this.emit('data', data);
  1653. this.onSuccess();
  1654. };
  1655. /**
  1656. * Called upon error.
  1657. *
  1658. * @api private
  1659. */
  1660. Request.prototype.onError = function(err){
  1661. this.emit('error', err);
  1662. this.cleanup(true);
  1663. };
  1664. /**
  1665. * Cleans up house.
  1666. *
  1667. * @api private
  1668. */
  1669. Request.prototype.cleanup = function(fromError){
  1670. if ('undefined' == typeof this.xhr || null === this.xhr) {
  1671. return;
  1672. }
  1673. // xmlhttprequest
  1674. if (this.hasXDR()) {
  1675. this.xhr.onload = this.xhr.onerror = empty;
  1676. } else {
  1677. this.xhr.onreadystatechange = empty;
  1678. }
  1679. if (fromError) {
  1680. try {
  1681. this.xhr.abort();
  1682. } catch(e) {}
  1683. }
  1684. if (global.document) {
  1685. delete Request.requests[this.index];
  1686. }
  1687. this.xhr = null;
  1688. };
  1689. /**
  1690. * Called upon load.
  1691. *
  1692. * @api private
  1693. */
  1694. Request.prototype.onLoad = function(){
  1695. var data;
  1696. try {
  1697. var contentType;
  1698. try {
  1699. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  1700. } catch (e) {}
  1701. if (contentType === 'application/octet-stream') {
  1702. data = this.xhr.response;
  1703. } else {
  1704. if (!this.supportsBinary) {
  1705. data = this.xhr.responseText;
  1706. } else {
  1707. data = 'ok';
  1708. }
  1709. }
  1710. } catch (e) {
  1711. this.onError(e);
  1712. }
  1713. if (null != data) {
  1714. this.onData(data);
  1715. }
  1716. };
  1717. /**
  1718. * Check if it has XDomainRequest.
  1719. *
  1720. * @api private
  1721. */
  1722. Request.prototype.hasXDR = function(){
  1723. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  1724. };
  1725. /**
  1726. * Aborts the request.
  1727. *
  1728. * @api public
  1729. */
  1730. Request.prototype.abort = function(){
  1731. this.cleanup();
  1732. };
  1733. /**
  1734. * Aborts pending requests when unloading the window. This is needed to prevent
  1735. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  1736. * emitted.
  1737. */
  1738. if (global.document) {
  1739. Request.requestsCount = 0;
  1740. Request.requests = {};
  1741. if (global.attachEvent) {
  1742. global.attachEvent('onunload', unloadHandler);
  1743. } else if (global.addEventListener) {
  1744. global.addEventListener('beforeunload', unloadHandler, false);
  1745. }
  1746. }
  1747. function unloadHandler() {
  1748. for (var i in Request.requests) {
  1749. if (Request.requests.hasOwnProperty(i)) {
  1750. Request.requests[i].abort();
  1751. }
  1752. }
  1753. }
  1754. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1755. },{"./polling":17,"component-emitter":8,"component-inherit":9,"debug":20,"xmlhttprequest":19}],17:[function(require,module,exports){
  1756. /**
  1757. * Module dependencies.
  1758. */
  1759. var Transport = require('../transport');
  1760. var parseqs = require('parseqs');
  1761. var parser = require('engine.io-parser');
  1762. var inherit = require('component-inherit');
  1763. var debug = require('debug')('engine.io-client:polling');
  1764. /**
  1765. * Module exports.
  1766. */
  1767. module.exports = Polling;
  1768. /**
  1769. * Is XHR2 supported?
  1770. */
  1771. var hasXHR2 = (function() {
  1772. var XMLHttpRequest = require('xmlhttprequest');
  1773. var xhr = new XMLHttpRequest({ xdomain: false });
  1774. return null != xhr.responseType;
  1775. })();
  1776. /**
  1777. * Polling interface.
  1778. *
  1779. * @param {Object} opts
  1780. * @api private
  1781. */
  1782. function Polling(opts){
  1783. var forceBase64 = (opts && opts.forceBase64);
  1784. if (!hasXHR2 || forceBase64) {
  1785. this.supportsBinary = false;
  1786. }
  1787. Transport.call(this, opts);
  1788. }
  1789. /**
  1790. * Inherits from Transport.
  1791. */
  1792. inherit(Polling, Transport);
  1793. /**
  1794. * Transport name.
  1795. */
  1796. Polling.prototype.name = 'polling';
  1797. /**
  1798. * Opens the socket (triggers polling). We write a PING message to determine
  1799. * when the transport is open.
  1800. *
  1801. * @api private
  1802. */
  1803. Polling.prototype.doOpen = function(){
  1804. this.poll();
  1805. };
  1806. /**
  1807. * Pauses polling.
  1808. *
  1809. * @param {Function} callback upon buffers are flushed and transport is paused
  1810. * @api private
  1811. */
  1812. Polling.prototype.pause = function(onPause){
  1813. var pending = 0;
  1814. var self = this;
  1815. this.readyState = 'pausing';
  1816. function pause(){
  1817. debug('paused');
  1818. self.readyState = 'paused';
  1819. onPause();
  1820. }
  1821. if (this.polling || !this.writable) {
  1822. var total = 0;
  1823. if (this.polling) {
  1824. debug('we are currently polling - waiting to pause');
  1825. total++;
  1826. this.once('pollComplete', function(){
  1827. debug('pre-pause polling complete');
  1828. --total || pause();
  1829. });
  1830. }
  1831. if (!this.writable) {
  1832. debug('we are currently writing - waiting to pause');
  1833. total++;
  1834. this.once('drain', function(){
  1835. debug('pre-pause writing complete');
  1836. --total || pause();
  1837. });
  1838. }
  1839. } else {
  1840. pause();
  1841. }
  1842. };
  1843. /**
  1844. * Starts polling cycle.
  1845. *
  1846. * @api public
  1847. */
  1848. Polling.prototype.poll = function(){
  1849. debug('polling');
  1850. this.polling = true;
  1851. this.doPoll();
  1852. this.emit('poll');
  1853. };
  1854. /**
  1855. * Overloads onData to detect payloads.
  1856. *
  1857. * @api private
  1858. */
  1859. Polling.prototype.onData = function(data){
  1860. var self = this;
  1861. debug('polling got data %s', data);
  1862. var callback = function(packet, index, total) {
  1863. // if its the first message we consider the transport open
  1864. if ('opening' == self.readyState) {
  1865. self.onOpen();
  1866. }
  1867. // if its a close packet, we close the ongoing requests
  1868. if ('close' == packet.type) {
  1869. self.onClose();
  1870. return false;
  1871. }
  1872. // otherwise bypass onData and handle the message
  1873. self.onPacket(packet);
  1874. };
  1875. // decode payload
  1876. parser.decodePayload(data, this.socket.binaryType, callback);
  1877. // if an event did not trigger closing
  1878. if ('closed' != this.readyState) {
  1879. // if we got data we're not polling
  1880. this.polling = false;
  1881. this.emit('pollComplete');
  1882. if ('open' == this.readyState) {
  1883. this.poll();
  1884. } else {
  1885. debug('ignoring poll - transport state "%s"', this.readyState);
  1886. }
  1887. }
  1888. };
  1889. /**
  1890. * For polling, send a close packet.
  1891. *
  1892. * @api private
  1893. */
  1894. Polling.prototype.doClose = function(){
  1895. var self = this;
  1896. function close(){
  1897. debug('writing close packet');
  1898. self.write([{ type: 'close' }]);
  1899. }
  1900. if ('open' == this.readyState) {
  1901. debug('transport open - closing');
  1902. close();
  1903. } else {
  1904. // in case we're trying to close while
  1905. // handshaking is in progress (GH-164)
  1906. debug('transport not open - deferring close');
  1907. this.once('open', close);
  1908. }
  1909. };
  1910. /**
  1911. * Writes a packets payload.
  1912. *
  1913. * @param {Array} data packets
  1914. * @param {Function} drain callback
  1915. * @api private
  1916. */
  1917. Polling.prototype.write = function(packets){
  1918. var self = this;
  1919. this.writable = false;
  1920. var callbackfn = function() {
  1921. self.writable = true;
  1922. self.emit('drain');
  1923. };
  1924. var self = this;
  1925. parser.encodePayload(packets, this.supportsBinary, function(data) {
  1926. self.doWrite(data, callbackfn);
  1927. });
  1928. };
  1929. /**
  1930. * Generates uri for connection.
  1931. *
  1932. * @api private
  1933. */
  1934. Polling.prototype.uri = function(){
  1935. var query = this.query || {};
  1936. var schema = this.secure ? 'https' : 'http';
  1937. var port = '';
  1938. // cache busting is forced
  1939. if (false !== this.timestampRequests) {
  1940. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  1941. }
  1942. if (!this.supportsBinary && !query.sid) {
  1943. query.b64 = 1;
  1944. }
  1945. query = parseqs.encode(query);
  1946. // avoid port if default for schema
  1947. if (this.port && (('https' == schema && this.port != 443) ||
  1948. ('http' == schema && this.port != 80))) {
  1949. port = ':' + this.port;
  1950. }
  1951. // prepend ? to query
  1952. if (query.length) {
  1953. query = '?' + query;
  1954. }
  1955. return schema + '://' + this.hostname + port + this.path + query;
  1956. };
  1957. },{"../transport":13,"component-inherit":9,"debug":20,"engine.io-parser":24,"parseqs":53,"xmlhttprequest":19}],18:[function(require,module,exports){
  1958. /**
  1959. * Module dependencies.
  1960. */
  1961. var Transport = require('../transport');
  1962. var parser = require('engine.io-parser');
  1963. var parseqs = require('parseqs');
  1964. var inherit = require('component-inherit');
  1965. var debug = require('debug')('engine.io-client:websocket');
  1966. /**
  1967. * `ws` exposes a WebSocket-compatible interface in
  1968. * Node, or the `WebSocket` or `MozWebSocket` globals
  1969. * in the browser.
  1970. */
  1971. var WebSocket = require('ws');
  1972. /**
  1973. * Module exports.
  1974. */
  1975. module.exports = WS;
  1976. /**
  1977. * WebSocket transport constructor.
  1978. *
  1979. * @api {Object} connection options
  1980. * @api public
  1981. */
  1982. function WS(opts){
  1983. var forceBase64 = (opts && opts.forceBase64);
  1984. if (forceBase64) {
  1985. this.supportsBinary = false;
  1986. }
  1987. Transport.call(this, opts);
  1988. }
  1989. /**
  1990. * Inherits from Transport.
  1991. */
  1992. inherit(WS, Transport);
  1993. /**
  1994. * Transport name.
  1995. *
  1996. * @api public
  1997. */
  1998. WS.prototype.name = 'websocket';
  1999. /*
  2000. * WebSockets support binary
  2001. */
  2002. WS.prototype.supportsBinary = true;
  2003. /**
  2004. * Opens socket.
  2005. *
  2006. * @api private
  2007. */
  2008. WS.prototype.doOpen = function(){
  2009. if (!this.check()) {
  2010. // let probe timeout
  2011. return;
  2012. }
  2013. var self = this;
  2014. var uri = this.uri();
  2015. var protocols = void(0);
  2016. var opts = { agent: this.agent };
  2017. // SSL options for Node.js client
  2018. opts.pfx = this.pfx;
  2019. opts.key = this.key;
  2020. opts.passphrase = this.passphrase;
  2021. opts.cert = this.cert;
  2022. opts.ca = this.ca;
  2023. opts.ciphers = this.ciphers;
  2024. opts.rejectUnauthorized = this.rejectUnauthorized;
  2025. this.ws = new WebSocket(uri, protocols, opts);
  2026. if (this.ws.binaryType === undefined) {
  2027. this.supportsBinary = false;
  2028. }
  2029. this.ws.binaryType = 'arraybuffer';
  2030. this.addEventListeners();
  2031. };
  2032. /**
  2033. * Adds event listeners to the socket
  2034. *
  2035. * @api private
  2036. */
  2037. WS.prototype.addEventListeners = function(){
  2038. var self = this;
  2039. this.ws.onopen = function(){
  2040. self.onOpen();
  2041. };
  2042. this.ws.onclose = function(){
  2043. self.onClose();
  2044. };
  2045. this.ws.onmessage = function(ev){
  2046. self.onData(ev.data);
  2047. };
  2048. this.ws.onerror = function(e){
  2049. self.onError('websocket error', e);
  2050. };
  2051. };
  2052. /**
  2053. * Override `onData` to use a timer on iOS.
  2054. * See: https://gist.github.com/mloughran/2052006
  2055. *
  2056. * @api private
  2057. */
  2058. if ('undefined' != typeof navigator
  2059. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  2060. WS.prototype.onData = function(data){
  2061. var self = this;
  2062. setTimeout(function(){
  2063. Transport.prototype.onData.call(self, data);
  2064. }, 0);
  2065. };
  2066. }
  2067. /**
  2068. * Writes data to socket.
  2069. *
  2070. * @param {Array} array of packets.
  2071. * @api private
  2072. */
  2073. WS.prototype.write = function(packets){
  2074. var self = this;
  2075. this.writable = false;
  2076. // encodePacket efficient as it uses WS framing
  2077. // no need for encodePayload
  2078. for (var i = 0, l = packets.length; i < l; i++) {
  2079. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  2080. //Sometimes the websocket has already been closed but the browser didn't
  2081. //have a chance of informing us about it yet, in that case send will
  2082. //throw an error
  2083. try {
  2084. self.ws.send(data);
  2085. } catch (e){
  2086. debug('websocket closed before onclose event');
  2087. }
  2088. });
  2089. }
  2090. function ondrain() {
  2091. self.writable = true;
  2092. self.emit('drain');
  2093. }
  2094. // fake drain
  2095. // defer to next tick to allow Socket to clear writeBuffer
  2096. setTimeout(ondrain, 0);
  2097. };
  2098. /**
  2099. * Called upon close
  2100. *
  2101. * @api private
  2102. */
  2103. WS.prototype.onClose = function(){
  2104. Transport.prototype.onClose.call(this);
  2105. };
  2106. /**
  2107. * Closes socket.
  2108. *
  2109. * @api private
  2110. */
  2111. WS.prototype.doClose = function(){
  2112. if (typeof this.ws !== 'undefined') {
  2113. this.ws.close();
  2114. }
  2115. };
  2116. /**
  2117. * Generates uri for connection.
  2118. *
  2119. * @api private
  2120. */
  2121. WS.prototype.uri = function(){
  2122. var query = this.query || {};
  2123. var schema = this.secure ? 'wss' : 'ws';
  2124. var port = '';
  2125. // avoid port if default for schema
  2126. if (this.port && (('wss' == schema && this.port != 443)
  2127. || ('ws' == schema && this.port != 80))) {
  2128. port = ':' + this.port;
  2129. }
  2130. // append timestamp to URI
  2131. if (this.timestampRequests) {
  2132. query[this.timestampParam] = +new Date;
  2133. }
  2134. // communicate binary support capabilities
  2135. if (!this.supportsBinary) {
  2136. query.b64 = 1;
  2137. }
  2138. query = parseqs.encode(query);
  2139. // prepend ? to query
  2140. if (query.length) {
  2141. query = '?' + query;
  2142. }
  2143. return schema + '://' + this.hostname + port + this.path + query;
  2144. };
  2145. /**
  2146. * Feature detection for WebSocket.
  2147. *
  2148. * @return {Boolean} whether this transport is available.
  2149. * @api public
  2150. */
  2151. WS.prototype.check = function(){
  2152. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  2153. };
  2154. },{"../transport":13,"component-inherit":9,"debug":20,"engine.io-parser":24,"parseqs":53,"ws":101}],19:[function(require,module,exports){
  2155. // browser shim for xmlhttprequest module
  2156. var hasCORS = require('has-cors');
  2157. module.exports = function(opts) {
  2158. var xdomain = opts.xdomain;
  2159. // scheme must be same when usign XDomainRequest
  2160. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  2161. var xscheme = opts.xscheme;
  2162. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  2163. // https://github.com/Automattic/engine.io-client/pull/217
  2164. var enablesXDR = opts.enablesXDR;
  2165. // XMLHttpRequest can be disabled on IE
  2166. try {
  2167. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  2168. return new XMLHttpRequest();
  2169. }
  2170. } catch (e) { }
  2171. // Use XDomainRequest for IE8 if enablesXDR is true
  2172. // because loading bar keeps flashing when using jsonp-polling
  2173. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  2174. try {
  2175. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  2176. return new XDomainRequest();
  2177. }
  2178. } catch (e) { }
  2179. if (!xdomain) {
  2180. try {
  2181. return new ActiveXObject('Microsoft.XMLHTTP');
  2182. } catch(e) { }
  2183. }
  2184. }
  2185. },{"has-cors":43}],20:[function(require,module,exports){
  2186. /**
  2187. * This is the web browser implementation of `debug()`.
  2188. *
  2189. * Expose `debug()` as the module.
  2190. */
  2191. exports = module.exports = require('./debug');
  2192. exports.log = log;
  2193. exports.formatArgs = formatArgs;
  2194. exports.save = save;
  2195. exports.load = load;
  2196. exports.useColors = useColors;
  2197. /**
  2198. * Colors.
  2199. */
  2200. exports.colors = [
  2201. 'lightseagreen',
  2202. 'forestgreen',
  2203. 'goldenrod',
  2204. 'dodgerblue',
  2205. 'darkorchid',
  2206. 'crimson'
  2207. ];
  2208. /**
  2209. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2210. * and the Firebug extension (any Firefox version) are known
  2211. * to support "%c" CSS customizations.
  2212. *
  2213. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2214. */
  2215. function useColors() {
  2216. // is webkit? http://stackoverflow.com/a/16459606/376773
  2217. return ('WebkitAppearance' in document.documentElement.style) ||
  2218. // is firebug? http://stackoverflow.com/a/398120/376773
  2219. (window.console && (console.firebug || (console.exception && console.table))) ||
  2220. // is firefox >= v31?
  2221. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2222. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  2223. }
  2224. /**
  2225. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2226. */
  2227. exports.formatters.j = function(v) {
  2228. return JSON.stringify(v);
  2229. };
  2230. /**
  2231. * Colorize log arguments if enabled.
  2232. *
  2233. * @api public
  2234. */
  2235. function formatArgs() {
  2236. var args = arguments;
  2237. var useColors = this.useColors;
  2238. args[0] = (useColors ? '%c' : '')
  2239. + this.namespace
  2240. + (useColors ? ' %c' : ' ')
  2241. + args[0]
  2242. + (useColors ? '%c ' : ' ')
  2243. + '+' + exports.humanize(this.diff);
  2244. if (!useColors) return args;
  2245. var c = 'color: ' + this.color;
  2246. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  2247. // the final "%c" is somewhat tricky, because there could be other
  2248. // arguments passed either before or after the %c, so we need to
  2249. // figure out the correct index to insert the CSS into
  2250. var index = 0;
  2251. var lastC = 0;
  2252. args[0].replace(/%[a-z%]/g, function(match) {
  2253. if ('%%' === match) return;
  2254. index++;
  2255. if ('%c' === match) {
  2256. // we only are interested in the *last* %c
  2257. // (the user may have provided their own)
  2258. lastC = index;
  2259. }
  2260. });
  2261. args.splice(lastC, 0, c);
  2262. return args;
  2263. }
  2264. /**
  2265. * Invokes `console.log()` when available.
  2266. * No-op when `console.log` is not a "function".
  2267. *
  2268. * @api public
  2269. */
  2270. function log() {
  2271. // This hackery is required for IE8,
  2272. // where the `console.log` function doesn't have 'apply'
  2273. return 'object' == typeof console
  2274. && 'function' == typeof console.log
  2275. && Function.prototype.apply.call(console.log, console, arguments);
  2276. }
  2277. /**
  2278. * Save `namespaces`.
  2279. *
  2280. * @param {String} namespaces
  2281. * @api private
  2282. */
  2283. function save(namespaces) {
  2284. try {
  2285. if (null == namespaces) {
  2286. localStorage.removeItem('debug');
  2287. } else {
  2288. localStorage.debug = namespaces;
  2289. }
  2290. } catch(e) {}
  2291. }
  2292. /**
  2293. * Load `namespaces`.
  2294. *
  2295. * @return {String} returns the previously persisted debug modes
  2296. * @api private
  2297. */
  2298. function load() {
  2299. var r;
  2300. try {
  2301. r = localStorage.debug;
  2302. } catch(e) {}
  2303. return r;
  2304. }
  2305. /**
  2306. * Enable namespaces listed in `localStorage.debug` initially.
  2307. */
  2308. exports.enable(load());
  2309. },{"./debug":21}],21:[function(require,module,exports){
  2310. /**
  2311. * This is the common logic for both the Node.js and web browser
  2312. * implementations of `debug()`.
  2313. *
  2314. * Expose `debug()` as the module.
  2315. */
  2316. exports = module.exports = debug;
  2317. exports.coerce = coerce;
  2318. exports.disable = disable;
  2319. exports.enable = enable;
  2320. exports.enabled = enabled;
  2321. exports.humanize = require('ms');
  2322. /**
  2323. * The currently active debug mode names, and names to skip.
  2324. */
  2325. exports.names = [];
  2326. exports.skips = [];
  2327. /**
  2328. * Map of special "%n" handling functions, for the debug "format" argument.
  2329. *
  2330. * Valid key names are a single, lowercased letter, i.e. "n".
  2331. */
  2332. exports.formatters = {};
  2333. /**
  2334. * Previously assigned color.
  2335. */
  2336. var prevColor = 0;
  2337. /**
  2338. * Previous log timestamp.
  2339. */
  2340. var prevTime;
  2341. /**
  2342. * Select a color.
  2343. *
  2344. * @return {Number}
  2345. * @api private
  2346. */
  2347. function selectColor() {
  2348. return exports.colors[prevColor++ % exports.colors.length];
  2349. }
  2350. /**
  2351. * Create a debugger with the given `namespace`.
  2352. *
  2353. * @param {String} namespace
  2354. * @return {Function}
  2355. * @api public
  2356. */
  2357. function debug(namespace) {
  2358. // define the `disabled` version
  2359. function disabled() {
  2360. }
  2361. disabled.enabled = false;
  2362. // define the `enabled` version
  2363. function enabled() {
  2364. var self = enabled;
  2365. // set `diff` timestamp
  2366. var curr = +new Date();
  2367. var ms = curr - (prevTime || curr);
  2368. self.diff = ms;
  2369. self.prev = prevTime;
  2370. self.curr = curr;
  2371. prevTime = curr;
  2372. // add the `color` if not set
  2373. if (null == self.useColors) self.useColors = exports.useColors();
  2374. if (null == self.color && self.useColors) self.color = selectColor();
  2375. var args = Array.prototype.slice.call(arguments);
  2376. args[0] = exports.coerce(args[0]);
  2377. if ('string' !== typeof args[0]) {
  2378. // anything else let's inspect with %o
  2379. args = ['%o'].concat(args);
  2380. }
  2381. // apply any `formatters` transformations
  2382. var index = 0;
  2383. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  2384. // if we encounter an escaped % then don't increase the array index
  2385. if (match === '%%') return match;
  2386. index++;
  2387. var formatter = exports.formatters[format];
  2388. if ('function' === typeof formatter) {
  2389. var val = args[index];
  2390. match = formatter.call(self, val);
  2391. // now we need to remove `args[index]` since it's inlined in the `format`
  2392. args.splice(index, 1);
  2393. index--;
  2394. }
  2395. return match;
  2396. });
  2397. if ('function' === typeof exports.formatArgs) {
  2398. args = exports.formatArgs.apply(self, args);
  2399. }
  2400. var logFn = enabled.log || exports.log || console.log.bind(console);
  2401. logFn.apply(self, args);
  2402. }
  2403. enabled.enabled = true;
  2404. var fn = exports.enabled(namespace) ? enabled : disabled;
  2405. fn.namespace = namespace;
  2406. return fn;
  2407. }
  2408. /**
  2409. * Enables a debug mode by namespaces. This can include modes
  2410. * separated by a colon and wildcards.
  2411. *
  2412. * @param {String} namespaces
  2413. * @api public
  2414. */
  2415. function enable(namespaces) {
  2416. exports.save(namespaces);
  2417. var split = (namespaces || '').split(/[\s,]+/);
  2418. var len = split.length;
  2419. for (var i = 0; i < len; i++) {
  2420. if (!split[i]) continue; // ignore empty strings
  2421. namespaces = split[i].replace(/\*/g, '.*?');
  2422. if (namespaces[0] === '-') {
  2423. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2424. } else {
  2425. exports.names.push(new RegExp('^' + namespaces + '$'));
  2426. }
  2427. }
  2428. }
  2429. /**
  2430. * Disable debug output.
  2431. *
  2432. * @api public
  2433. */
  2434. function disable() {
  2435. exports.enable('');
  2436. }
  2437. /**
  2438. * Returns true if the given mode name is enabled, false otherwise.
  2439. *
  2440. * @param {String} name
  2441. * @return {Boolean}
  2442. * @api public
  2443. */
  2444. function enabled(name) {
  2445. var i, len;
  2446. for (i = 0, len = exports.skips.length; i < len; i++) {
  2447. if (exports.skips[i].test(name)) {
  2448. return false;
  2449. }
  2450. }
  2451. for (i = 0, len = exports.names.length; i < len; i++) {
  2452. if (exports.names[i].test(name)) {
  2453. return true;
  2454. }
  2455. }
  2456. return false;
  2457. }
  2458. /**
  2459. * Coerce `val`.
  2460. *
  2461. * @param {Mixed} val
  2462. * @return {Mixed}
  2463. * @api private
  2464. */
  2465. function coerce(val) {
  2466. if (val instanceof Error) return val.stack || val.message;
  2467. return val;
  2468. }
  2469. },{"ms":22}],22:[function(require,module,exports){
  2470. /**
  2471. * Helpers.
  2472. */
  2473. var s = 1000;
  2474. var m = s * 60;
  2475. var h = m * 60;
  2476. var d = h * 24;
  2477. var y = d * 365.25;
  2478. /**
  2479. * Parse or format the given `val`.
  2480. *
  2481. * Options:
  2482. *
  2483. * - `long` verbose formatting [false]
  2484. *
  2485. * @param {String|Number} val
  2486. * @param {Object} options
  2487. * @return {String|Number}
  2488. * @api public
  2489. */
  2490. module.exports = function(val, options){
  2491. options = options || {};
  2492. if ('string' == typeof val) return parse(val);
  2493. return options.long
  2494. ? long(val)
  2495. : short(val);
  2496. };
  2497. /**
  2498. * Parse the given `str` and return milliseconds.
  2499. *
  2500. * @param {String} str
  2501. * @return {Number}
  2502. * @api private
  2503. */
  2504. function parse(str) {
  2505. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  2506. if (!match) return;
  2507. var n = parseFloat(match[1]);
  2508. var type = (match[2] || 'ms').toLowerCase();
  2509. switch (type) {
  2510. case 'years':
  2511. case 'year':
  2512. case 'y':
  2513. return n * y;
  2514. case 'days':
  2515. case 'day':
  2516. case 'd':
  2517. return n * d;
  2518. case 'hours':
  2519. case 'hour':
  2520. case 'h':
  2521. return n * h;
  2522. case 'minutes':
  2523. case 'minute':
  2524. case 'm':
  2525. return n * m;
  2526. case 'seconds':
  2527. case 'second':
  2528. case 's':
  2529. return n * s;
  2530. case 'ms':
  2531. return n;
  2532. }
  2533. }
  2534. /**
  2535. * Short format for `ms`.
  2536. *
  2537. * @param {Number} ms
  2538. * @return {String}
  2539. * @api private
  2540. */
  2541. function short(ms) {
  2542. if (ms >= d) return Math.round(ms / d) + 'd';
  2543. if (ms >= h) return Math.round(ms / h) + 'h';
  2544. if (ms >= m) return Math.round(ms / m) + 'm';
  2545. if (ms >= s) return Math.round(ms / s) + 's';
  2546. return ms + 'ms';
  2547. }
  2548. /**
  2549. * Long format for `ms`.
  2550. *
  2551. * @param {Number} ms
  2552. * @return {String}
  2553. * @api private
  2554. */
  2555. function long(ms) {
  2556. return plural(ms, d, 'day')
  2557. || plural(ms, h, 'hour')
  2558. || plural(ms, m, 'minute')
  2559. || plural(ms, s, 'second')
  2560. || ms + ' ms';
  2561. }
  2562. /**
  2563. * Pluralization helper.
  2564. */
  2565. function plural(ms, n, name) {
  2566. if (ms < n) return;
  2567. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  2568. return Math.ceil(ms / n) + ' ' + name + 's';
  2569. }
  2570. },{}],23:[function(require,module,exports){
  2571. /**
  2572. * Parses an URI
  2573. *
  2574. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  2575. * @api private
  2576. */
  2577. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  2578. var parts = [
  2579. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  2580. ];
  2581. module.exports = function parseuri(str) {
  2582. var src = str,
  2583. b = str.indexOf('['),
  2584. e = str.indexOf(']');
  2585. if (b != -1 && e != -1) {
  2586. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  2587. }
  2588. var m = re.exec(str || ''),
  2589. uri = {},
  2590. i = 14;
  2591. while (i--) {
  2592. uri[parts[i]] = m[i] || '';
  2593. }
  2594. if (b != -1 && e != -1) {
  2595. uri.source = src;
  2596. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  2597. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  2598. uri.ipv6uri = true;
  2599. }
  2600. return uri;
  2601. };
  2602. },{}],24:[function(require,module,exports){
  2603. (function (global){
  2604. /**
  2605. * Module dependencies.
  2606. */
  2607. var keys = require('./keys');
  2608. var hasBinary = require('has-binary');
  2609. var sliceBuffer = require('arraybuffer.slice');
  2610. var base64encoder = require('base64-arraybuffer');
  2611. var after = require('after');
  2612. var utf8 = require('utf8');
  2613. /**
  2614. * Check if we are running an android browser. That requires us to use
  2615. * ArrayBuffer with polling transports...
  2616. *
  2617. * http://ghinda.net/jpeg-blob-ajax-android/
  2618. */
  2619. var isAndroid = navigator.userAgent.match(/Android/i);
  2620. /**
  2621. * Check if we are running in PhantomJS.
  2622. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  2623. * https://github.com/ariya/phantomjs/issues/11395
  2624. * @type boolean
  2625. */
  2626. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  2627. /**
  2628. * When true, avoids using Blobs to encode payloads.
  2629. * @type boolean
  2630. */
  2631. var dontSendBlobs = isAndroid || isPhantomJS;
  2632. /**
  2633. * Current protocol version.
  2634. */
  2635. exports.protocol = 3;
  2636. /**
  2637. * Packet types.
  2638. */
  2639. var packets = exports.packets = {
  2640. open: 0 // non-ws
  2641. , close: 1 // non-ws
  2642. , ping: 2
  2643. , pong: 3
  2644. , message: 4
  2645. , upgrade: 5
  2646. , noop: 6
  2647. };
  2648. var packetslist = keys(packets);
  2649. /**
  2650. * Premade error packet.
  2651. */
  2652. var err = { type: 'error', data: 'parser error' };
  2653. /**
  2654. * Create a blob api even for blob builder when vendor prefixes exist
  2655. */
  2656. var Blob = require('blob');
  2657. /**
  2658. * Encodes a packet.
  2659. *
  2660. * <packet type id> [ <data> ]
  2661. *
  2662. * Example:
  2663. *
  2664. * 5hello world
  2665. * 3
  2666. * 4
  2667. *
  2668. * Binary is encoded in an identical principle
  2669. *
  2670. * @api private
  2671. */
  2672. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  2673. if ('function' == typeof supportsBinary) {
  2674. callback = supportsBinary;
  2675. supportsBinary = false;
  2676. }
  2677. if ('function' == typeof utf8encode) {
  2678. callback = utf8encode;
  2679. utf8encode = null;
  2680. }
  2681. var data = (packet.data === undefined)
  2682. ? undefined
  2683. : packet.data.buffer || packet.data;
  2684. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  2685. return encodeArrayBuffer(packet, supportsBinary, callback);
  2686. } else if (Blob && data instanceof global.Blob) {
  2687. return encodeBlob(packet, supportsBinary, callback);
  2688. }
  2689. // might be an object with { base64: true, data: dataAsBase64String }
  2690. if (data && data.base64) {
  2691. return encodeBase64Object(packet, callback);
  2692. }
  2693. // Sending data as a utf-8 string
  2694. var encoded = packets[packet.type];
  2695. // data fragment is optional
  2696. if (undefined !== packet.data) {
  2697. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  2698. }
  2699. return callback('' + encoded);
  2700. };
  2701. function encodeBase64Object(packet, callback) {
  2702. // packet data is an object { base64: true, data: dataAsBase64String }
  2703. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  2704. return callback(message);
  2705. }
  2706. /**
  2707. * Encode packet helpers for binary types
  2708. */
  2709. function encodeArrayBuffer(packet, supportsBinary, callback) {
  2710. if (!supportsBinary) {
  2711. return exports.encodeBase64Packet(packet, callback);
  2712. }
  2713. var data = packet.data;
  2714. var contentArray = new Uint8Array(data);
  2715. var resultBuffer = new Uint8Array(1 + data.byteLength);
  2716. resultBuffer[0] = packets[packet.type];
  2717. for (var i = 0; i < contentArray.length; i++) {
  2718. resultBuffer[i+1] = contentArray[i];
  2719. }
  2720. return callback(resultBuffer.buffer);
  2721. }
  2722. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  2723. if (!supportsBinary) {
  2724. return exports.encodeBase64Packet(packet, callback);
  2725. }
  2726. var fr = new FileReader();
  2727. fr.onload = function() {
  2728. packet.data = fr.result;
  2729. exports.encodePacket(packet, supportsBinary, true, callback);
  2730. };
  2731. return fr.readAsArrayBuffer(packet.data);
  2732. }
  2733. function encodeBlob(packet, supportsBinary, callback) {
  2734. if (!supportsBinary) {
  2735. return exports.encodeBase64Packet(packet, callback);
  2736. }
  2737. if (dontSendBlobs) {
  2738. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  2739. }
  2740. var length = new Uint8Array(1);
  2741. length[0] = packets[packet.type];
  2742. var blob = new Blob([length.buffer, packet.data]);
  2743. return callback(blob);
  2744. }
  2745. /**
  2746. * Encodes a packet with binary data in a base64 string
  2747. *
  2748. * @param {Object} packet, has `type` and `data`
  2749. * @return {String} base64 encoded message
  2750. */
  2751. exports.encodeBase64Packet = function(packet, callback) {
  2752. var message = 'b' + exports.packets[packet.type];
  2753. if (Blob && packet.data instanceof Blob) {
  2754. var fr = new FileReader();
  2755. fr.onload = function() {
  2756. var b64 = fr.result.split(',')[1];
  2757. callback(message + b64);
  2758. };
  2759. return fr.readAsDataURL(packet.data);
  2760. }
  2761. var b64data;
  2762. try {
  2763. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  2764. } catch (e) {
  2765. // iPhone Safari doesn't let you apply with typed arrays
  2766. var typed = new Uint8Array(packet.data);
  2767. var basic = new Array(typed.length);
  2768. for (var i = 0; i < typed.length; i++) {
  2769. basic[i] = typed[i];
  2770. }
  2771. b64data = String.fromCharCode.apply(null, basic);
  2772. }
  2773. message += global.btoa(b64data);
  2774. return callback(message);
  2775. };
  2776. /**
  2777. * Decodes a packet. Changes format to Blob if requested.
  2778. *
  2779. * @return {Object} with `type` and `data` (if any)
  2780. * @api private
  2781. */
  2782. exports.decodePacket = function (data, binaryType, utf8decode) {
  2783. // String data
  2784. if (typeof data == 'string' || data === undefined) {
  2785. if (data.charAt(0) == 'b') {
  2786. return exports.decodeBase64Packet(data.substr(1), binaryType);
  2787. }
  2788. if (utf8decode) {
  2789. try {
  2790. data = utf8.decode(data);
  2791. } catch (e) {
  2792. return err;
  2793. }
  2794. }
  2795. var type = data.charAt(0);
  2796. if (Number(type) != type || !packetslist[type]) {
  2797. return err;
  2798. }
  2799. if (data.length > 1) {
  2800. return { type: packetslist[type], data: data.substring(1) };
  2801. } else {
  2802. return { type: packetslist[type] };
  2803. }
  2804. }
  2805. var asArray = new Uint8Array(data);
  2806. var type = asArray[0];
  2807. var rest = sliceBuffer(data, 1);
  2808. if (Blob && binaryType === 'blob') {
  2809. rest = new Blob([rest]);
  2810. }
  2811. return { type: packetslist[type], data: rest };
  2812. };
  2813. /**
  2814. * Decodes a packet encoded in a base64 string
  2815. *
  2816. * @param {String} base64 encoded message
  2817. * @return {Object} with `type` and `data` (if any)
  2818. */
  2819. exports.decodeBase64Packet = function(msg, binaryType) {
  2820. var type = packetslist[msg.charAt(0)];
  2821. if (!global.ArrayBuffer) {
  2822. return { type: type, data: { base64: true, data: msg.substr(1) } };
  2823. }
  2824. var data = base64encoder.decode(msg.substr(1));
  2825. if (binaryType === 'blob' && Blob) {
  2826. data = new Blob([data]);
  2827. }
  2828. return { type: type, data: data };
  2829. };
  2830. /**
  2831. * Encodes multiple messages (payload).
  2832. *
  2833. * <length>:data
  2834. *
  2835. * Example:
  2836. *
  2837. * 11:hello world2:hi
  2838. *
  2839. * If any contents are binary, they will be encoded as base64 strings. Base64
  2840. * encoded strings are marked with a b before the length specifier
  2841. *
  2842. * @param {Array} packets
  2843. * @api private
  2844. */
  2845. exports.encodePayload = function (packets, supportsBinary, callback) {
  2846. if (typeof supportsBinary == 'function') {
  2847. callback = supportsBinary;
  2848. supportsBinary = null;
  2849. }
  2850. var isBinary = hasBinary(packets);
  2851. if (supportsBinary && isBinary) {
  2852. if (Blob && !dontSendBlobs) {
  2853. return exports.encodePayloadAsBlob(packets, callback);
  2854. }
  2855. return exports.encodePayloadAsArrayBuffer(packets, callback);
  2856. }
  2857. if (!packets.length) {
  2858. return callback('0:');
  2859. }
  2860. function setLengthHeader(message) {
  2861. return message.length + ':' + message;
  2862. }
  2863. function encodeOne(packet, doneCallback) {
  2864. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  2865. doneCallback(null, setLengthHeader(message));
  2866. });
  2867. }
  2868. map(packets, encodeOne, function(err, results) {
  2869. return callback(results.join(''));
  2870. });
  2871. };
  2872. /**
  2873. * Async array map using after
  2874. */
  2875. function map(ary, each, done) {
  2876. var result = new Array(ary.length);
  2877. var next = after(ary.length, done);
  2878. var eachWithIndex = function(i, el, cb) {
  2879. each(el, function(error, msg) {
  2880. result[i] = msg;
  2881. cb(error, result);
  2882. });
  2883. };
  2884. for (var i = 0; i < ary.length; i++) {
  2885. eachWithIndex(i, ary[i], next);
  2886. }
  2887. }
  2888. /*
  2889. * Decodes data when a payload is maybe expected. Possible binary contents are
  2890. * decoded from their base64 representation
  2891. *
  2892. * @param {String} data, callback method
  2893. * @api public
  2894. */
  2895. exports.decodePayload = function (data, binaryType, callback) {
  2896. if (typeof data != 'string') {
  2897. return exports.decodePayloadAsBinary(data, binaryType, callback);
  2898. }
  2899. if (typeof binaryType === 'function') {
  2900. callback = binaryType;
  2901. binaryType = null;
  2902. }
  2903. var packet;
  2904. if (data == '') {
  2905. // parser error - ignoring payload
  2906. return callback(err, 0, 1);
  2907. }
  2908. var length = ''
  2909. , n, msg;
  2910. for (var i = 0, l = data.length; i < l; i++) {
  2911. var chr = data.charAt(i);
  2912. if (':' != chr) {
  2913. length += chr;
  2914. } else {
  2915. if ('' == length || (length != (n = Number(length)))) {
  2916. // parser error - ignoring payload
  2917. return callback(err, 0, 1);
  2918. }
  2919. msg = data.substr(i + 1, n);
  2920. if (length != msg.length) {
  2921. // parser error - ignoring payload
  2922. return callback(err, 0, 1);
  2923. }
  2924. if (msg.length) {
  2925. packet = exports.decodePacket(msg, binaryType, true);
  2926. if (err.type == packet.type && err.data == packet.data) {
  2927. // parser error in individual packet - ignoring payload
  2928. return callback(err, 0, 1);
  2929. }
  2930. var ret = callback(packet, i + n, l);
  2931. if (false === ret) return;
  2932. }
  2933. // advance cursor
  2934. i += n;
  2935. length = '';
  2936. }
  2937. }
  2938. if (length != '') {
  2939. // parser error - ignoring payload
  2940. return callback(err, 0, 1);
  2941. }
  2942. };
  2943. /**
  2944. * Encodes multiple messages (payload) as binary.
  2945. *
  2946. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  2947. * 255><data>
  2948. *
  2949. * Example:
  2950. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  2951. *
  2952. * @param {Array} packets
  2953. * @return {ArrayBuffer} encoded payload
  2954. * @api private
  2955. */
  2956. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  2957. if (!packets.length) {
  2958. return callback(new ArrayBuffer(0));
  2959. }
  2960. function encodeOne(packet, doneCallback) {
  2961. exports.encodePacket(packet, true, true, function(data) {
  2962. return doneCallback(null, data);
  2963. });
  2964. }
  2965. map(packets, encodeOne, function(err, encodedPackets) {
  2966. var totalLength = encodedPackets.reduce(function(acc, p) {
  2967. var len;
  2968. if (typeof p === 'string'){
  2969. len = p.length;
  2970. } else {
  2971. len = p.byteLength;
  2972. }
  2973. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  2974. }, 0);
  2975. var resultArray = new Uint8Array(totalLength);
  2976. var bufferIndex = 0;
  2977. encodedPackets.forEach(function(p) {
  2978. var isString = typeof p === 'string';
  2979. var ab = p;
  2980. if (isString) {
  2981. var view = new Uint8Array(p.length);
  2982. for (var i = 0; i < p.length; i++) {
  2983. view[i] = p.charCodeAt(i);
  2984. }
  2985. ab = view.buffer;
  2986. }
  2987. if (isString) { // not true binary
  2988. resultArray[bufferIndex++] = 0;
  2989. } else { // true binary
  2990. resultArray[bufferIndex++] = 1;
  2991. }
  2992. var lenStr = ab.byteLength.toString();
  2993. for (var i = 0; i < lenStr.length; i++) {
  2994. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  2995. }
  2996. resultArray[bufferIndex++] = 255;
  2997. var view = new Uint8Array(ab);
  2998. for (var i = 0; i < view.length; i++) {
  2999. resultArray[bufferIndex++] = view[i];
  3000. }
  3001. });
  3002. return callback(resultArray.buffer);
  3003. });
  3004. };
  3005. /**
  3006. * Encode as Blob
  3007. */
  3008. exports.encodePayloadAsBlob = function(packets, callback) {
  3009. function encodeOne(packet, doneCallback) {
  3010. exports.encodePacket(packet, true, true, function(encoded) {
  3011. var binaryIdentifier = new Uint8Array(1);
  3012. binaryIdentifier[0] = 1;
  3013. if (typeof encoded === 'string') {
  3014. var view = new Uint8Array(encoded.length);
  3015. for (var i = 0; i < encoded.length; i++) {
  3016. view[i] = encoded.charCodeAt(i);
  3017. }
  3018. encoded = view.buffer;
  3019. binaryIdentifier[0] = 0;
  3020. }
  3021. var len = (encoded instanceof ArrayBuffer)
  3022. ? encoded.byteLength
  3023. : encoded.size;
  3024. var lenStr = len.toString();
  3025. var lengthAry = new Uint8Array(lenStr.length + 1);
  3026. for (var i = 0; i < lenStr.length; i++) {
  3027. lengthAry[i] = parseInt(lenStr[i]);
  3028. }
  3029. lengthAry[lenStr.length] = 255;
  3030. if (Blob) {
  3031. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  3032. doneCallback(null, blob);
  3033. }
  3034. });
  3035. }
  3036. map(packets, encodeOne, function(err, results) {
  3037. return callback(new Blob(results));
  3038. });
  3039. };
  3040. /*
  3041. * Decodes data when a payload is maybe expected. Strings are decoded by
  3042. * interpreting each byte as a key code for entries marked to start with 0. See
  3043. * description of encodePayloadAsBinary
  3044. *
  3045. * @param {ArrayBuffer} data, callback method
  3046. * @api public
  3047. */
  3048. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  3049. if (typeof binaryType === 'function') {
  3050. callback = binaryType;
  3051. binaryType = null;
  3052. }
  3053. var bufferTail = data;
  3054. var buffers = [];
  3055. var numberTooLong = false;
  3056. while (bufferTail.byteLength > 0) {
  3057. var tailArray = new Uint8Array(bufferTail);
  3058. var isString = tailArray[0] === 0;
  3059. var msgLength = '';
  3060. for (var i = 1; ; i++) {
  3061. if (tailArray[i] == 255) break;
  3062. if (msgLength.length > 310) {
  3063. numberTooLong = true;
  3064. break;
  3065. }
  3066. msgLength += tailArray[i];
  3067. }
  3068. if(numberTooLong) return callback(err, 0, 1);
  3069. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  3070. msgLength = parseInt(msgLength);
  3071. var msg = sliceBuffer(bufferTail, 0, msgLength);
  3072. if (isString) {
  3073. try {
  3074. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  3075. } catch (e) {
  3076. // iPhone Safari doesn't let you apply to typed arrays
  3077. var typed = new Uint8Array(msg);
  3078. msg = '';
  3079. for (var i = 0; i < typed.length; i++) {
  3080. msg += String.fromCharCode(typed[i]);
  3081. }
  3082. }
  3083. }
  3084. buffers.push(msg);
  3085. bufferTail = sliceBuffer(bufferTail, msgLength);
  3086. }
  3087. var total = buffers.length;
  3088. buffers.forEach(function(buffer, i) {
  3089. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  3090. });
  3091. };
  3092. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3093. },{"./keys":25,"after":1,"arraybuffer.slice":2,"base64-arraybuffer":5,"blob":6,"has-binary":41,"utf8":86}],25:[function(require,module,exports){
  3094. /**
  3095. * Gets the keys for an object.
  3096. *
  3097. * @return {Array} keys
  3098. * @api private
  3099. */
  3100. module.exports = Object.keys || function keys (obj){
  3101. var arr = [];
  3102. var has = Object.prototype.hasOwnProperty;
  3103. for (var i in obj) {
  3104. if (has.call(obj, i)) {
  3105. arr.push(i);
  3106. }
  3107. }
  3108. return arr;
  3109. };
  3110. },{}],26:[function(require,module,exports){
  3111. var WildEmitter = require('wildemitter');
  3112. var util = require('util');
  3113. function Sender(opts) {
  3114. WildEmitter.call(this);
  3115. var options = opts || {};
  3116. this.config = {
  3117. chunksize: 16384,
  3118. pacing: 0
  3119. };
  3120. // set our config from options
  3121. var item;
  3122. for (item in options) {
  3123. this.config[item] = options[item];
  3124. }
  3125. this.file = null;
  3126. this.channel = null;
  3127. }
  3128. util.inherits(Sender, WildEmitter);
  3129. Sender.prototype.send = function (file, channel) {
  3130. var self = this;
  3131. this.file = file;
  3132. this.channel = channel;
  3133. var usePoll = typeof channel.bufferedAmountLowThreshold !== 'number';
  3134. var offset = 0;
  3135. var sliceFile = function() {
  3136. var reader = new window.FileReader();
  3137. reader.onload = (function() {
  3138. return function(e) {
  3139. self.channel.send(e.target.result);
  3140. self.emit('progress', offset, file.size, e.target.result);
  3141. if (file.size > offset + e.target.result.byteLength) {
  3142. if (usePoll) {
  3143. window.setTimeout(sliceFile, self.config.pacing);
  3144. } else if (channel.bufferedAmount <= channel.bufferedAmountLowThreshold) {
  3145. window.setTimeout(sliceFile, 0);
  3146. } else {
  3147. // wait for bufferedAmountLow to fire
  3148. }
  3149. } else {
  3150. self.emit('progress', file.size, file.size, null);
  3151. self.emit('sentFile');
  3152. }
  3153. offset = offset + self.config.chunksize;
  3154. };
  3155. })(file);
  3156. var slice = file.slice(offset, offset + self.config.chunksize);
  3157. reader.readAsArrayBuffer(slice);
  3158. };
  3159. if (!usePoll) {
  3160. channel.bufferedAmountLowThreshold = 8 * this.config.chunksize;
  3161. channel.addEventListener('bufferedamountlow', sliceFile);
  3162. }
  3163. window.setTimeout(sliceFile, 0);
  3164. };
  3165. function Receiver() {
  3166. WildEmitter.call(this);
  3167. this.receiveBuffer = [];
  3168. this.received = 0;
  3169. this.metadata = {};
  3170. this.channel = null;
  3171. }
  3172. util.inherits(Receiver, WildEmitter);
  3173. Receiver.prototype.receive = function (metadata, channel) {
  3174. var self = this;
  3175. if (metadata) {
  3176. this.metadata = metadata;
  3177. }
  3178. this.channel = channel;
  3179. // chrome only supports arraybuffers and those make it easier to calc the hash
  3180. channel.binaryType = 'arraybuffer';
  3181. this.channel.onmessage = function (event) {
  3182. var len = event.data.byteLength;
  3183. self.received += len;
  3184. self.receiveBuffer.push(event.data);
  3185. self.emit('progress', self.received, self.metadata.size, event.data);
  3186. if (self.received === self.metadata.size) {
  3187. self.emit('receivedFile', new window.Blob(self.receiveBuffer), self.metadata);
  3188. self.receiveBuffer = []; // discard receivebuffer
  3189. } else if (self.received > self.metadata.size) {
  3190. // FIXME
  3191. console.error('received more than expected, discarding...');
  3192. self.receiveBuffer = []; // just discard...
  3193. }
  3194. };
  3195. };
  3196. module.exports = {};
  3197. module.exports.support = typeof window !== 'undefined' && window && window.File && window.FileReader && window.Blob;
  3198. module.exports.Sender = Sender;
  3199. module.exports.Receiver = Receiver;
  3200. },{"util":89,"wildemitter":100}],27:[function(require,module,exports){
  3201. // getScreenMedia helper by @HenrikJoreteg
  3202. var getUserMedia = require('getusermedia');
  3203. // cache for constraints and callback
  3204. var cache = {};
  3205. module.exports = function (constraints, cb) {
  3206. var hasConstraints = arguments.length === 2;
  3207. var callback = hasConstraints ? cb : constraints;
  3208. var error;
  3209. if (typeof window === 'undefined' || window.location.protocol === 'http:') {
  3210. error = new Error('NavigatorUserMediaError');
  3211. error.name = 'HTTPS_REQUIRED';
  3212. return callback(error);
  3213. }
  3214. if (window.navigator.userAgent.match('Chrome')) {
  3215. var chromever = parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1], 10);
  3216. var maxver = 33;
  3217. var isCef = !window.chrome.webstore;
  3218. // "known" crash in chrome 34 and 35 on linux
  3219. if (window.navigator.userAgent.match('Linux')) maxver = 35;
  3220. // check that the extension is installed by looking for a
  3221. // sessionStorage variable that contains the extension id
  3222. // this has to be set after installation unless the contest
  3223. // script does that
  3224. if (sessionStorage.getScreenMediaJSExtensionId) {
  3225. chrome.runtime.sendMessage(sessionStorage.getScreenMediaJSExtensionId,
  3226. {type:'getScreen', id: 1}, null,
  3227. function (data) {
  3228. if (!data || data.sourceId === '') { // user canceled
  3229. var error = new Error('NavigatorUserMediaError');
  3230. error.name = 'PERMISSION_DENIED';
  3231. callback(error);
  3232. } else {
  3233. constraints = (hasConstraints && constraints) || {audio: false, video: {
  3234. mandatory: {
  3235. chromeMediaSource: 'desktop',
  3236. maxWidth: window.screen.width,
  3237. maxHeight: window.screen.height,
  3238. maxFrameRate: 3
  3239. }
  3240. }};
  3241. constraints.video.mandatory.chromeMediaSourceId = data.sourceId;
  3242. getUserMedia(constraints, callback);
  3243. }
  3244. }
  3245. );
  3246. } else if (window.cefGetScreenMedia) {
  3247. //window.cefGetScreenMedia is experimental - may be removed without notice
  3248. window.cefGetScreenMedia(function(sourceId) {
  3249. if (!sourceId) {
  3250. var error = new Error('cefGetScreenMediaError');
  3251. error.name = 'CEF_GETSCREENMEDIA_CANCELED';
  3252. callback(error);
  3253. } else {
  3254. constraints = (hasConstraints && constraints) || {audio: false, video: {
  3255. mandatory: {
  3256. chromeMediaSource: 'desktop',
  3257. maxWidth: window.screen.width,
  3258. maxHeight: window.screen.height,
  3259. maxFrameRate: 3
  3260. },
  3261. optional: [
  3262. {googLeakyBucket: true},
  3263. {googTemporalLayeredScreencast: true}
  3264. ]
  3265. }};
  3266. constraints.video.mandatory.chromeMediaSourceId = sourceId;
  3267. getUserMedia(constraints, callback);
  3268. }
  3269. });
  3270. } else if (isCef || (chromever >= 26 && chromever <= maxver)) {
  3271. // chrome 26 - chrome 33 way to do it -- requires bad chrome://flags
  3272. // note: this is basically in maintenance mode and will go away soon
  3273. constraints = (hasConstraints && constraints) || {
  3274. video: {
  3275. mandatory: {
  3276. googLeakyBucket: true,
  3277. maxWidth: window.screen.width,
  3278. maxHeight: window.screen.height,
  3279. maxFrameRate: 3,
  3280. chromeMediaSource: 'screen'
  3281. }
  3282. }
  3283. };
  3284. getUserMedia(constraints, callback);
  3285. } else {
  3286. // chrome 34+ way requiring an extension
  3287. var pending = window.setTimeout(function () {
  3288. error = new Error('NavigatorUserMediaError');
  3289. error.name = 'EXTENSION_UNAVAILABLE';
  3290. return callback(error);
  3291. }, 1000);
  3292. cache[pending] = [callback, hasConstraints ? constraints : null];
  3293. window.postMessage({ type: 'getScreen', id: pending }, '*');
  3294. }
  3295. } else if (window.navigator.userAgent.match('Firefox')) {
  3296. var ffver = parseInt(window.navigator.userAgent.match(/Firefox\/(.*)/)[1], 10);
  3297. if (ffver >= 33) {
  3298. constraints = (hasConstraints && constraints) || {
  3299. video: {
  3300. mozMediaSource: 'window',
  3301. mediaSource: 'window'
  3302. }
  3303. };
  3304. getUserMedia(constraints, function (err, stream) {
  3305. callback(err, stream);
  3306. // workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1045810
  3307. if (!err) {
  3308. var lastTime = stream.currentTime;
  3309. var polly = window.setInterval(function () {
  3310. if (!stream) window.clearInterval(polly);
  3311. if (stream.currentTime == lastTime) {
  3312. window.clearInterval(polly);
  3313. if (stream.onended) {
  3314. stream.onended();
  3315. }
  3316. }
  3317. lastTime = stream.currentTime;
  3318. }, 500);
  3319. }
  3320. });
  3321. } else {
  3322. error = new Error('NavigatorUserMediaError');
  3323. error.name = 'EXTENSION_UNAVAILABLE'; // does not make much sense but...
  3324. }
  3325. }
  3326. };
  3327. typeof window !== 'undefined' && window.addEventListener('message', function (event) {
  3328. if (event.origin != window.location.origin) {
  3329. return;
  3330. }
  3331. if (event.data.type == 'gotScreen' && cache[event.data.id]) {
  3332. var data = cache[event.data.id];
  3333. var constraints = data[1];
  3334. var callback = data[0];
  3335. delete cache[event.data.id];
  3336. if (event.data.sourceId === '') { // user canceled
  3337. var error = new Error('NavigatorUserMediaError');
  3338. error.name = 'PERMISSION_DENIED';
  3339. callback(error);
  3340. } else {
  3341. constraints = constraints || {audio: false, video: {
  3342. mandatory: {
  3343. chromeMediaSource: 'desktop',
  3344. maxWidth: window.screen.width,
  3345. maxHeight: window.screen.height,
  3346. maxFrameRate: 3
  3347. },
  3348. optional: [
  3349. {googLeakyBucket: true},
  3350. {googTemporalLayeredScreencast: true}
  3351. ]
  3352. }};
  3353. constraints.video.mandatory.chromeMediaSourceId = event.data.sourceId;
  3354. getUserMedia(constraints, callback);
  3355. }
  3356. } else if (event.data.type == 'getScreenPending') {
  3357. window.clearTimeout(event.data.id);
  3358. }
  3359. });
  3360. },{"getusermedia":28}],28:[function(require,module,exports){
  3361. // getUserMedia helper by @HenrikJoreteg used for navigator.getUserMedia shim
  3362. var adapter = require('webrtc-adapter');
  3363. module.exports = function (constraints, cb) {
  3364. var error;
  3365. var haveOpts = arguments.length === 2;
  3366. var defaultOpts = {video: true, audio: true};
  3367. var denied = 'PermissionDeniedError';
  3368. var altDenied = 'PERMISSION_DENIED';
  3369. var notSatisfied = 'ConstraintNotSatisfiedError';
  3370. // make constraints optional
  3371. if (!haveOpts) {
  3372. cb = constraints;
  3373. constraints = defaultOpts;
  3374. }
  3375. // treat lack of browser support like an error
  3376. if (typeof navigator === 'undefined' || !navigator.getUserMedia) {
  3377. // throw proper error per spec
  3378. error = new Error('MediaStreamError');
  3379. error.name = 'NotSupportedError';
  3380. // keep all callbacks async
  3381. return setTimeout(function () {
  3382. cb(error);
  3383. }, 0);
  3384. }
  3385. // normalize error handling when no media types are requested
  3386. if (!constraints.audio && !constraints.video) {
  3387. error = new Error('MediaStreamError');
  3388. error.name = 'NoMediaRequestedError';
  3389. // keep all callbacks async
  3390. return setTimeout(function () {
  3391. cb(error);
  3392. }, 0);
  3393. }
  3394. navigator.mediaDevices.getUserMedia(constraints)
  3395. .then(function (stream) {
  3396. cb(null, stream);
  3397. }).catch(function (err) {
  3398. var error;
  3399. // coerce into an error object since FF gives us a string
  3400. // there are only two valid names according to the spec
  3401. // we coerce all non-denied to "constraint not satisfied".
  3402. if (typeof err === 'string') {
  3403. error = new Error('MediaStreamError');
  3404. if (err === denied || err === altDenied) {
  3405. error.name = denied;
  3406. } else {
  3407. error.name = notSatisfied;
  3408. }
  3409. } else {
  3410. // if we get an error object make sure '.name' property is set
  3411. // according to spec: http://dev.w3.org/2011/webrtc/editor/getusermedia.html#navigatorusermediaerror-and-navigatorusermediaerrorcallback
  3412. error = err;
  3413. if (!error.name) {
  3414. // this is likely chrome which
  3415. // sets a property called "ERROR_DENIED" on the error object
  3416. // if so we make sure to set a name
  3417. if (error[denied]) {
  3418. err.name = denied;
  3419. } else {
  3420. err.name = notSatisfied;
  3421. }
  3422. }
  3423. }
  3424. cb(error);
  3425. });
  3426. };
  3427. },{"webrtc-adapter":90}],29:[function(require,module,exports){
  3428. // getUserMedia helper by @HenrikJoreteg used for navigator.getUserMedia shim
  3429. var adapter = require('webrtc-adapter');
  3430. module.exports = function (constraints, cb) {
  3431. var error;
  3432. var haveOpts = arguments.length === 2;
  3433. var defaultOpts = {video: true, audio: true};
  3434. var denied = 'PermissionDeniedError';
  3435. var altDenied = 'PERMISSION_DENIED';
  3436. var notSatisfied = 'ConstraintNotSatisfiedError';
  3437. // make constraints optional
  3438. if (!haveOpts) {
  3439. cb = constraints;
  3440. constraints = defaultOpts;
  3441. }
  3442. // treat lack of browser support like an error
  3443. if (typeof navigator === 'undefined' || !navigator.getUserMedia) {
  3444. // throw proper error per spec
  3445. error = new Error('MediaStreamError');
  3446. error.name = 'NotSupportedError';
  3447. // keep all callbacks async
  3448. return setTimeout(function () {
  3449. cb(error);
  3450. }, 0);
  3451. }
  3452. // normalize error handling when no media types are requested
  3453. if (!constraints.audio && !constraints.video) {
  3454. error = new Error('MediaStreamError');
  3455. error.name = 'NoMediaRequestedError';
  3456. // keep all callbacks async
  3457. return setTimeout(function () {
  3458. cb(error);
  3459. }, 0);
  3460. }
  3461. // testing support -- note: using the about:config pref is better
  3462. // for Firefox 39+, this might get removed in the future
  3463. if (localStorage && localStorage.useFirefoxFakeDevice === 'true') {
  3464. constraints.fake = true;
  3465. }
  3466. navigator.mediaDevices.getUserMedia(constraints)
  3467. .then(function (stream) {
  3468. cb(null, stream);
  3469. }).catch(function (err) {
  3470. var error;
  3471. // coerce into an error object since FF gives us a string
  3472. // there are only two valid names according to the spec
  3473. // we coerce all non-denied to "constraint not satisfied".
  3474. if (typeof err === 'string') {
  3475. error = new Error('MediaStreamError');
  3476. if (err === denied || err === altDenied) {
  3477. error.name = denied;
  3478. } else {
  3479. error.name = notSatisfied;
  3480. }
  3481. } else {
  3482. // if we get an error object make sure '.name' property is set
  3483. // according to spec: http://dev.w3.org/2011/webrtc/editor/getusermedia.html#navigatorusermediaerror-and-navigatorusermediaerrorcallback
  3484. error = err;
  3485. if (!error.name) {
  3486. // this is likely chrome which
  3487. // sets a property called "ERROR_DENIED" on the error object
  3488. // if so we make sure to set a name
  3489. if (error[denied]) {
  3490. err.name = denied;
  3491. } else {
  3492. err.name = notSatisfied;
  3493. }
  3494. }
  3495. }
  3496. cb(error);
  3497. });
  3498. };
  3499. },{"webrtc-adapter":30}],30:[function(require,module,exports){
  3500. /*
  3501. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3502. *
  3503. * Use of this source code is governed by a BSD-style license
  3504. * that can be found in the LICENSE file in the root of the source
  3505. * tree.
  3506. */
  3507. /* eslint-env node */
  3508. 'use strict';
  3509. // Shimming starts here.
  3510. (function() {
  3511. // Utils.
  3512. var logging = require('./utils').log;
  3513. var browserDetails = require('./utils').browserDetails;
  3514. // Export to the adapter global object visible in the browser.
  3515. module.exports.browserDetails = browserDetails;
  3516. module.exports.extractVersion = require('./utils').extractVersion;
  3517. module.exports.disableLog = require('./utils').disableLog;
  3518. // Uncomment the line below if you want logging to occur, including logging
  3519. // for the switch statement below. Can also be turned on in the browser via
  3520. // adapter.disableLog(false), but then logging from the switch statement below
  3521. // will not appear.
  3522. // require('./utils').disableLog(false);
  3523. // Browser shims.
  3524. var chromeShim = require('./chrome/chrome_shim') || null;
  3525. var edgeShim = require('./edge/edge_shim') || null;
  3526. var firefoxShim = require('./firefox/firefox_shim') || null;
  3527. var safariShim = require('./safari/safari_shim') || null;
  3528. // Shim browser if found.
  3529. switch (browserDetails.browser) {
  3530. case 'opera': // fallthrough as it uses chrome shims
  3531. case 'chrome':
  3532. if (!chromeShim || !chromeShim.shimPeerConnection) {
  3533. logging('Chrome shim is not included in this adapter release.');
  3534. return;
  3535. }
  3536. logging('adapter.js shimming chrome.');
  3537. // Export to the adapter global object visible in the browser.
  3538. module.exports.browserShim = chromeShim;
  3539. chromeShim.shimGetUserMedia();
  3540. chromeShim.shimMediaStream();
  3541. chromeShim.shimSourceObject();
  3542. chromeShim.shimPeerConnection();
  3543. chromeShim.shimOnTrack();
  3544. break;
  3545. case 'firefox':
  3546. if (!firefoxShim || !firefoxShim.shimPeerConnection) {
  3547. logging('Firefox shim is not included in this adapter release.');
  3548. return;
  3549. }
  3550. logging('adapter.js shimming firefox.');
  3551. // Export to the adapter global object visible in the browser.
  3552. module.exports.browserShim = firefoxShim;
  3553. firefoxShim.shimGetUserMedia();
  3554. firefoxShim.shimSourceObject();
  3555. firefoxShim.shimPeerConnection();
  3556. firefoxShim.shimOnTrack();
  3557. break;
  3558. case 'edge':
  3559. if (!edgeShim || !edgeShim.shimPeerConnection) {
  3560. logging('MS edge shim is not included in this adapter release.');
  3561. return;
  3562. }
  3563. logging('adapter.js shimming edge.');
  3564. // Export to the adapter global object visible in the browser.
  3565. module.exports.browserShim = edgeShim;
  3566. edgeShim.shimGetUserMedia();
  3567. edgeShim.shimPeerConnection();
  3568. break;
  3569. case 'safari':
  3570. if (!safariShim) {
  3571. logging('Safari shim is not included in this adapter release.');
  3572. return;
  3573. }
  3574. logging('adapter.js shimming safari.');
  3575. // Export to the adapter global object visible in the browser.
  3576. module.exports.browserShim = safariShim;
  3577. safariShim.shimGetUserMedia();
  3578. break;
  3579. default:
  3580. logging('Unsupported browser!');
  3581. }
  3582. })();
  3583. },{"./chrome/chrome_shim":31,"./edge/edge_shim":33,"./firefox/firefox_shim":35,"./safari/safari_shim":37,"./utils":38}],31:[function(require,module,exports){
  3584. /*
  3585. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3586. *
  3587. * Use of this source code is governed by a BSD-style license
  3588. * that can be found in the LICENSE file in the root of the source
  3589. * tree.
  3590. */
  3591. /* eslint-env node */
  3592. 'use strict';
  3593. var logging = require('../utils.js').log;
  3594. var browserDetails = require('../utils.js').browserDetails;
  3595. var chromeShim = {
  3596. shimMediaStream: function() {
  3597. window.MediaStream = window.MediaStream || window.webkitMediaStream;
  3598. },
  3599. shimOnTrack: function() {
  3600. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  3601. window.RTCPeerConnection.prototype)) {
  3602. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  3603. get: function() {
  3604. return this._ontrack;
  3605. },
  3606. set: function(f) {
  3607. var self = this;
  3608. if (this._ontrack) {
  3609. this.removeEventListener('track', this._ontrack);
  3610. this.removeEventListener('addstream', this._ontrackpoly);
  3611. }
  3612. this.addEventListener('track', this._ontrack = f);
  3613. this.addEventListener('addstream', this._ontrackpoly = function(e) {
  3614. // onaddstream does not fire when a track is added to an existing
  3615. // stream. But stream.onaddtrack is implemented so we use that.
  3616. e.stream.addEventListener('addtrack', function(te) {
  3617. var event = new Event('track');
  3618. event.track = te.track;
  3619. event.receiver = {track: te.track};
  3620. event.streams = [e.stream];
  3621. self.dispatchEvent(event);
  3622. });
  3623. e.stream.getTracks().forEach(function(track) {
  3624. var event = new Event('track');
  3625. event.track = track;
  3626. event.receiver = {track: track};
  3627. event.streams = [e.stream];
  3628. this.dispatchEvent(event);
  3629. }.bind(this));
  3630. }.bind(this));
  3631. }
  3632. });
  3633. }
  3634. },
  3635. shimSourceObject: function() {
  3636. if (typeof window === 'object') {
  3637. if (window.HTMLMediaElement &&
  3638. !('srcObject' in window.HTMLMediaElement.prototype)) {
  3639. // Shim the srcObject property, once, when HTMLMediaElement is found.
  3640. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
  3641. get: function() {
  3642. return this._srcObject;
  3643. },
  3644. set: function(stream) {
  3645. var self = this;
  3646. // Use _srcObject as a private property for this shim
  3647. this._srcObject = stream;
  3648. if (this.src) {
  3649. URL.revokeObjectURL(this.src);
  3650. }
  3651. if (!stream) {
  3652. this.src = '';
  3653. return;
  3654. }
  3655. this.src = URL.createObjectURL(stream);
  3656. // We need to recreate the blob url when a track is added or
  3657. // removed. Doing it manually since we want to avoid a recursion.
  3658. stream.addEventListener('addtrack', function() {
  3659. if (self.src) {
  3660. URL.revokeObjectURL(self.src);
  3661. }
  3662. self.src = URL.createObjectURL(stream);
  3663. });
  3664. stream.addEventListener('removetrack', function() {
  3665. if (self.src) {
  3666. URL.revokeObjectURL(self.src);
  3667. }
  3668. self.src = URL.createObjectURL(stream);
  3669. });
  3670. }
  3671. });
  3672. }
  3673. }
  3674. },
  3675. shimPeerConnection: function() {
  3676. // The RTCPeerConnection object.
  3677. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  3678. // Translate iceTransportPolicy to iceTransports,
  3679. // see https://code.google.com/p/webrtc/issues/detail?id=4869
  3680. logging('PeerConnection');
  3681. if (pcConfig && pcConfig.iceTransportPolicy) {
  3682. pcConfig.iceTransports = pcConfig.iceTransportPolicy;
  3683. }
  3684. var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints);
  3685. var origGetStats = pc.getStats.bind(pc);
  3686. pc.getStats = function(selector, successCallback, errorCallback) {
  3687. var self = this;
  3688. var args = arguments;
  3689. // If selector is a function then we are in the old style stats so just
  3690. // pass back the original getStats format to avoid breaking old users.
  3691. if (arguments.length > 0 && typeof selector === 'function') {
  3692. return origGetStats(selector, successCallback);
  3693. }
  3694. var fixChromeStats_ = function(response) {
  3695. var standardReport = {};
  3696. var reports = response.result();
  3697. reports.forEach(function(report) {
  3698. var standardStats = {
  3699. id: report.id,
  3700. timestamp: report.timestamp,
  3701. type: report.type
  3702. };
  3703. report.names().forEach(function(name) {
  3704. standardStats[name] = report.stat(name);
  3705. });
  3706. standardReport[standardStats.id] = standardStats;
  3707. });
  3708. return standardReport;
  3709. };
  3710. // shim getStats with maplike support
  3711. var makeMapStats = function(stats, legacyStats) {
  3712. var map = new Map(Object.keys(stats).map(function(key) {
  3713. return[key, stats[key]];
  3714. }));
  3715. legacyStats = legacyStats || stats;
  3716. Object.keys(legacyStats).forEach(function(key) {
  3717. map[key] = legacyStats[key];
  3718. });
  3719. return map;
  3720. };
  3721. if (arguments.length >= 2) {
  3722. var successCallbackWrapper_ = function(response) {
  3723. args[1](makeMapStats(fixChromeStats_(response)));
  3724. };
  3725. return origGetStats.apply(this, [successCallbackWrapper_,
  3726. arguments[0]]);
  3727. }
  3728. // promise-support
  3729. return new Promise(function(resolve, reject) {
  3730. if (args.length === 1 && typeof selector === 'object') {
  3731. origGetStats.apply(self, [
  3732. function(response) {
  3733. resolve(makeMapStats(fixChromeStats_(response)));
  3734. }, reject]);
  3735. } else {
  3736. // Preserve legacy chrome stats only on legacy access of stats obj
  3737. origGetStats.apply(self, [
  3738. function(response) {
  3739. resolve(makeMapStats(fixChromeStats_(response),
  3740. response.result()));
  3741. }, reject]);
  3742. }
  3743. }).then(successCallback, errorCallback);
  3744. };
  3745. return pc;
  3746. };
  3747. window.RTCPeerConnection.prototype = webkitRTCPeerConnection.prototype;
  3748. // wrap static methods. Currently just generateCertificate.
  3749. if (webkitRTCPeerConnection.generateCertificate) {
  3750. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  3751. get: function() {
  3752. return webkitRTCPeerConnection.generateCertificate;
  3753. }
  3754. });
  3755. }
  3756. ['createOffer', 'createAnswer'].forEach(function(method) {
  3757. var nativeMethod = webkitRTCPeerConnection.prototype[method];
  3758. webkitRTCPeerConnection.prototype[method] = function() {
  3759. var self = this;
  3760. if (arguments.length < 1 || (arguments.length === 1 &&
  3761. typeof arguments[0] === 'object')) {
  3762. var opts = arguments.length === 1 ? arguments[0] : undefined;
  3763. return new Promise(function(resolve, reject) {
  3764. nativeMethod.apply(self, [resolve, reject, opts]);
  3765. });
  3766. }
  3767. return nativeMethod.apply(this, arguments);
  3768. };
  3769. });
  3770. // add promise support -- natively available in Chrome 51
  3771. if (browserDetails.version < 51) {
  3772. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  3773. .forEach(function(method) {
  3774. var nativeMethod = webkitRTCPeerConnection.prototype[method];
  3775. webkitRTCPeerConnection.prototype[method] = function() {
  3776. var args = arguments;
  3777. var self = this;
  3778. var promise = new Promise(function(resolve, reject) {
  3779. nativeMethod.apply(self, [args[0], resolve, reject]);
  3780. });
  3781. if (args.length < 2) {
  3782. return promise;
  3783. }
  3784. return promise.then(function() {
  3785. args[1].apply(null, []);
  3786. },
  3787. function(err) {
  3788. if (args.length >= 3) {
  3789. args[2].apply(null, [err]);
  3790. }
  3791. });
  3792. };
  3793. });
  3794. }
  3795. // support for addIceCandidate(null)
  3796. var nativeAddIceCandidate =
  3797. RTCPeerConnection.prototype.addIceCandidate;
  3798. RTCPeerConnection.prototype.addIceCandidate = function() {
  3799. return arguments[0] === null ? Promise.resolve()
  3800. : nativeAddIceCandidate.apply(this, arguments);
  3801. };
  3802. // shim implicit creation of RTCSessionDescription/RTCIceCandidate
  3803. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  3804. .forEach(function(method) {
  3805. var nativeMethod = webkitRTCPeerConnection.prototype[method];
  3806. webkitRTCPeerConnection.prototype[method] = function() {
  3807. arguments[0] = new ((method === 'addIceCandidate') ?
  3808. RTCIceCandidate : RTCSessionDescription)(arguments[0]);
  3809. return nativeMethod.apply(this, arguments);
  3810. };
  3811. });
  3812. },
  3813. // Attach a media stream to an element.
  3814. attachMediaStream: function(element, stream) {
  3815. logging('DEPRECATED, attachMediaStream will soon be removed.');
  3816. if (browserDetails.version >= 43) {
  3817. element.srcObject = stream;
  3818. } else if (typeof element.src !== 'undefined') {
  3819. element.src = URL.createObjectURL(stream);
  3820. } else {
  3821. logging('Error attaching stream to element.');
  3822. }
  3823. },
  3824. reattachMediaStream: function(to, from) {
  3825. logging('DEPRECATED, reattachMediaStream will soon be removed.');
  3826. if (browserDetails.version >= 43) {
  3827. to.srcObject = from.srcObject;
  3828. } else {
  3829. to.src = from.src;
  3830. }
  3831. }
  3832. };
  3833. // Expose public methods.
  3834. module.exports = {
  3835. shimMediaStream: chromeShim.shimMediaStream,
  3836. shimOnTrack: chromeShim.shimOnTrack,
  3837. shimSourceObject: chromeShim.shimSourceObject,
  3838. shimPeerConnection: chromeShim.shimPeerConnection,
  3839. shimGetUserMedia: require('./getusermedia'),
  3840. attachMediaStream: chromeShim.attachMediaStream,
  3841. reattachMediaStream: chromeShim.reattachMediaStream
  3842. };
  3843. },{"../utils.js":38,"./getusermedia":32}],32:[function(require,module,exports){
  3844. /*
  3845. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3846. *
  3847. * Use of this source code is governed by a BSD-style license
  3848. * that can be found in the LICENSE file in the root of the source
  3849. * tree.
  3850. */
  3851. /* eslint-env node */
  3852. 'use strict';
  3853. var logging = require('../utils.js').log;
  3854. // Expose public methods.
  3855. module.exports = function() {
  3856. var constraintsToChrome_ = function(c) {
  3857. if (typeof c !== 'object' || c.mandatory || c.optional) {
  3858. return c;
  3859. }
  3860. var cc = {};
  3861. Object.keys(c).forEach(function(key) {
  3862. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  3863. return;
  3864. }
  3865. var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
  3866. if (r.exact !== undefined && typeof r.exact === 'number') {
  3867. r.min = r.max = r.exact;
  3868. }
  3869. var oldname_ = function(prefix, name) {
  3870. if (prefix) {
  3871. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  3872. }
  3873. return (name === 'deviceId') ? 'sourceId' : name;
  3874. };
  3875. if (r.ideal !== undefined) {
  3876. cc.optional = cc.optional || [];
  3877. var oc = {};
  3878. if (typeof r.ideal === 'number') {
  3879. oc[oldname_('min', key)] = r.ideal;
  3880. cc.optional.push(oc);
  3881. oc = {};
  3882. oc[oldname_('max', key)] = r.ideal;
  3883. cc.optional.push(oc);
  3884. } else {
  3885. oc[oldname_('', key)] = r.ideal;
  3886. cc.optional.push(oc);
  3887. }
  3888. }
  3889. if (r.exact !== undefined && typeof r.exact !== 'number') {
  3890. cc.mandatory = cc.mandatory || {};
  3891. cc.mandatory[oldname_('', key)] = r.exact;
  3892. } else {
  3893. ['min', 'max'].forEach(function(mix) {
  3894. if (r[mix] !== undefined) {
  3895. cc.mandatory = cc.mandatory || {};
  3896. cc.mandatory[oldname_(mix, key)] = r[mix];
  3897. }
  3898. });
  3899. }
  3900. });
  3901. if (c.advanced) {
  3902. cc.optional = (cc.optional || []).concat(c.advanced);
  3903. }
  3904. return cc;
  3905. };
  3906. var shimConstraints_ = function(constraints, func) {
  3907. constraints = JSON.parse(JSON.stringify(constraints));
  3908. if (constraints && constraints.audio) {
  3909. constraints.audio = constraintsToChrome_(constraints.audio);
  3910. }
  3911. if (constraints && typeof constraints.video === 'object') {
  3912. // Shim facingMode for mobile, where it defaults to "user".
  3913. var face = constraints.video.facingMode;
  3914. face = face && ((typeof face === 'object') ? face : {ideal: face});
  3915. if ((face && (face.exact === 'user' || face.exact === 'environment' ||
  3916. face.ideal === 'user' || face.ideal === 'environment')) &&
  3917. !(navigator.mediaDevices.getSupportedConstraints &&
  3918. navigator.mediaDevices.getSupportedConstraints().facingMode)) {
  3919. delete constraints.video.facingMode;
  3920. if (face.exact === 'environment' || face.ideal === 'environment') {
  3921. // Look for "back" in label, or use last cam (typically back cam).
  3922. return navigator.mediaDevices.enumerateDevices()
  3923. .then(function(devices) {
  3924. devices = devices.filter(function(d) {
  3925. return d.kind === 'videoinput';
  3926. });
  3927. var back = devices.find(function(d) {
  3928. return d.label.toLowerCase().indexOf('back') !== -1;
  3929. }) || (devices.length && devices[devices.length - 1]);
  3930. if (back) {
  3931. constraints.video.deviceId = face.exact ? {exact: back.deviceId} :
  3932. {ideal: back.deviceId};
  3933. }
  3934. constraints.video = constraintsToChrome_(constraints.video);
  3935. logging('chrome: ' + JSON.stringify(constraints));
  3936. return func(constraints);
  3937. });
  3938. }
  3939. }
  3940. constraints.video = constraintsToChrome_(constraints.video);
  3941. }
  3942. logging('chrome: ' + JSON.stringify(constraints));
  3943. return func(constraints);
  3944. };
  3945. var shimError_ = function(e) {
  3946. return {
  3947. name: {
  3948. PermissionDeniedError: 'NotAllowedError',
  3949. ConstraintNotSatisfiedError: 'OverconstrainedError'
  3950. }[e.name] || e.name,
  3951. message: e.message,
  3952. constraint: e.constraintName,
  3953. toString: function() {
  3954. return this.name + (this.message && ': ') + this.message;
  3955. }
  3956. };
  3957. };
  3958. var getUserMedia_ = function(constraints, onSuccess, onError) {
  3959. shimConstraints_(constraints, function(c) {
  3960. navigator.webkitGetUserMedia(c, onSuccess, function(e) {
  3961. onError(shimError_(e));
  3962. });
  3963. });
  3964. };
  3965. navigator.getUserMedia = getUserMedia_;
  3966. // Returns the result of getUserMedia as a Promise.
  3967. var getUserMediaPromise_ = function(constraints) {
  3968. return new Promise(function(resolve, reject) {
  3969. navigator.getUserMedia(constraints, resolve, reject);
  3970. });
  3971. };
  3972. if (!navigator.mediaDevices) {
  3973. navigator.mediaDevices = {
  3974. getUserMedia: getUserMediaPromise_,
  3975. enumerateDevices: function() {
  3976. return new Promise(function(resolve) {
  3977. var kinds = {audio: 'audioinput', video: 'videoinput'};
  3978. return MediaStreamTrack.getSources(function(devices) {
  3979. resolve(devices.map(function(device) {
  3980. return {label: device.label,
  3981. kind: kinds[device.kind],
  3982. deviceId: device.id,
  3983. groupId: ''};
  3984. }));
  3985. });
  3986. });
  3987. }
  3988. };
  3989. }
  3990. // A shim for getUserMedia method on the mediaDevices object.
  3991. // TODO(KaptenJansson) remove once implemented in Chrome stable.
  3992. if (!navigator.mediaDevices.getUserMedia) {
  3993. navigator.mediaDevices.getUserMedia = function(constraints) {
  3994. return getUserMediaPromise_(constraints);
  3995. };
  3996. } else {
  3997. // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
  3998. // function which returns a Promise, it does not accept spec-style
  3999. // constraints.
  4000. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  4001. bind(navigator.mediaDevices);
  4002. navigator.mediaDevices.getUserMedia = function(cs) {
  4003. return shimConstraints_(cs, function(c) {
  4004. return origGetUserMedia(c).catch(function(e) {
  4005. return Promise.reject(shimError_(e));
  4006. });
  4007. });
  4008. };
  4009. }
  4010. // Dummy devicechange event methods.
  4011. // TODO(KaptenJansson) remove once implemented in Chrome stable.
  4012. if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
  4013. navigator.mediaDevices.addEventListener = function() {
  4014. logging('Dummy mediaDevices.addEventListener called.');
  4015. };
  4016. }
  4017. if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
  4018. navigator.mediaDevices.removeEventListener = function() {
  4019. logging('Dummy mediaDevices.removeEventListener called.');
  4020. };
  4021. }
  4022. };
  4023. },{"../utils.js":38}],33:[function(require,module,exports){
  4024. /*
  4025. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4026. *
  4027. * Use of this source code is governed by a BSD-style license
  4028. * that can be found in the LICENSE file in the root of the source
  4029. * tree.
  4030. */
  4031. /* eslint-env node */
  4032. 'use strict';
  4033. var SDPUtils = require('sdp');
  4034. var logging = require('../utils').log;
  4035. var edgeShim = {
  4036. shimPeerConnection: function() {
  4037. if (window.RTCIceGatherer) {
  4038. // ORTC defines an RTCIceCandidate object but no constructor.
  4039. // Not implemented in Edge.
  4040. if (!window.RTCIceCandidate) {
  4041. window.RTCIceCandidate = function(args) {
  4042. return args;
  4043. };
  4044. }
  4045. // ORTC does not have a session description object but
  4046. // other browsers (i.e. Chrome) that will support both PC and ORTC
  4047. // in the future might have this defined already.
  4048. if (!window.RTCSessionDescription) {
  4049. window.RTCSessionDescription = function(args) {
  4050. return args;
  4051. };
  4052. }
  4053. }
  4054. window.RTCPeerConnection = function(config) {
  4055. var self = this;
  4056. var _eventTarget = document.createDocumentFragment();
  4057. ['addEventListener', 'removeEventListener', 'dispatchEvent']
  4058. .forEach(function(method) {
  4059. self[method] = _eventTarget[method].bind(_eventTarget);
  4060. });
  4061. this.onicecandidate = null;
  4062. this.onaddstream = null;
  4063. this.ontrack = null;
  4064. this.onremovestream = null;
  4065. this.onsignalingstatechange = null;
  4066. this.oniceconnectionstatechange = null;
  4067. this.onnegotiationneeded = null;
  4068. this.ondatachannel = null;
  4069. this.localStreams = [];
  4070. this.remoteStreams = [];
  4071. this.getLocalStreams = function() {
  4072. return self.localStreams;
  4073. };
  4074. this.getRemoteStreams = function() {
  4075. return self.remoteStreams;
  4076. };
  4077. this.localDescription = new RTCSessionDescription({
  4078. type: '',
  4079. sdp: ''
  4080. });
  4081. this.remoteDescription = new RTCSessionDescription({
  4082. type: '',
  4083. sdp: ''
  4084. });
  4085. this.signalingState = 'stable';
  4086. this.iceConnectionState = 'new';
  4087. this.iceGatheringState = 'new';
  4088. this.iceOptions = {
  4089. gatherPolicy: 'all',
  4090. iceServers: []
  4091. };
  4092. if (config && config.iceTransportPolicy) {
  4093. switch (config.iceTransportPolicy) {
  4094. case 'all':
  4095. case 'relay':
  4096. this.iceOptions.gatherPolicy = config.iceTransportPolicy;
  4097. break;
  4098. case 'none':
  4099. // FIXME: remove once implementation and spec have added this.
  4100. throw new TypeError('iceTransportPolicy "none" not supported');
  4101. default:
  4102. // don't set iceTransportPolicy.
  4103. break;
  4104. }
  4105. }
  4106. this.usingBundle = config && config.bundlePolicy === 'max-bundle';
  4107. if (config && config.iceServers) {
  4108. // Edge does not like
  4109. // 1) stun:
  4110. // 2) turn: that does not have all of turn:host:port?transport=udp
  4111. var iceServers = JSON.parse(JSON.stringify(config.iceServers));
  4112. this.iceOptions.iceServers = iceServers.filter(function(server) {
  4113. if (server && server.urls) {
  4114. var urls = server.urls;
  4115. if (typeof urls === 'string') {
  4116. urls = [urls];
  4117. }
  4118. urls = urls.filter(function(url) {
  4119. return url.indexOf('turn:') === 0 &&
  4120. url.indexOf('transport=udp') !== -1;
  4121. })[0];
  4122. return !!urls;
  4123. }
  4124. return false;
  4125. });
  4126. }
  4127. // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
  4128. // everything that is needed to describe a SDP m-line.
  4129. this.transceivers = [];
  4130. // since the iceGatherer is currently created in createOffer but we
  4131. // must not emit candidates until after setLocalDescription we buffer
  4132. // them in this array.
  4133. this._localIceCandidatesBuffer = [];
  4134. };
  4135. window.RTCPeerConnection.prototype._emitBufferedCandidates = function() {
  4136. var self = this;
  4137. var sections = SDPUtils.splitSections(self.localDescription.sdp);
  4138. // FIXME: need to apply ice candidates in a way which is async but
  4139. // in-order
  4140. this._localIceCandidatesBuffer.forEach(function(event) {
  4141. var end = !event.candidate || Object.keys(event.candidate).length === 0;
  4142. if (end) {
  4143. for (var j = 1; j < sections.length; j++) {
  4144. if (sections[j].indexOf('\r\na=end-of-candidates\r\n') === -1) {
  4145. sections[j] += 'a=end-of-candidates\r\n';
  4146. }
  4147. }
  4148. } else if (event.candidate.candidate.indexOf('typ endOfCandidates')
  4149. === -1) {
  4150. sections[event.candidate.sdpMLineIndex + 1] +=
  4151. 'a=' + event.candidate.candidate + '\r\n';
  4152. }
  4153. self.localDescription.sdp = sections.join('');
  4154. self.dispatchEvent(event);
  4155. if (self.onicecandidate !== null) {
  4156. self.onicecandidate(event);
  4157. }
  4158. if (!event.candidate && self.iceGatheringState !== 'complete') {
  4159. var complete = self.transceivers.every(function(transceiver) {
  4160. return transceiver.iceGatherer &&
  4161. transceiver.iceGatherer.state === 'completed';
  4162. });
  4163. if (complete) {
  4164. self.iceGatheringState = 'complete';
  4165. }
  4166. }
  4167. });
  4168. this._localIceCandidatesBuffer = [];
  4169. };
  4170. window.RTCPeerConnection.prototype.addStream = function(stream) {
  4171. // Clone is necessary for local demos mostly, attaching directly
  4172. // to two different senders does not work (build 10547).
  4173. this.localStreams.push(stream.clone());
  4174. this._maybeFireNegotiationNeeded();
  4175. };
  4176. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  4177. var idx = this.localStreams.indexOf(stream);
  4178. if (idx > -1) {
  4179. this.localStreams.splice(idx, 1);
  4180. this._maybeFireNegotiationNeeded();
  4181. }
  4182. };
  4183. window.RTCPeerConnection.prototype.getSenders = function() {
  4184. return this.transceivers.filter(function(transceiver) {
  4185. return !!transceiver.rtpSender;
  4186. })
  4187. .map(function(transceiver) {
  4188. return transceiver.rtpSender;
  4189. });
  4190. };
  4191. window.RTCPeerConnection.prototype.getReceivers = function() {
  4192. return this.transceivers.filter(function(transceiver) {
  4193. return !!transceiver.rtpReceiver;
  4194. })
  4195. .map(function(transceiver) {
  4196. return transceiver.rtpReceiver;
  4197. });
  4198. };
  4199. // Determines the intersection of local and remote capabilities.
  4200. window.RTCPeerConnection.prototype._getCommonCapabilities =
  4201. function(localCapabilities, remoteCapabilities) {
  4202. var commonCapabilities = {
  4203. codecs: [],
  4204. headerExtensions: [],
  4205. fecMechanisms: []
  4206. };
  4207. localCapabilities.codecs.forEach(function(lCodec) {
  4208. for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
  4209. var rCodec = remoteCapabilities.codecs[i];
  4210. if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
  4211. lCodec.clockRate === rCodec.clockRate &&
  4212. lCodec.numChannels === rCodec.numChannels) {
  4213. // push rCodec so we reply with offerer payload type
  4214. commonCapabilities.codecs.push(rCodec);
  4215. // FIXME: also need to determine intersection between
  4216. // .rtcpFeedback and .parameters
  4217. break;
  4218. }
  4219. }
  4220. });
  4221. localCapabilities.headerExtensions
  4222. .forEach(function(lHeaderExtension) {
  4223. for (var i = 0; i < remoteCapabilities.headerExtensions.length;
  4224. i++) {
  4225. var rHeaderExtension = remoteCapabilities.headerExtensions[i];
  4226. if (lHeaderExtension.uri === rHeaderExtension.uri) {
  4227. commonCapabilities.headerExtensions.push(rHeaderExtension);
  4228. break;
  4229. }
  4230. }
  4231. });
  4232. // FIXME: fecMechanisms
  4233. return commonCapabilities;
  4234. };
  4235. // Create ICE gatherer, ICE transport and DTLS transport.
  4236. window.RTCPeerConnection.prototype._createIceAndDtlsTransports =
  4237. function(mid, sdpMLineIndex) {
  4238. var self = this;
  4239. var iceGatherer = new RTCIceGatherer(self.iceOptions);
  4240. var iceTransport = new RTCIceTransport(iceGatherer);
  4241. iceGatherer.onlocalcandidate = function(evt) {
  4242. var event = new Event('icecandidate');
  4243. event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
  4244. var cand = evt.candidate;
  4245. var end = !cand || Object.keys(cand).length === 0;
  4246. // Edge emits an empty object for RTCIceCandidateComplete‥
  4247. if (end) {
  4248. // polyfill since RTCIceGatherer.state is not implemented in
  4249. // Edge 10547 yet.
  4250. if (iceGatherer.state === undefined) {
  4251. iceGatherer.state = 'completed';
  4252. }
  4253. // Emit a candidate with type endOfCandidates to make the samples
  4254. // work. Edge requires addIceCandidate with this empty candidate
  4255. // to start checking. The real solution is to signal
  4256. // end-of-candidates to the other side when getting the null
  4257. // candidate but some apps (like the samples) don't do that.
  4258. event.candidate.candidate =
  4259. 'candidate:1 1 udp 1 0.0.0.0 9 typ endOfCandidates';
  4260. } else {
  4261. // RTCIceCandidate doesn't have a component, needs to be added
  4262. cand.component = iceTransport.component === 'RTCP' ? 2 : 1;
  4263. event.candidate.candidate = SDPUtils.writeCandidate(cand);
  4264. }
  4265. // update local description.
  4266. var sections = SDPUtils.splitSections(self.localDescription.sdp);
  4267. if (event.candidate.candidate.indexOf('typ endOfCandidates')
  4268. === -1) {
  4269. sections[event.candidate.sdpMLineIndex + 1] +=
  4270. 'a=' + event.candidate.candidate + '\r\n';
  4271. } else {
  4272. sections[event.candidate.sdpMLineIndex + 1] +=
  4273. 'a=end-of-candidates\r\n';
  4274. }
  4275. self.localDescription.sdp = sections.join('');
  4276. var complete = self.transceivers.every(function(transceiver) {
  4277. return transceiver.iceGatherer &&
  4278. transceiver.iceGatherer.state === 'completed';
  4279. });
  4280. // Emit candidate if localDescription is set.
  4281. // Also emits null candidate when all gatherers are complete.
  4282. switch (self.iceGatheringState) {
  4283. case 'new':
  4284. self._localIceCandidatesBuffer.push(event);
  4285. if (end && complete) {
  4286. self._localIceCandidatesBuffer.push(
  4287. new Event('icecandidate'));
  4288. }
  4289. break;
  4290. case 'gathering':
  4291. self._emitBufferedCandidates();
  4292. self.dispatchEvent(event);
  4293. if (self.onicecandidate !== null) {
  4294. self.onicecandidate(event);
  4295. }
  4296. if (complete) {
  4297. self.dispatchEvent(new Event('icecandidate'));
  4298. if (self.onicecandidate !== null) {
  4299. self.onicecandidate(new Event('icecandidate'));
  4300. }
  4301. self.iceGatheringState = 'complete';
  4302. }
  4303. break;
  4304. case 'complete':
  4305. // should not happen... currently!
  4306. break;
  4307. default: // no-op.
  4308. break;
  4309. }
  4310. };
  4311. iceTransport.onicestatechange = function() {
  4312. self._updateConnectionState();
  4313. };
  4314. var dtlsTransport = new RTCDtlsTransport(iceTransport);
  4315. dtlsTransport.ondtlsstatechange = function() {
  4316. self._updateConnectionState();
  4317. };
  4318. dtlsTransport.onerror = function() {
  4319. // onerror does not set state to failed by itself.
  4320. dtlsTransport.state = 'failed';
  4321. self._updateConnectionState();
  4322. };
  4323. return {
  4324. iceGatherer: iceGatherer,
  4325. iceTransport: iceTransport,
  4326. dtlsTransport: dtlsTransport
  4327. };
  4328. };
  4329. // Start the RTP Sender and Receiver for a transceiver.
  4330. window.RTCPeerConnection.prototype._transceive = function(transceiver,
  4331. send, recv) {
  4332. var params = this._getCommonCapabilities(transceiver.localCapabilities,
  4333. transceiver.remoteCapabilities);
  4334. if (send && transceiver.rtpSender) {
  4335. params.encodings = transceiver.sendEncodingParameters;
  4336. params.rtcp = {
  4337. cname: SDPUtils.localCName
  4338. };
  4339. if (transceiver.recvEncodingParameters.length) {
  4340. params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
  4341. }
  4342. transceiver.rtpSender.send(params);
  4343. }
  4344. if (recv && transceiver.rtpReceiver) {
  4345. params.encodings = transceiver.recvEncodingParameters;
  4346. params.rtcp = {
  4347. cname: transceiver.cname
  4348. };
  4349. if (transceiver.sendEncodingParameters.length) {
  4350. params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
  4351. }
  4352. transceiver.rtpReceiver.receive(params);
  4353. }
  4354. };
  4355. window.RTCPeerConnection.prototype.setLocalDescription =
  4356. function(description) {
  4357. var self = this;
  4358. var sections;
  4359. var sessionpart;
  4360. if (description.type === 'offer') {
  4361. // FIXME: What was the purpose of this empty if statement?
  4362. // if (!this._pendingOffer) {
  4363. // } else {
  4364. if (this._pendingOffer) {
  4365. // VERY limited support for SDP munging. Limited to:
  4366. // * changing the order of codecs
  4367. sections = SDPUtils.splitSections(description.sdp);
  4368. sessionpart = sections.shift();
  4369. sections.forEach(function(mediaSection, sdpMLineIndex) {
  4370. var caps = SDPUtils.parseRtpParameters(mediaSection);
  4371. self._pendingOffer[sdpMLineIndex].localCapabilities = caps;
  4372. });
  4373. this.transceivers = this._pendingOffer;
  4374. delete this._pendingOffer;
  4375. }
  4376. } else if (description.type === 'answer') {
  4377. sections = SDPUtils.splitSections(self.remoteDescription.sdp);
  4378. sessionpart = sections.shift();
  4379. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  4380. 'a=ice-lite').length > 0;
  4381. sections.forEach(function(mediaSection, sdpMLineIndex) {
  4382. var transceiver = self.transceivers[sdpMLineIndex];
  4383. var iceGatherer = transceiver.iceGatherer;
  4384. var iceTransport = transceiver.iceTransport;
  4385. var dtlsTransport = transceiver.dtlsTransport;
  4386. var localCapabilities = transceiver.localCapabilities;
  4387. var remoteCapabilities = transceiver.remoteCapabilities;
  4388. var rejected = mediaSection.split('\n', 1)[0]
  4389. .split(' ', 2)[1] === '0';
  4390. if (!rejected) {
  4391. var remoteIceParameters = SDPUtils.getIceParameters(
  4392. mediaSection, sessionpart);
  4393. if (isIceLite) {
  4394. var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
  4395. .map(function(cand) {
  4396. return SDPUtils.parseCandidate(cand);
  4397. })
  4398. .filter(function(cand) {
  4399. return cand.component === '1';
  4400. });
  4401. // ice-lite only includes host candidates in the SDP so we can
  4402. // use setRemoteCandidates (which implies an
  4403. // RTCIceCandidateComplete)
  4404. if (cands.length) {
  4405. iceTransport.setRemoteCandidates(cands);
  4406. }
  4407. }
  4408. var remoteDtlsParameters = SDPUtils.getDtlsParameters(
  4409. mediaSection, sessionpart);
  4410. if (isIceLite) {
  4411. remoteDtlsParameters.role = 'server';
  4412. }
  4413. if (!self.usingBundle || sdpMLineIndex === 0) {
  4414. iceTransport.start(iceGatherer, remoteIceParameters,
  4415. isIceLite ? 'controlling' : 'controlled');
  4416. dtlsTransport.start(remoteDtlsParameters);
  4417. }
  4418. // Calculate intersection of capabilities.
  4419. var params = self._getCommonCapabilities(localCapabilities,
  4420. remoteCapabilities);
  4421. // Start the RTCRtpSender. The RTCRtpReceiver for this
  4422. // transceiver has already been started in setRemoteDescription.
  4423. self._transceive(transceiver,
  4424. params.codecs.length > 0,
  4425. false);
  4426. }
  4427. });
  4428. }
  4429. this.localDescription = {
  4430. type: description.type,
  4431. sdp: description.sdp
  4432. };
  4433. switch (description.type) {
  4434. case 'offer':
  4435. this._updateSignalingState('have-local-offer');
  4436. break;
  4437. case 'answer':
  4438. this._updateSignalingState('stable');
  4439. break;
  4440. default:
  4441. throw new TypeError('unsupported type "' + description.type +
  4442. '"');
  4443. }
  4444. // If a success callback was provided, emit ICE candidates after it
  4445. // has been executed. Otherwise, emit callback after the Promise is
  4446. // resolved.
  4447. var hasCallback = arguments.length > 1 &&
  4448. typeof arguments[1] === 'function';
  4449. if (hasCallback) {
  4450. var cb = arguments[1];
  4451. window.setTimeout(function() {
  4452. cb();
  4453. if (self.iceGatheringState === 'new') {
  4454. self.iceGatheringState = 'gathering';
  4455. }
  4456. self._emitBufferedCandidates();
  4457. }, 0);
  4458. }
  4459. var p = Promise.resolve();
  4460. p.then(function() {
  4461. if (!hasCallback) {
  4462. if (self.iceGatheringState === 'new') {
  4463. self.iceGatheringState = 'gathering';
  4464. }
  4465. // Usually candidates will be emitted earlier.
  4466. window.setTimeout(self._emitBufferedCandidates.bind(self), 500);
  4467. }
  4468. });
  4469. return p;
  4470. };
  4471. window.RTCPeerConnection.prototype.setRemoteDescription =
  4472. function(description) {
  4473. var self = this;
  4474. var stream = new MediaStream();
  4475. var receiverList = [];
  4476. var sections = SDPUtils.splitSections(description.sdp);
  4477. var sessionpart = sections.shift();
  4478. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  4479. 'a=ice-lite').length > 0;
  4480. this.usingBundle = SDPUtils.matchPrefix(sessionpart,
  4481. 'a=group:BUNDLE ').length > 0;
  4482. sections.forEach(function(mediaSection, sdpMLineIndex) {
  4483. var lines = SDPUtils.splitLines(mediaSection);
  4484. var mline = lines[0].substr(2).split(' ');
  4485. var kind = mline[0];
  4486. var rejected = mline[1] === '0';
  4487. var direction = SDPUtils.getDirection(mediaSection, sessionpart);
  4488. var transceiver;
  4489. var iceGatherer;
  4490. var iceTransport;
  4491. var dtlsTransport;
  4492. var rtpSender;
  4493. var rtpReceiver;
  4494. var sendEncodingParameters;
  4495. var recvEncodingParameters;
  4496. var localCapabilities;
  4497. var track;
  4498. // FIXME: ensure the mediaSection has rtcp-mux set.
  4499. var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection);
  4500. var remoteIceParameters;
  4501. var remoteDtlsParameters;
  4502. if (!rejected) {
  4503. remoteIceParameters = SDPUtils.getIceParameters(mediaSection,
  4504. sessionpart);
  4505. remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection,
  4506. sessionpart);
  4507. remoteDtlsParameters.role = 'client';
  4508. }
  4509. recvEncodingParameters =
  4510. SDPUtils.parseRtpEncodingParameters(mediaSection);
  4511. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:');
  4512. if (mid.length) {
  4513. mid = mid[0].substr(6);
  4514. } else {
  4515. mid = SDPUtils.generateIdentifier();
  4516. }
  4517. var cname;
  4518. // Gets the first SSRC. Note that with RTX there might be multiple
  4519. // SSRCs.
  4520. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  4521. .map(function(line) {
  4522. return SDPUtils.parseSsrcMedia(line);
  4523. })
  4524. .filter(function(obj) {
  4525. return obj.attribute === 'cname';
  4526. })[0];
  4527. if (remoteSsrc) {
  4528. cname = remoteSsrc.value;
  4529. }
  4530. var isComplete = SDPUtils.matchPrefix(mediaSection,
  4531. 'a=end-of-candidates').length > 0;
  4532. var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
  4533. .map(function(cand) {
  4534. return SDPUtils.parseCandidate(cand);
  4535. })
  4536. .filter(function(cand) {
  4537. return cand.component === '1';
  4538. });
  4539. if (description.type === 'offer' && !rejected) {
  4540. var transports = self.usingBundle && sdpMLineIndex > 0 ? {
  4541. iceGatherer: self.transceivers[0].iceGatherer,
  4542. iceTransport: self.transceivers[0].iceTransport,
  4543. dtlsTransport: self.transceivers[0].dtlsTransport
  4544. } : self._createIceAndDtlsTransports(mid, sdpMLineIndex);
  4545. if (isComplete) {
  4546. transports.iceTransport.setRemoteCandidates(cands);
  4547. }
  4548. localCapabilities = RTCRtpReceiver.getCapabilities(kind);
  4549. sendEncodingParameters = [{
  4550. ssrc: (2 * sdpMLineIndex + 2) * 1001
  4551. }];
  4552. rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind);
  4553. track = rtpReceiver.track;
  4554. receiverList.push([track, rtpReceiver]);
  4555. // FIXME: not correct when there are multiple streams but that is
  4556. // not currently supported in this shim.
  4557. stream.addTrack(track);
  4558. // FIXME: look at direction.
  4559. if (self.localStreams.length > 0 &&
  4560. self.localStreams[0].getTracks().length >= sdpMLineIndex) {
  4561. // FIXME: actually more complicated, needs to match types etc
  4562. var localtrack = self.localStreams[0]
  4563. .getTracks()[sdpMLineIndex];
  4564. rtpSender = new RTCRtpSender(localtrack,
  4565. transports.dtlsTransport);
  4566. }
  4567. self.transceivers[sdpMLineIndex] = {
  4568. iceGatherer: transports.iceGatherer,
  4569. iceTransport: transports.iceTransport,
  4570. dtlsTransport: transports.dtlsTransport,
  4571. localCapabilities: localCapabilities,
  4572. remoteCapabilities: remoteCapabilities,
  4573. rtpSender: rtpSender,
  4574. rtpReceiver: rtpReceiver,
  4575. kind: kind,
  4576. mid: mid,
  4577. cname: cname,
  4578. sendEncodingParameters: sendEncodingParameters,
  4579. recvEncodingParameters: recvEncodingParameters
  4580. };
  4581. // Start the RTCRtpReceiver now. The RTPSender is started in
  4582. // setLocalDescription.
  4583. self._transceive(self.transceivers[sdpMLineIndex],
  4584. false,
  4585. direction === 'sendrecv' || direction === 'sendonly');
  4586. } else if (description.type === 'answer' && !rejected) {
  4587. transceiver = self.transceivers[sdpMLineIndex];
  4588. iceGatherer = transceiver.iceGatherer;
  4589. iceTransport = transceiver.iceTransport;
  4590. dtlsTransport = transceiver.dtlsTransport;
  4591. rtpSender = transceiver.rtpSender;
  4592. rtpReceiver = transceiver.rtpReceiver;
  4593. sendEncodingParameters = transceiver.sendEncodingParameters;
  4594. localCapabilities = transceiver.localCapabilities;
  4595. self.transceivers[sdpMLineIndex].recvEncodingParameters =
  4596. recvEncodingParameters;
  4597. self.transceivers[sdpMLineIndex].remoteCapabilities =
  4598. remoteCapabilities;
  4599. self.transceivers[sdpMLineIndex].cname = cname;
  4600. if ((isIceLite || isComplete) && cands.length) {
  4601. iceTransport.setRemoteCandidates(cands);
  4602. }
  4603. if (!self.usingBundle || sdpMLineIndex === 0) {
  4604. iceTransport.start(iceGatherer, remoteIceParameters,
  4605. 'controlling');
  4606. dtlsTransport.start(remoteDtlsParameters);
  4607. }
  4608. self._transceive(transceiver,
  4609. direction === 'sendrecv' || direction === 'recvonly',
  4610. direction === 'sendrecv' || direction === 'sendonly');
  4611. if (rtpReceiver &&
  4612. (direction === 'sendrecv' || direction === 'sendonly')) {
  4613. track = rtpReceiver.track;
  4614. receiverList.push([track, rtpReceiver]);
  4615. stream.addTrack(track);
  4616. } else {
  4617. // FIXME: actually the receiver should be created later.
  4618. delete transceiver.rtpReceiver;
  4619. }
  4620. }
  4621. });
  4622. this.remoteDescription = {
  4623. type: description.type,
  4624. sdp: description.sdp
  4625. };
  4626. switch (description.type) {
  4627. case 'offer':
  4628. this._updateSignalingState('have-remote-offer');
  4629. break;
  4630. case 'answer':
  4631. this._updateSignalingState('stable');
  4632. break;
  4633. default:
  4634. throw new TypeError('unsupported type "' + description.type +
  4635. '"');
  4636. }
  4637. if (stream.getTracks().length) {
  4638. self.remoteStreams.push(stream);
  4639. window.setTimeout(function() {
  4640. var event = new Event('addstream');
  4641. event.stream = stream;
  4642. self.dispatchEvent(event);
  4643. if (self.onaddstream !== null) {
  4644. window.setTimeout(function() {
  4645. self.onaddstream(event);
  4646. }, 0);
  4647. }
  4648. receiverList.forEach(function(item) {
  4649. var track = item[0];
  4650. var receiver = item[1];
  4651. var trackEvent = new Event('track');
  4652. trackEvent.track = track;
  4653. trackEvent.receiver = receiver;
  4654. trackEvent.streams = [stream];
  4655. self.dispatchEvent(event);
  4656. if (self.ontrack !== null) {
  4657. window.setTimeout(function() {
  4658. self.ontrack(trackEvent);
  4659. }, 0);
  4660. }
  4661. });
  4662. }, 0);
  4663. }
  4664. if (arguments.length > 1 && typeof arguments[1] === 'function') {
  4665. window.setTimeout(arguments[1], 0);
  4666. }
  4667. return Promise.resolve();
  4668. };
  4669. window.RTCPeerConnection.prototype.close = function() {
  4670. this.transceivers.forEach(function(transceiver) {
  4671. /* not yet
  4672. if (transceiver.iceGatherer) {
  4673. transceiver.iceGatherer.close();
  4674. }
  4675. */
  4676. if (transceiver.iceTransport) {
  4677. transceiver.iceTransport.stop();
  4678. }
  4679. if (transceiver.dtlsTransport) {
  4680. transceiver.dtlsTransport.stop();
  4681. }
  4682. if (transceiver.rtpSender) {
  4683. transceiver.rtpSender.stop();
  4684. }
  4685. if (transceiver.rtpReceiver) {
  4686. transceiver.rtpReceiver.stop();
  4687. }
  4688. });
  4689. // FIXME: clean up tracks, local streams, remote streams, etc
  4690. this._updateSignalingState('closed');
  4691. };
  4692. // Update the signaling state.
  4693. window.RTCPeerConnection.prototype._updateSignalingState =
  4694. function(newState) {
  4695. this.signalingState = newState;
  4696. var event = new Event('signalingstatechange');
  4697. this.dispatchEvent(event);
  4698. if (this.onsignalingstatechange !== null) {
  4699. this.onsignalingstatechange(event);
  4700. }
  4701. };
  4702. // Determine whether to fire the negotiationneeded event.
  4703. window.RTCPeerConnection.prototype._maybeFireNegotiationNeeded =
  4704. function() {
  4705. // Fire away (for now).
  4706. var event = new Event('negotiationneeded');
  4707. this.dispatchEvent(event);
  4708. if (this.onnegotiationneeded !== null) {
  4709. this.onnegotiationneeded(event);
  4710. }
  4711. };
  4712. // Update the connection state.
  4713. window.RTCPeerConnection.prototype._updateConnectionState = function() {
  4714. var self = this;
  4715. var newState;
  4716. var states = {
  4717. 'new': 0,
  4718. closed: 0,
  4719. connecting: 0,
  4720. checking: 0,
  4721. connected: 0,
  4722. completed: 0,
  4723. failed: 0
  4724. };
  4725. this.transceivers.forEach(function(transceiver) {
  4726. states[transceiver.iceTransport.state]++;
  4727. states[transceiver.dtlsTransport.state]++;
  4728. });
  4729. // ICETransport.completed and connected are the same for this purpose.
  4730. states.connected += states.completed;
  4731. newState = 'new';
  4732. if (states.failed > 0) {
  4733. newState = 'failed';
  4734. } else if (states.connecting > 0 || states.checking > 0) {
  4735. newState = 'connecting';
  4736. } else if (states.disconnected > 0) {
  4737. newState = 'disconnected';
  4738. } else if (states.new > 0) {
  4739. newState = 'new';
  4740. } else if (states.connected > 0 || states.completed > 0) {
  4741. newState = 'connected';
  4742. }
  4743. if (newState !== self.iceConnectionState) {
  4744. self.iceConnectionState = newState;
  4745. var event = new Event('iceconnectionstatechange');
  4746. this.dispatchEvent(event);
  4747. if (this.oniceconnectionstatechange !== null) {
  4748. this.oniceconnectionstatechange(event);
  4749. }
  4750. }
  4751. };
  4752. window.RTCPeerConnection.prototype.createOffer = function() {
  4753. var self = this;
  4754. if (this._pendingOffer) {
  4755. throw new Error('createOffer called while there is a pending offer.');
  4756. }
  4757. var offerOptions;
  4758. if (arguments.length === 1 && typeof arguments[0] !== 'function') {
  4759. offerOptions = arguments[0];
  4760. } else if (arguments.length === 3) {
  4761. offerOptions = arguments[2];
  4762. }
  4763. var tracks = [];
  4764. var numAudioTracks = 0;
  4765. var numVideoTracks = 0;
  4766. // Default to sendrecv.
  4767. if (this.localStreams.length) {
  4768. numAudioTracks = this.localStreams[0].getAudioTracks().length;
  4769. numVideoTracks = this.localStreams[0].getVideoTracks().length;
  4770. }
  4771. // Determine number of audio and video tracks we need to send/recv.
  4772. if (offerOptions) {
  4773. // Reject Chrome legacy constraints.
  4774. if (offerOptions.mandatory || offerOptions.optional) {
  4775. throw new TypeError(
  4776. 'Legacy mandatory/optional constraints not supported.');
  4777. }
  4778. if (offerOptions.offerToReceiveAudio !== undefined) {
  4779. numAudioTracks = offerOptions.offerToReceiveAudio;
  4780. }
  4781. if (offerOptions.offerToReceiveVideo !== undefined) {
  4782. numVideoTracks = offerOptions.offerToReceiveVideo;
  4783. }
  4784. }
  4785. if (this.localStreams.length) {
  4786. // Push local streams.
  4787. this.localStreams[0].getTracks().forEach(function(track) {
  4788. tracks.push({
  4789. kind: track.kind,
  4790. track: track,
  4791. wantReceive: track.kind === 'audio' ?
  4792. numAudioTracks > 0 : numVideoTracks > 0
  4793. });
  4794. if (track.kind === 'audio') {
  4795. numAudioTracks--;
  4796. } else if (track.kind === 'video') {
  4797. numVideoTracks--;
  4798. }
  4799. });
  4800. }
  4801. // Create M-lines for recvonly streams.
  4802. while (numAudioTracks > 0 || numVideoTracks > 0) {
  4803. if (numAudioTracks > 0) {
  4804. tracks.push({
  4805. kind: 'audio',
  4806. wantReceive: true
  4807. });
  4808. numAudioTracks--;
  4809. }
  4810. if (numVideoTracks > 0) {
  4811. tracks.push({
  4812. kind: 'video',
  4813. wantReceive: true
  4814. });
  4815. numVideoTracks--;
  4816. }
  4817. }
  4818. var sdp = SDPUtils.writeSessionBoilerplate();
  4819. var transceivers = [];
  4820. tracks.forEach(function(mline, sdpMLineIndex) {
  4821. // For each track, create an ice gatherer, ice transport,
  4822. // dtls transport, potentially rtpsender and rtpreceiver.
  4823. var track = mline.track;
  4824. var kind = mline.kind;
  4825. var mid = SDPUtils.generateIdentifier();
  4826. var transports = self.usingBundle && sdpMLineIndex > 0 ? {
  4827. iceGatherer: transceivers[0].iceGatherer,
  4828. iceTransport: transceivers[0].iceTransport,
  4829. dtlsTransport: transceivers[0].dtlsTransport
  4830. } : self._createIceAndDtlsTransports(mid, sdpMLineIndex);
  4831. var localCapabilities = RTCRtpSender.getCapabilities(kind);
  4832. var rtpSender;
  4833. var rtpReceiver;
  4834. // generate an ssrc now, to be used later in rtpSender.send
  4835. var sendEncodingParameters = [{
  4836. ssrc: (2 * sdpMLineIndex + 1) * 1001
  4837. }];
  4838. if (track) {
  4839. rtpSender = new RTCRtpSender(track, transports.dtlsTransport);
  4840. }
  4841. if (mline.wantReceive) {
  4842. rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind);
  4843. }
  4844. transceivers[sdpMLineIndex] = {
  4845. iceGatherer: transports.iceGatherer,
  4846. iceTransport: transports.iceTransport,
  4847. dtlsTransport: transports.dtlsTransport,
  4848. localCapabilities: localCapabilities,
  4849. remoteCapabilities: null,
  4850. rtpSender: rtpSender,
  4851. rtpReceiver: rtpReceiver,
  4852. kind: kind,
  4853. mid: mid,
  4854. sendEncodingParameters: sendEncodingParameters,
  4855. recvEncodingParameters: null
  4856. };
  4857. });
  4858. if (this.usingBundle) {
  4859. sdp += 'a=group:BUNDLE ' + transceivers.map(function(t) {
  4860. return t.mid;
  4861. }).join(' ') + '\r\n';
  4862. }
  4863. tracks.forEach(function(mline, sdpMLineIndex) {
  4864. var transceiver = transceivers[sdpMLineIndex];
  4865. sdp += SDPUtils.writeMediaSection(transceiver,
  4866. transceiver.localCapabilities, 'offer', self.localStreams[0]);
  4867. });
  4868. this._pendingOffer = transceivers;
  4869. var desc = new RTCSessionDescription({
  4870. type: 'offer',
  4871. sdp: sdp
  4872. });
  4873. if (arguments.length && typeof arguments[0] === 'function') {
  4874. window.setTimeout(arguments[0], 0, desc);
  4875. }
  4876. return Promise.resolve(desc);
  4877. };
  4878. window.RTCPeerConnection.prototype.createAnswer = function() {
  4879. var self = this;
  4880. var sdp = SDPUtils.writeSessionBoilerplate();
  4881. if (this.usingBundle) {
  4882. sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) {
  4883. return t.mid;
  4884. }).join(' ') + '\r\n';
  4885. }
  4886. this.transceivers.forEach(function(transceiver) {
  4887. // Calculate intersection of capabilities.
  4888. var commonCapabilities = self._getCommonCapabilities(
  4889. transceiver.localCapabilities,
  4890. transceiver.remoteCapabilities);
  4891. sdp += SDPUtils.writeMediaSection(transceiver, commonCapabilities,
  4892. 'answer', self.localStreams[0]);
  4893. });
  4894. var desc = new RTCSessionDescription({
  4895. type: 'answer',
  4896. sdp: sdp
  4897. });
  4898. if (arguments.length && typeof arguments[0] === 'function') {
  4899. window.setTimeout(arguments[0], 0, desc);
  4900. }
  4901. return Promise.resolve(desc);
  4902. };
  4903. window.RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
  4904. if (candidate === null) {
  4905. this.transceivers.forEach(function(transceiver) {
  4906. transceiver.iceTransport.addRemoteCandidate({});
  4907. });
  4908. } else {
  4909. var mLineIndex = candidate.sdpMLineIndex;
  4910. if (candidate.sdpMid) {
  4911. for (var i = 0; i < this.transceivers.length; i++) {
  4912. if (this.transceivers[i].mid === candidate.sdpMid) {
  4913. mLineIndex = i;
  4914. break;
  4915. }
  4916. }
  4917. }
  4918. var transceiver = this.transceivers[mLineIndex];
  4919. if (transceiver) {
  4920. var cand = Object.keys(candidate.candidate).length > 0 ?
  4921. SDPUtils.parseCandidate(candidate.candidate) : {};
  4922. // Ignore Chrome's invalid candidates since Edge does not like them.
  4923. if (cand.protocol === 'tcp' && cand.port === 0) {
  4924. return;
  4925. }
  4926. // Ignore RTCP candidates, we assume RTCP-MUX.
  4927. if (cand.component !== '1') {
  4928. return;
  4929. }
  4930. // A dirty hack to make samples work.
  4931. if (cand.type === 'endOfCandidates') {
  4932. cand = {};
  4933. }
  4934. transceiver.iceTransport.addRemoteCandidate(cand);
  4935. // update the remoteDescription.
  4936. var sections = SDPUtils.splitSections(this.remoteDescription.sdp);
  4937. sections[mLineIndex + 1] += (cand.type ? candidate.candidate.trim()
  4938. : 'a=end-of-candidates') + '\r\n';
  4939. this.remoteDescription.sdp = sections.join('');
  4940. }
  4941. }
  4942. if (arguments.length > 1 && typeof arguments[1] === 'function') {
  4943. window.setTimeout(arguments[1], 0);
  4944. }
  4945. return Promise.resolve();
  4946. };
  4947. window.RTCPeerConnection.prototype.getStats = function() {
  4948. var promises = [];
  4949. this.transceivers.forEach(function(transceiver) {
  4950. ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
  4951. 'dtlsTransport'].forEach(function(method) {
  4952. if (transceiver[method]) {
  4953. promises.push(transceiver[method].getStats());
  4954. }
  4955. });
  4956. });
  4957. var cb = arguments.length > 1 && typeof arguments[1] === 'function' &&
  4958. arguments[1];
  4959. return new Promise(function(resolve) {
  4960. // shim getStats with maplike support
  4961. var results = new Map();
  4962. Promise.all(promises).then(function(res) {
  4963. res.forEach(function(result) {
  4964. Object.keys(result).forEach(function(id) {
  4965. results.set(id, result[id]);
  4966. results[id] = result[id];
  4967. });
  4968. });
  4969. if (cb) {
  4970. window.setTimeout(cb, 0, results);
  4971. }
  4972. resolve(results);
  4973. });
  4974. });
  4975. };
  4976. },
  4977. // Attach a media stream to an element.
  4978. attachMediaStream: function(element, stream) {
  4979. logging('DEPRECATED, attachMediaStream will soon be removed.');
  4980. element.srcObject = stream;
  4981. },
  4982. reattachMediaStream: function(to, from) {
  4983. logging('DEPRECATED, reattachMediaStream will soon be removed.');
  4984. to.srcObject = from.srcObject;
  4985. }
  4986. };
  4987. // Expose public methods.
  4988. module.exports = {
  4989. shimPeerConnection: edgeShim.shimPeerConnection,
  4990. shimGetUserMedia: require('./getusermedia'),
  4991. attachMediaStream: edgeShim.attachMediaStream,
  4992. reattachMediaStream: edgeShim.reattachMediaStream
  4993. };
  4994. },{"../utils":38,"./getusermedia":34,"sdp":62}],34:[function(require,module,exports){
  4995. /*
  4996. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4997. *
  4998. * Use of this source code is governed by a BSD-style license
  4999. * that can be found in the LICENSE file in the root of the source
  5000. * tree.
  5001. */
  5002. /* eslint-env node */
  5003. 'use strict';
  5004. // Expose public methods.
  5005. module.exports = function() {
  5006. var shimError_ = function(e) {
  5007. return {
  5008. name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name,
  5009. message: e.message,
  5010. constraint: e.constraint,
  5011. toString: function() {
  5012. return this.name;
  5013. }
  5014. };
  5015. };
  5016. // getUserMedia error shim.
  5017. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  5018. bind(navigator.mediaDevices);
  5019. navigator.mediaDevices.getUserMedia = function(c) {
  5020. return origGetUserMedia(c).catch(function(e) {
  5021. return Promise.reject(shimError_(e));
  5022. });
  5023. };
  5024. };
  5025. },{}],35:[function(require,module,exports){
  5026. /*
  5027. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  5028. *
  5029. * Use of this source code is governed by a BSD-style license
  5030. * that can be found in the LICENSE file in the root of the source
  5031. * tree.
  5032. */
  5033. /* eslint-env node */
  5034. 'use strict';
  5035. var logging = require('../utils').log;
  5036. var browserDetails = require('../utils').browserDetails;
  5037. var firefoxShim = {
  5038. shimOnTrack: function() {
  5039. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  5040. window.RTCPeerConnection.prototype)) {
  5041. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  5042. get: function() {
  5043. return this._ontrack;
  5044. },
  5045. set: function(f) {
  5046. if (this._ontrack) {
  5047. this.removeEventListener('track', this._ontrack);
  5048. this.removeEventListener('addstream', this._ontrackpoly);
  5049. }
  5050. this.addEventListener('track', this._ontrack = f);
  5051. this.addEventListener('addstream', this._ontrackpoly = function(e) {
  5052. e.stream.getTracks().forEach(function(track) {
  5053. var event = new Event('track');
  5054. event.track = track;
  5055. event.receiver = {track: track};
  5056. event.streams = [e.stream];
  5057. this.dispatchEvent(event);
  5058. }.bind(this));
  5059. }.bind(this));
  5060. }
  5061. });
  5062. }
  5063. },
  5064. shimSourceObject: function() {
  5065. // Firefox has supported mozSrcObject since FF22, unprefixed in 42.
  5066. if (typeof window === 'object') {
  5067. if (window.HTMLMediaElement &&
  5068. !('srcObject' in window.HTMLMediaElement.prototype)) {
  5069. // Shim the srcObject property, once, when HTMLMediaElement is found.
  5070. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
  5071. get: function() {
  5072. return this.mozSrcObject;
  5073. },
  5074. set: function(stream) {
  5075. this.mozSrcObject = stream;
  5076. }
  5077. });
  5078. }
  5079. }
  5080. },
  5081. shimPeerConnection: function() {
  5082. if (typeof window !== 'object' || !(window.RTCPeerConnection ||
  5083. window.mozRTCPeerConnection)) {
  5084. return; // probably media.peerconnection.enabled=false in about:config
  5085. }
  5086. // The RTCPeerConnection object.
  5087. if (!window.RTCPeerConnection) {
  5088. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  5089. if (browserDetails.version < 38) {
  5090. // .urls is not supported in FF < 38.
  5091. // create RTCIceServers with a single url.
  5092. if (pcConfig && pcConfig.iceServers) {
  5093. var newIceServers = [];
  5094. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  5095. var server = pcConfig.iceServers[i];
  5096. if (server.hasOwnProperty('urls')) {
  5097. for (var j = 0; j < server.urls.length; j++) {
  5098. var newServer = {
  5099. url: server.urls[j]
  5100. };
  5101. if (server.urls[j].indexOf('turn') === 0) {
  5102. newServer.username = server.username;
  5103. newServer.credential = server.credential;
  5104. }
  5105. newIceServers.push(newServer);
  5106. }
  5107. } else {
  5108. newIceServers.push(pcConfig.iceServers[i]);
  5109. }
  5110. }
  5111. pcConfig.iceServers = newIceServers;
  5112. }
  5113. }
  5114. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  5115. };
  5116. window.RTCPeerConnection.prototype = mozRTCPeerConnection.prototype;
  5117. // wrap static methods. Currently just generateCertificate.
  5118. if (mozRTCPeerConnection.generateCertificate) {
  5119. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  5120. get: function() {
  5121. return mozRTCPeerConnection.generateCertificate;
  5122. }
  5123. });
  5124. }
  5125. window.RTCSessionDescription = mozRTCSessionDescription;
  5126. window.RTCIceCandidate = mozRTCIceCandidate;
  5127. }
  5128. // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
  5129. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  5130. .forEach(function(method) {
  5131. var nativeMethod = RTCPeerConnection.prototype[method];
  5132. RTCPeerConnection.prototype[method] = function() {
  5133. arguments[0] = new ((method === 'addIceCandidate') ?
  5134. RTCIceCandidate : RTCSessionDescription)(arguments[0]);
  5135. return nativeMethod.apply(this, arguments);
  5136. };
  5137. });
  5138. // support for addIceCandidate(null)
  5139. var nativeAddIceCandidate =
  5140. RTCPeerConnection.prototype.addIceCandidate;
  5141. RTCPeerConnection.prototype.addIceCandidate = function() {
  5142. return arguments[0] === null ? Promise.resolve()
  5143. : nativeAddIceCandidate.apply(this, arguments);
  5144. };
  5145. // shim getStats with maplike support
  5146. var makeMapStats = function(stats) {
  5147. var map = new Map();
  5148. Object.keys(stats).forEach(function(key) {
  5149. map.set(key, stats[key]);
  5150. map[key] = stats[key];
  5151. });
  5152. return map;
  5153. };
  5154. var nativeGetStats = RTCPeerConnection.prototype.getStats;
  5155. RTCPeerConnection.prototype.getStats = function(selector, onSucc, onErr) {
  5156. return nativeGetStats.apply(this, [selector || null])
  5157. .then(function(stats) {
  5158. return makeMapStats(stats);
  5159. })
  5160. .then(onSucc, onErr);
  5161. };
  5162. },
  5163. // Attach a media stream to an element.
  5164. attachMediaStream: function(element, stream) {
  5165. logging('DEPRECATED, attachMediaStream will soon be removed.');
  5166. element.srcObject = stream;
  5167. },
  5168. reattachMediaStream: function(to, from) {
  5169. logging('DEPRECATED, reattachMediaStream will soon be removed.');
  5170. to.srcObject = from.srcObject;
  5171. }
  5172. };
  5173. // Expose public methods.
  5174. module.exports = {
  5175. shimOnTrack: firefoxShim.shimOnTrack,
  5176. shimSourceObject: firefoxShim.shimSourceObject,
  5177. shimPeerConnection: firefoxShim.shimPeerConnection,
  5178. shimGetUserMedia: require('./getusermedia'),
  5179. attachMediaStream: firefoxShim.attachMediaStream,
  5180. reattachMediaStream: firefoxShim.reattachMediaStream
  5181. };
  5182. },{"../utils":38,"./getusermedia":36}],36:[function(require,module,exports){
  5183. /*
  5184. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  5185. *
  5186. * Use of this source code is governed by a BSD-style license
  5187. * that can be found in the LICENSE file in the root of the source
  5188. * tree.
  5189. */
  5190. /* eslint-env node */
  5191. 'use strict';
  5192. var logging = require('../utils').log;
  5193. var browserDetails = require('../utils').browserDetails;
  5194. // Expose public methods.
  5195. module.exports = function() {
  5196. var shimError_ = function(e) {
  5197. return {
  5198. name: {
  5199. SecurityError: 'NotAllowedError',
  5200. PermissionDeniedError: 'NotAllowedError'
  5201. }[e.name] || e.name,
  5202. message: {
  5203. 'The operation is insecure.': 'The request is not allowed by the ' +
  5204. 'user agent or the platform in the current context.'
  5205. }[e.message] || e.message,
  5206. constraint: e.constraint,
  5207. toString: function() {
  5208. return this.name + (this.message && ': ') + this.message;
  5209. }
  5210. };
  5211. };
  5212. // getUserMedia constraints shim.
  5213. var getUserMedia_ = function(constraints, onSuccess, onError) {
  5214. var constraintsToFF37_ = function(c) {
  5215. if (typeof c !== 'object' || c.require) {
  5216. return c;
  5217. }
  5218. var require = [];
  5219. Object.keys(c).forEach(function(key) {
  5220. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  5221. return;
  5222. }
  5223. var r = c[key] = (typeof c[key] === 'object') ?
  5224. c[key] : {ideal: c[key]};
  5225. if (r.min !== undefined ||
  5226. r.max !== undefined || r.exact !== undefined) {
  5227. require.push(key);
  5228. }
  5229. if (r.exact !== undefined) {
  5230. if (typeof r.exact === 'number') {
  5231. r. min = r.max = r.exact;
  5232. } else {
  5233. c[key] = r.exact;
  5234. }
  5235. delete r.exact;
  5236. }
  5237. if (r.ideal !== undefined) {
  5238. c.advanced = c.advanced || [];
  5239. var oc = {};
  5240. if (typeof r.ideal === 'number') {
  5241. oc[key] = {min: r.ideal, max: r.ideal};
  5242. } else {
  5243. oc[key] = r.ideal;
  5244. }
  5245. c.advanced.push(oc);
  5246. delete r.ideal;
  5247. if (!Object.keys(r).length) {
  5248. delete c[key];
  5249. }
  5250. }
  5251. });
  5252. if (require.length) {
  5253. c.require = require;
  5254. }
  5255. return c;
  5256. };
  5257. constraints = JSON.parse(JSON.stringify(constraints));
  5258. if (browserDetails.version < 38) {
  5259. logging('spec: ' + JSON.stringify(constraints));
  5260. if (constraints.audio) {
  5261. constraints.audio = constraintsToFF37_(constraints.audio);
  5262. }
  5263. if (constraints.video) {
  5264. constraints.video = constraintsToFF37_(constraints.video);
  5265. }
  5266. logging('ff37: ' + JSON.stringify(constraints));
  5267. }
  5268. return navigator.mozGetUserMedia(constraints, onSuccess, function(e) {
  5269. onError(shimError_(e));
  5270. });
  5271. };
  5272. // Returns the result of getUserMedia as a Promise.
  5273. var getUserMediaPromise_ = function(constraints) {
  5274. return new Promise(function(resolve, reject) {
  5275. getUserMedia_(constraints, resolve, reject);
  5276. });
  5277. };
  5278. // Shim for mediaDevices on older versions.
  5279. if (!navigator.mediaDevices) {
  5280. navigator.mediaDevices = {getUserMedia: getUserMediaPromise_,
  5281. addEventListener: function() { },
  5282. removeEventListener: function() { }
  5283. };
  5284. }
  5285. navigator.mediaDevices.enumerateDevices =
  5286. navigator.mediaDevices.enumerateDevices || function() {
  5287. return new Promise(function(resolve) {
  5288. var infos = [
  5289. {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
  5290. {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
  5291. ];
  5292. resolve(infos);
  5293. });
  5294. };
  5295. if (browserDetails.version < 41) {
  5296. // Work around http://bugzil.la/1169665
  5297. var orgEnumerateDevices =
  5298. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
  5299. navigator.mediaDevices.enumerateDevices = function() {
  5300. return orgEnumerateDevices().then(undefined, function(e) {
  5301. if (e.name === 'NotFoundError') {
  5302. return [];
  5303. }
  5304. throw e;
  5305. });
  5306. };
  5307. }
  5308. if (browserDetails.version < 49) {
  5309. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  5310. bind(navigator.mediaDevices);
  5311. navigator.mediaDevices.getUserMedia = function(c) {
  5312. return origGetUserMedia(c).catch(function(e) {
  5313. return Promise.reject(shimError_(e));
  5314. });
  5315. };
  5316. }
  5317. navigator.getUserMedia = function(constraints, onSuccess, onError) {
  5318. if (browserDetails.version < 44) {
  5319. return getUserMedia_(constraints, onSuccess, onError);
  5320. }
  5321. // Replace Firefox 44+'s deprecation warning with unprefixed version.
  5322. console.warn('navigator.getUserMedia has been replaced by ' +
  5323. 'navigator.mediaDevices.getUserMedia');
  5324. navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  5325. };
  5326. };
  5327. },{"../utils":38}],37:[function(require,module,exports){
  5328. /*
  5329. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  5330. *
  5331. * Use of this source code is governed by a BSD-style license
  5332. * that can be found in the LICENSE file in the root of the source
  5333. * tree.
  5334. */
  5335. 'use strict';
  5336. var safariShim = {
  5337. // TODO: DrAlex, should be here, double check against LayoutTests
  5338. // shimOnTrack: function() { },
  5339. // TODO: DrAlex
  5340. // attachMediaStream: function(element, stream) { },
  5341. // reattachMediaStream: function(to, from) { },
  5342. // TODO: once the back-end for the mac port is done, add.
  5343. // TODO: check for webkitGTK+
  5344. // shimPeerConnection: function() { },
  5345. shimGetUserMedia: function() {
  5346. navigator.getUserMedia = navigator.webkitGetUserMedia;
  5347. }
  5348. };
  5349. // Expose public methods.
  5350. module.exports = {
  5351. shimGetUserMedia: safariShim.shimGetUserMedia
  5352. // TODO
  5353. // shimOnTrack: safariShim.shimOnTrack,
  5354. // shimPeerConnection: safariShim.shimPeerConnection,
  5355. // attachMediaStream: safariShim.attachMediaStream,
  5356. // reattachMediaStream: safariShim.reattachMediaStream
  5357. };
  5358. },{}],38:[function(require,module,exports){
  5359. /*
  5360. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  5361. *
  5362. * Use of this source code is governed by a BSD-style license
  5363. * that can be found in the LICENSE file in the root of the source
  5364. * tree.
  5365. */
  5366. /* eslint-env node */
  5367. 'use strict';
  5368. var logDisabled_ = true;
  5369. // Utility methods.
  5370. var utils = {
  5371. disableLog: function(bool) {
  5372. if (typeof bool !== 'boolean') {
  5373. return new Error('Argument type: ' + typeof bool +
  5374. '. Please use a boolean.');
  5375. }
  5376. logDisabled_ = bool;
  5377. return (bool) ? 'adapter.js logging disabled' :
  5378. 'adapter.js logging enabled';
  5379. },
  5380. log: function() {
  5381. if (typeof window === 'object') {
  5382. if (logDisabled_) {
  5383. return;
  5384. }
  5385. if (typeof console !== 'undefined' && typeof console.log === 'function') {
  5386. console.log.apply(console, arguments);
  5387. }
  5388. }
  5389. },
  5390. /**
  5391. * Extract browser version out of the provided user agent string.
  5392. *
  5393. * @param {!string} uastring userAgent string.
  5394. * @param {!string} expr Regular expression used as match criteria.
  5395. * @param {!number} pos position in the version string to be returned.
  5396. * @return {!number} browser version.
  5397. */
  5398. extractVersion: function(uastring, expr, pos) {
  5399. var match = uastring.match(expr);
  5400. return match && match.length >= pos && parseInt(match[pos], 10);
  5401. },
  5402. /**
  5403. * Browser detector.
  5404. *
  5405. * @return {object} result containing browser, version and minVersion
  5406. * properties.
  5407. */
  5408. detectBrowser: function() {
  5409. // Returned result object.
  5410. var result = {};
  5411. result.browser = null;
  5412. result.version = null;
  5413. result.minVersion = null;
  5414. // Fail early if it's not a browser
  5415. if (typeof window === 'undefined' || !window.navigator) {
  5416. result.browser = 'Not a browser.';
  5417. return result;
  5418. }
  5419. // Firefox.
  5420. if (navigator.mozGetUserMedia) {
  5421. result.browser = 'firefox';
  5422. result.version = this.extractVersion(navigator.userAgent,
  5423. /Firefox\/([0-9]+)\./, 1);
  5424. result.minVersion = 31;
  5425. // all webkit-based browsers
  5426. } else if (navigator.webkitGetUserMedia) {
  5427. // Chrome, Chromium, Webview, Opera, all use the chrome shim for now
  5428. if (window.webkitRTCPeerConnection) {
  5429. result.browser = 'chrome';
  5430. result.version = this.extractVersion(navigator.userAgent,
  5431. /Chrom(e|ium)\/([0-9]+)\./, 2);
  5432. result.minVersion = 38;
  5433. // Safari or unknown webkit-based
  5434. // for the time being Safari has support for MediaStreams but not webRTC
  5435. } else {
  5436. // Safari UA substrings of interest for reference:
  5437. // - webkit version: AppleWebKit/602.1.25 (also used in Op,Cr)
  5438. // - safari UI version: Version/9.0.3 (unique to Safari)
  5439. // - safari UI webkit version: Safari/601.4.4 (also used in Op,Cr)
  5440. //
  5441. // if the webkit version and safari UI webkit versions are equals,
  5442. // ... this is a stable version.
  5443. //
  5444. // only the internal webkit version is important today to know if
  5445. // media streams are supported
  5446. //
  5447. if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) {
  5448. result.browser = 'safari';
  5449. result.version = this.extractVersion(navigator.userAgent,
  5450. /AppleWebKit\/([0-9]+)\./, 1);
  5451. result.minVersion = 602;
  5452. // unknown webkit-based browser
  5453. } else {
  5454. result.browser = 'Unsupported webkit-based browser ' +
  5455. 'with GUM support but no WebRTC support.';
  5456. return result;
  5457. }
  5458. }
  5459. // Edge.
  5460. } else if (navigator.mediaDevices &&
  5461. navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) {
  5462. result.browser = 'edge';
  5463. result.version = this.extractVersion(navigator.userAgent,
  5464. /Edge\/(\d+).(\d+)$/, 2);
  5465. result.minVersion = 10547;
  5466. // Default fallthrough: not supported.
  5467. } else {
  5468. result.browser = 'Not a supported browser.';
  5469. return result;
  5470. }
  5471. // Warn if version is less than minVersion.
  5472. if (result.version < result.minVersion) {
  5473. utils.log('Browser: ' + result.browser + ' Version: ' + result.version +
  5474. ' < minimum supported version: ' + result.minVersion +
  5475. '\n some things might not work!');
  5476. }
  5477. return result;
  5478. }
  5479. };
  5480. // Export.
  5481. module.exports = {
  5482. log: utils.log,
  5483. disableLog: utils.disableLog,
  5484. browserDetails: utils.detectBrowser(),
  5485. extractVersion: utils.extractVersion
  5486. };
  5487. },{}],39:[function(require,module,exports){
  5488. /**
  5489. * Returns `this`. Execute this without a "context" (i.e. without it being
  5490. * attached to an object of the left-hand side), and `this` points to the
  5491. * "global" scope of the current JS execution.
  5492. */
  5493. module.exports = (function () { return this; })();
  5494. },{}],40:[function(require,module,exports){
  5495. var WildEmitter = require('wildemitter');
  5496. function getMaxVolume (analyser, fftBins) {
  5497. var maxVolume = -Infinity;
  5498. analyser.getFloatFrequencyData(fftBins);
  5499. for(var i=4, ii=fftBins.length; i < ii; i++) {
  5500. if (fftBins[i] > maxVolume && fftBins[i] < 0) {
  5501. maxVolume = fftBins[i];
  5502. }
  5503. };
  5504. return maxVolume;
  5505. }
  5506. var audioContextType;
  5507. if (typeof window !== 'undefined') {
  5508. audioContextType = window.AudioContext || window.webkitAudioContext;
  5509. }
  5510. // use a single audio context due to hardware limits
  5511. var audioContext = null;
  5512. module.exports = function(stream, options) {
  5513. var harker = new WildEmitter();
  5514. // make it not break in non-supported browsers
  5515. if (!audioContextType) return harker;
  5516. //Config
  5517. var options = options || {},
  5518. smoothing = (options.smoothing || 0.1),
  5519. interval = (options.interval || 50),
  5520. threshold = options.threshold,
  5521. play = options.play,
  5522. history = options.history || 10,
  5523. running = true;
  5524. //Setup Audio Context
  5525. if (!audioContext) {
  5526. audioContext = new audioContextType();
  5527. }
  5528. var sourceNode, fftBins, analyser;
  5529. analyser = audioContext.createAnalyser();
  5530. analyser.fftSize = 512;
  5531. analyser.smoothingTimeConstant = smoothing;
  5532. fftBins = new Float32Array(analyser.frequencyBinCount);
  5533. if (stream.jquery) stream = stream[0];
  5534. if (stream instanceof HTMLAudioElement || stream instanceof HTMLVideoElement) {
  5535. //Audio Tag
  5536. sourceNode = audioContext.createMediaElementSource(stream);
  5537. if (typeof play === 'undefined') play = true;
  5538. threshold = threshold || -50;
  5539. } else {
  5540. //WebRTC Stream
  5541. sourceNode = audioContext.createMediaStreamSource(stream);
  5542. threshold = threshold || -50;
  5543. }
  5544. sourceNode.connect(analyser);
  5545. if (play) analyser.connect(audioContext.destination);
  5546. harker.speaking = false;
  5547. harker.setThreshold = function(t) {
  5548. threshold = t;
  5549. };
  5550. harker.setInterval = function(i) {
  5551. interval = i;
  5552. };
  5553. harker.stop = function() {
  5554. running = false;
  5555. harker.emit('volume_change', -100, threshold);
  5556. if (harker.speaking) {
  5557. harker.speaking = false;
  5558. harker.emit('stopped_speaking');
  5559. }
  5560. analyser.disconnect();
  5561. sourceNode.disconnect();
  5562. };
  5563. harker.speakingHistory = [];
  5564. for (var i = 0; i < history; i++) {
  5565. harker.speakingHistory.push(0);
  5566. }
  5567. // Poll the analyser node to determine if speaking
  5568. // and emit events if changed
  5569. var looper = function() {
  5570. setTimeout(function() {
  5571. //check if stop has been called
  5572. if(!running) {
  5573. return;
  5574. }
  5575. var currentVolume = getMaxVolume(analyser, fftBins);
  5576. harker.emit('volume_change', currentVolume, threshold);
  5577. var history = 0;
  5578. if (currentVolume > threshold && !harker.speaking) {
  5579. // trigger quickly, short history
  5580. for (var i = harker.speakingHistory.length - 3; i < harker.speakingHistory.length; i++) {
  5581. history += harker.speakingHistory[i];
  5582. }
  5583. if (history >= 2) {
  5584. harker.speaking = true;
  5585. harker.emit('speaking');
  5586. }
  5587. } else if (currentVolume < threshold && harker.speaking) {
  5588. for (var i = 0; i < harker.speakingHistory.length; i++) {
  5589. history += harker.speakingHistory[i];
  5590. }
  5591. if (history == 0) {
  5592. harker.speaking = false;
  5593. harker.emit('stopped_speaking');
  5594. }
  5595. }
  5596. harker.speakingHistory.shift();
  5597. harker.speakingHistory.push(0 + (currentVolume > threshold));
  5598. looper();
  5599. }, interval);
  5600. };
  5601. looper();
  5602. return harker;
  5603. }
  5604. },{"wildemitter":100}],41:[function(require,module,exports){
  5605. (function (global){
  5606. /*
  5607. * Module requirements.
  5608. */
  5609. var isArray = require('isarray');
  5610. /**
  5611. * Module exports.
  5612. */
  5613. module.exports = hasBinary;
  5614. /**
  5615. * Checks for binary data.
  5616. *
  5617. * Right now only Buffer and ArrayBuffer are supported..
  5618. *
  5619. * @param {Object} anything
  5620. * @api public
  5621. */
  5622. function hasBinary(data) {
  5623. function _hasBinary(obj) {
  5624. if (!obj) return false;
  5625. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  5626. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  5627. (global.Blob && obj instanceof Blob) ||
  5628. (global.File && obj instanceof File)
  5629. ) {
  5630. return true;
  5631. }
  5632. if (isArray(obj)) {
  5633. for (var i = 0; i < obj.length; i++) {
  5634. if (_hasBinary(obj[i])) {
  5635. return true;
  5636. }
  5637. }
  5638. } else if (obj && 'object' == typeof obj) {
  5639. if (obj.toJSON) {
  5640. obj = obj.toJSON();
  5641. }
  5642. for (var key in obj) {
  5643. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  5644. return true;
  5645. }
  5646. }
  5647. }
  5648. return false;
  5649. }
  5650. return _hasBinary(data);
  5651. }
  5652. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  5653. },{"isarray":42}],42:[function(require,module,exports){
  5654. module.exports = Array.isArray || function (arr) {
  5655. return Object.prototype.toString.call(arr) == '[object Array]';
  5656. };
  5657. },{}],43:[function(require,module,exports){
  5658. /**
  5659. * Module dependencies.
  5660. */
  5661. var global = require('global');
  5662. /**
  5663. * Module exports.
  5664. *
  5665. * Logic borrowed from Modernizr:
  5666. *
  5667. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  5668. */
  5669. try {
  5670. module.exports = 'XMLHttpRequest' in global &&
  5671. 'withCredentials' in new global.XMLHttpRequest();
  5672. } catch (err) {
  5673. // if XMLHttp support is disabled in IE then it will throw
  5674. // when trying to create
  5675. module.exports = false;
  5676. }
  5677. },{"global":39}],44:[function(require,module,exports){
  5678. var indexOf = [].indexOf;
  5679. module.exports = function(arr, obj){
  5680. if (indexOf) return arr.indexOf(obj);
  5681. for (var i = 0; i < arr.length; ++i) {
  5682. if (arr[i] === obj) return i;
  5683. }
  5684. return -1;
  5685. };
  5686. },{}],45:[function(require,module,exports){
  5687. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  5688. ;(function (window) {
  5689. // Convenience aliases.
  5690. var getClass = {}.toString, isProperty, forEach, undef;
  5691. // Detect the `define` function exposed by asynchronous module loaders. The
  5692. // strict `define` check is necessary for compatibility with `r.js`.
  5693. var isLoader = typeof define === "function" && define.amd;
  5694. // Detect native implementations.
  5695. var nativeJSON = typeof JSON == "object" && JSON;
  5696. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  5697. // available.
  5698. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  5699. if (JSON3 && nativeJSON) {
  5700. // Explicitly delegate to the native `stringify` and `parse`
  5701. // implementations in CommonJS environments.
  5702. JSON3.stringify = nativeJSON.stringify;
  5703. JSON3.parse = nativeJSON.parse;
  5704. } else {
  5705. // Export for web browsers, JavaScript engines, and asynchronous module
  5706. // loaders, using the global `JSON` object if available.
  5707. JSON3 = window.JSON = nativeJSON || {};
  5708. }
  5709. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  5710. var isExtended = new Date(-3509827334573292);
  5711. try {
  5712. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  5713. // results for certain dates in Opera >= 10.53.
  5714. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  5715. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  5716. // but clips the values returned by the date methods to the range of
  5717. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  5718. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  5719. } catch (exception) {}
  5720. // Internal: Determines whether the native `JSON.stringify` and `parse`
  5721. // implementations are spec-compliant. Based on work by Ken Snyder.
  5722. function has(name) {
  5723. if (has[name] !== undef) {
  5724. // Return cached feature test result.
  5725. return has[name];
  5726. }
  5727. var isSupported;
  5728. if (name == "bug-string-char-index") {
  5729. // IE <= 7 doesn't support accessing string characters using square
  5730. // bracket notation. IE 8 only supports this for primitives.
  5731. isSupported = "a"[0] != "a";
  5732. } else if (name == "json") {
  5733. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  5734. // supported.
  5735. isSupported = has("json-stringify") && has("json-parse");
  5736. } else {
  5737. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  5738. // Test `JSON.stringify`.
  5739. if (name == "json-stringify") {
  5740. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  5741. if (stringifySupported) {
  5742. // A test function object with a custom `toJSON` method.
  5743. (value = function () {
  5744. return 1;
  5745. }).toJSON = value;
  5746. try {
  5747. stringifySupported =
  5748. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  5749. // primitives as object literals.
  5750. stringify(0) === "0" &&
  5751. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  5752. // literals.
  5753. stringify(new Number()) === "0" &&
  5754. stringify(new String()) == '""' &&
  5755. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  5756. // does not define a canonical JSON representation (this applies to
  5757. // objects with `toJSON` properties as well, *unless* they are nested
  5758. // within an object or array).
  5759. stringify(getClass) === undef &&
  5760. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  5761. // FF 3.1b3 pass this test.
  5762. stringify(undef) === undef &&
  5763. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  5764. // respectively, if the value is omitted entirely.
  5765. stringify() === undef &&
  5766. // FF 3.1b1, 2 throw an error if the given value is not a number,
  5767. // string, array, object, Boolean, or `null` literal. This applies to
  5768. // objects with custom `toJSON` methods as well, unless they are nested
  5769. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  5770. // methods entirely.
  5771. stringify(value) === "1" &&
  5772. stringify([value]) == "[1]" &&
  5773. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  5774. // `"[null]"`.
  5775. stringify([undef]) == "[null]" &&
  5776. // YUI 3.0.0b1 fails to serialize `null` literals.
  5777. stringify(null) == "null" &&
  5778. // FF 3.1b1, 2 halts serialization if an array contains a function:
  5779. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  5780. // elides non-JSON values from objects and arrays, unless they
  5781. // define custom `toJSON` methods.
  5782. stringify([undef, getClass, null]) == "[null,null,null]" &&
  5783. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  5784. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  5785. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  5786. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  5787. stringify(null, value) === "1" &&
  5788. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  5789. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  5790. // serialize extended years.
  5791. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  5792. // The milliseconds are optional in ES 5, but required in 5.1.
  5793. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  5794. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  5795. // four-digit years instead of six-digit years. Credits: @Yaffle.
  5796. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  5797. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  5798. // values less than 1000. Credits: @Yaffle.
  5799. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  5800. } catch (exception) {
  5801. stringifySupported = false;
  5802. }
  5803. }
  5804. isSupported = stringifySupported;
  5805. }
  5806. // Test `JSON.parse`.
  5807. if (name == "json-parse") {
  5808. var parse = JSON3.parse;
  5809. if (typeof parse == "function") {
  5810. try {
  5811. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  5812. // Conforming implementations should also coerce the initial argument to
  5813. // a string prior to parsing.
  5814. if (parse("0") === 0 && !parse(false)) {
  5815. // Simple parsing test.
  5816. value = parse(serialized);
  5817. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  5818. if (parseSupported) {
  5819. try {
  5820. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  5821. parseSupported = !parse('"\t"');
  5822. } catch (exception) {}
  5823. if (parseSupported) {
  5824. try {
  5825. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  5826. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  5827. // certain octal literals.
  5828. parseSupported = parse("01") !== 1;
  5829. } catch (exception) {}
  5830. }
  5831. if (parseSupported) {
  5832. try {
  5833. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  5834. // points. These environments, along with FF 3.1b1 and 2,
  5835. // also allow trailing commas in JSON objects and arrays.
  5836. parseSupported = parse("1.") !== 1;
  5837. } catch (exception) {}
  5838. }
  5839. }
  5840. }
  5841. } catch (exception) {
  5842. parseSupported = false;
  5843. }
  5844. }
  5845. isSupported = parseSupported;
  5846. }
  5847. }
  5848. return has[name] = !!isSupported;
  5849. }
  5850. if (!has("json")) {
  5851. // Common `[[Class]]` name aliases.
  5852. var functionClass = "[object Function]";
  5853. var dateClass = "[object Date]";
  5854. var numberClass = "[object Number]";
  5855. var stringClass = "[object String]";
  5856. var arrayClass = "[object Array]";
  5857. var booleanClass = "[object Boolean]";
  5858. // Detect incomplete support for accessing string characters by index.
  5859. var charIndexBuggy = has("bug-string-char-index");
  5860. // Define additional utility methods if the `Date` methods are buggy.
  5861. if (!isExtended) {
  5862. var floor = Math.floor;
  5863. // A mapping between the months of the year and the number of days between
  5864. // January 1st and the first of the respective month.
  5865. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  5866. // Internal: Calculates the number of days between the Unix epoch and the
  5867. // first day of the given month.
  5868. var getDay = function (year, month) {
  5869. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  5870. };
  5871. }
  5872. // Internal: Determines if a property is a direct property of the given
  5873. // object. Delegates to the native `Object#hasOwnProperty` method.
  5874. if (!(isProperty = {}.hasOwnProperty)) {
  5875. isProperty = function (property) {
  5876. var members = {}, constructor;
  5877. if ((members.__proto__ = null, members.__proto__ = {
  5878. // The *proto* property cannot be set multiple times in recent
  5879. // versions of Firefox and SeaMonkey.
  5880. "toString": 1
  5881. }, members).toString != getClass) {
  5882. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  5883. // supports the mutable *proto* property.
  5884. isProperty = function (property) {
  5885. // Capture and break the object's prototype chain (see section 8.6.2
  5886. // of the ES 5.1 spec). The parenthesized expression prevents an
  5887. // unsafe transformation by the Closure Compiler.
  5888. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  5889. // Restore the original prototype chain.
  5890. this.__proto__ = original;
  5891. return result;
  5892. };
  5893. } else {
  5894. // Capture a reference to the top-level `Object` constructor.
  5895. constructor = members.constructor;
  5896. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  5897. // other environments.
  5898. isProperty = function (property) {
  5899. var parent = (this.constructor || constructor).prototype;
  5900. return property in this && !(property in parent && this[property] === parent[property]);
  5901. };
  5902. }
  5903. members = null;
  5904. return isProperty.call(this, property);
  5905. };
  5906. }
  5907. // Internal: A set of primitive types used by `isHostType`.
  5908. var PrimitiveTypes = {
  5909. 'boolean': 1,
  5910. 'number': 1,
  5911. 'string': 1,
  5912. 'undefined': 1
  5913. };
  5914. // Internal: Determines if the given object `property` value is a
  5915. // non-primitive.
  5916. var isHostType = function (object, property) {
  5917. var type = typeof object[property];
  5918. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  5919. };
  5920. // Internal: Normalizes the `for...in` iteration algorithm across
  5921. // environments. Each enumerated key is yielded to a `callback` function.
  5922. forEach = function (object, callback) {
  5923. var size = 0, Properties, members, property;
  5924. // Tests for bugs in the current environment's `for...in` algorithm. The
  5925. // `valueOf` property inherits the non-enumerable flag from
  5926. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  5927. (Properties = function () {
  5928. this.valueOf = 0;
  5929. }).prototype.valueOf = 0;
  5930. // Iterate over a new instance of the `Properties` class.
  5931. members = new Properties();
  5932. for (property in members) {
  5933. // Ignore all properties inherited from `Object.prototype`.
  5934. if (isProperty.call(members, property)) {
  5935. size++;
  5936. }
  5937. }
  5938. Properties = members = null;
  5939. // Normalize the iteration algorithm.
  5940. if (!size) {
  5941. // A list of non-enumerable properties inherited from `Object.prototype`.
  5942. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  5943. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  5944. // properties.
  5945. forEach = function (object, callback) {
  5946. var isFunction = getClass.call(object) == functionClass, property, length;
  5947. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  5948. for (property in object) {
  5949. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  5950. // certain conditions; IE does not.
  5951. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  5952. callback(property);
  5953. }
  5954. }
  5955. // Manually invoke the callback for each non-enumerable property.
  5956. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  5957. };
  5958. } else if (size == 2) {
  5959. // Safari <= 2.0.4 enumerates shadowed properties twice.
  5960. forEach = function (object, callback) {
  5961. // Create a set of iterated properties.
  5962. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  5963. for (property in object) {
  5964. // Store each property name to prevent double enumeration. The
  5965. // `prototype` property of functions is not enumerated due to cross-
  5966. // environment inconsistencies.
  5967. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  5968. callback(property);
  5969. }
  5970. }
  5971. };
  5972. } else {
  5973. // No bugs detected; use the standard `for...in` algorithm.
  5974. forEach = function (object, callback) {
  5975. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  5976. for (property in object) {
  5977. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  5978. callback(property);
  5979. }
  5980. }
  5981. // Manually invoke the callback for the `constructor` property due to
  5982. // cross-environment inconsistencies.
  5983. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  5984. callback(property);
  5985. }
  5986. };
  5987. }
  5988. return forEach(object, callback);
  5989. };
  5990. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  5991. // `filter` argument may specify either a function that alters how object and
  5992. // array members are serialized, or an array of strings and numbers that
  5993. // indicates which properties should be serialized. The optional `width`
  5994. // argument may be either a string or number that specifies the indentation
  5995. // level of the output.
  5996. if (!has("json-stringify")) {
  5997. // Internal: A map of control characters and their escaped equivalents.
  5998. var Escapes = {
  5999. 92: "\\\\",
  6000. 34: '\\"',
  6001. 8: "\\b",
  6002. 12: "\\f",
  6003. 10: "\\n",
  6004. 13: "\\r",
  6005. 9: "\\t"
  6006. };
  6007. // Internal: Converts `value` into a zero-padded string such that its
  6008. // length is at least equal to `width`. The `width` must be <= 6.
  6009. var leadingZeroes = "000000";
  6010. var toPaddedString = function (width, value) {
  6011. // The `|| 0` expression is necessary to work around a bug in
  6012. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  6013. return (leadingZeroes + (value || 0)).slice(-width);
  6014. };
  6015. // Internal: Double-quotes a string `value`, replacing all ASCII control
  6016. // characters (characters with code unit values between 0 and 31) with
  6017. // their escaped equivalents. This is an implementation of the
  6018. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  6019. var unicodePrefix = "\\u00";
  6020. var quote = function (value) {
  6021. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  6022. if (isLarge) {
  6023. symbols = value.split("");
  6024. }
  6025. for (; index < length; index++) {
  6026. var charCode = value.charCodeAt(index);
  6027. // If the character is a control character, append its Unicode or
  6028. // shorthand escape sequence; otherwise, append the character as-is.
  6029. switch (charCode) {
  6030. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  6031. result += Escapes[charCode];
  6032. break;
  6033. default:
  6034. if (charCode < 32) {
  6035. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  6036. break;
  6037. }
  6038. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  6039. }
  6040. }
  6041. return result + '"';
  6042. };
  6043. // Internal: Recursively serializes an object. Implements the
  6044. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  6045. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  6046. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  6047. try {
  6048. // Necessary for host object support.
  6049. value = object[property];
  6050. } catch (exception) {}
  6051. if (typeof value == "object" && value) {
  6052. className = getClass.call(value);
  6053. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  6054. if (value > -1 / 0 && value < 1 / 0) {
  6055. // Dates are serialized according to the `Date#toJSON` method
  6056. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  6057. // for the ISO 8601 date time string format.
  6058. if (getDay) {
  6059. // Manually compute the year, month, date, hours, minutes,
  6060. // seconds, and milliseconds if the `getUTC*` methods are
  6061. // buggy. Adapted from @Yaffle's `date-shim` project.
  6062. date = floor(value / 864e5);
  6063. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  6064. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  6065. date = 1 + date - getDay(year, month);
  6066. // The `time` value specifies the time within the day (see ES
  6067. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  6068. // to compute `A modulo B`, as the `%` operator does not
  6069. // correspond to the `modulo` operation for negative numbers.
  6070. time = (value % 864e5 + 864e5) % 864e5;
  6071. // The hours, minutes, seconds, and milliseconds are obtained by
  6072. // decomposing the time within the day. See section 15.9.1.10.
  6073. hours = floor(time / 36e5) % 24;
  6074. minutes = floor(time / 6e4) % 60;
  6075. seconds = floor(time / 1e3) % 60;
  6076. milliseconds = time % 1e3;
  6077. } else {
  6078. year = value.getUTCFullYear();
  6079. month = value.getUTCMonth();
  6080. date = value.getUTCDate();
  6081. hours = value.getUTCHours();
  6082. minutes = value.getUTCMinutes();
  6083. seconds = value.getUTCSeconds();
  6084. milliseconds = value.getUTCMilliseconds();
  6085. }
  6086. // Serialize extended years correctly.
  6087. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  6088. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  6089. // Months, dates, hours, minutes, and seconds should have two
  6090. // digits; milliseconds should have three.
  6091. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  6092. // Milliseconds are optional in ES 5.0, but required in 5.1.
  6093. "." + toPaddedString(3, milliseconds) + "Z";
  6094. } else {
  6095. value = null;
  6096. }
  6097. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  6098. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  6099. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  6100. // ignores all `toJSON` methods on these objects unless they are
  6101. // defined directly on an instance.
  6102. value = value.toJSON(property);
  6103. }
  6104. }
  6105. if (callback) {
  6106. // If a replacement function was provided, call it to obtain the value
  6107. // for serialization.
  6108. value = callback.call(object, property, value);
  6109. }
  6110. if (value === null) {
  6111. return "null";
  6112. }
  6113. className = getClass.call(value);
  6114. if (className == booleanClass) {
  6115. // Booleans are represented literally.
  6116. return "" + value;
  6117. } else if (className == numberClass) {
  6118. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  6119. // `"null"`.
  6120. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  6121. } else if (className == stringClass) {
  6122. // Strings are double-quoted and escaped.
  6123. return quote("" + value);
  6124. }
  6125. // Recursively serialize objects and arrays.
  6126. if (typeof value == "object") {
  6127. // Check for cyclic structures. This is a linear search; performance
  6128. // is inversely proportional to the number of unique nested objects.
  6129. for (length = stack.length; length--;) {
  6130. if (stack[length] === value) {
  6131. // Cyclic structures cannot be serialized by `JSON.stringify`.
  6132. throw TypeError();
  6133. }
  6134. }
  6135. // Add the object to the stack of traversed objects.
  6136. stack.push(value);
  6137. results = [];
  6138. // Save the current indentation level and indent one additional level.
  6139. prefix = indentation;
  6140. indentation += whitespace;
  6141. if (className == arrayClass) {
  6142. // Recursively serialize array elements.
  6143. for (index = 0, length = value.length; index < length; index++) {
  6144. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  6145. results.push(element === undef ? "null" : element);
  6146. }
  6147. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  6148. } else {
  6149. // Recursively serialize object members. Members are selected from
  6150. // either a user-specified list of property names, or the object
  6151. // itself.
  6152. forEach(properties || value, function (property) {
  6153. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  6154. if (element !== undef) {
  6155. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  6156. // is not the empty string, let `member` {quote(property) + ":"}
  6157. // be the concatenation of `member` and the `space` character."
  6158. // The "`space` character" refers to the literal space
  6159. // character, not the `space` {width} argument provided to
  6160. // `JSON.stringify`.
  6161. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  6162. }
  6163. });
  6164. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  6165. }
  6166. // Remove the object from the traversed object stack.
  6167. stack.pop();
  6168. return result;
  6169. }
  6170. };
  6171. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  6172. JSON3.stringify = function (source, filter, width) {
  6173. var whitespace, callback, properties, className;
  6174. if (typeof filter == "function" || typeof filter == "object" && filter) {
  6175. if ((className = getClass.call(filter)) == functionClass) {
  6176. callback = filter;
  6177. } else if (className == arrayClass) {
  6178. // Convert the property names array into a makeshift set.
  6179. properties = {};
  6180. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  6181. }
  6182. }
  6183. if (width) {
  6184. if ((className = getClass.call(width)) == numberClass) {
  6185. // Convert the `width` to an integer and create a string containing
  6186. // `width` number of space characters.
  6187. if ((width -= width % 1) > 0) {
  6188. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  6189. }
  6190. } else if (className == stringClass) {
  6191. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  6192. }
  6193. }
  6194. // Opera <= 7.54u2 discards the values associated with empty string keys
  6195. // (`""`) only if they are used directly within an object member list
  6196. // (e.g., `!("" in { "": 1})`).
  6197. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  6198. };
  6199. }
  6200. // Public: Parses a JSON source string.
  6201. if (!has("json-parse")) {
  6202. var fromCharCode = String.fromCharCode;
  6203. // Internal: A map of escaped control characters and their unescaped
  6204. // equivalents.
  6205. var Unescapes = {
  6206. 92: "\\",
  6207. 34: '"',
  6208. 47: "/",
  6209. 98: "\b",
  6210. 116: "\t",
  6211. 110: "\n",
  6212. 102: "\f",
  6213. 114: "\r"
  6214. };
  6215. // Internal: Stores the parser state.
  6216. var Index, Source;
  6217. // Internal: Resets the parser state and throws a `SyntaxError`.
  6218. var abort = function() {
  6219. Index = Source = null;
  6220. throw SyntaxError();
  6221. };
  6222. // Internal: Returns the next token, or `"$"` if the parser has reached
  6223. // the end of the source string. A token may be a string, number, `null`
  6224. // literal, or Boolean literal.
  6225. var lex = function () {
  6226. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  6227. while (Index < length) {
  6228. charCode = source.charCodeAt(Index);
  6229. switch (charCode) {
  6230. case 9: case 10: case 13: case 32:
  6231. // Skip whitespace tokens, including tabs, carriage returns, line
  6232. // feeds, and space characters.
  6233. Index++;
  6234. break;
  6235. case 123: case 125: case 91: case 93: case 58: case 44:
  6236. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  6237. // the current position.
  6238. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  6239. Index++;
  6240. return value;
  6241. case 34:
  6242. // `"` delimits a JSON string; advance to the next character and
  6243. // begin parsing the string. String tokens are prefixed with the
  6244. // sentinel `@` character to distinguish them from punctuators and
  6245. // end-of-string tokens.
  6246. for (value = "@", Index++; Index < length;) {
  6247. charCode = source.charCodeAt(Index);
  6248. if (charCode < 32) {
  6249. // Unescaped ASCII control characters (those with a code unit
  6250. // less than the space character) are not permitted.
  6251. abort();
  6252. } else if (charCode == 92) {
  6253. // A reverse solidus (`\`) marks the beginning of an escaped
  6254. // control character (including `"`, `\`, and `/`) or Unicode
  6255. // escape sequence.
  6256. charCode = source.charCodeAt(++Index);
  6257. switch (charCode) {
  6258. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  6259. // Revive escaped control characters.
  6260. value += Unescapes[charCode];
  6261. Index++;
  6262. break;
  6263. case 117:
  6264. // `\u` marks the beginning of a Unicode escape sequence.
  6265. // Advance to the first character and validate the
  6266. // four-digit code point.
  6267. begin = ++Index;
  6268. for (position = Index + 4; Index < position; Index++) {
  6269. charCode = source.charCodeAt(Index);
  6270. // A valid sequence comprises four hexdigits (case-
  6271. // insensitive) that form a single hexadecimal value.
  6272. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  6273. // Invalid Unicode escape sequence.
  6274. abort();
  6275. }
  6276. }
  6277. // Revive the escaped character.
  6278. value += fromCharCode("0x" + source.slice(begin, Index));
  6279. break;
  6280. default:
  6281. // Invalid escape sequence.
  6282. abort();
  6283. }
  6284. } else {
  6285. if (charCode == 34) {
  6286. // An unescaped double-quote character marks the end of the
  6287. // string.
  6288. break;
  6289. }
  6290. charCode = source.charCodeAt(Index);
  6291. begin = Index;
  6292. // Optimize for the common case where a string is valid.
  6293. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  6294. charCode = source.charCodeAt(++Index);
  6295. }
  6296. // Append the string as-is.
  6297. value += source.slice(begin, Index);
  6298. }
  6299. }
  6300. if (source.charCodeAt(Index) == 34) {
  6301. // Advance to the next character and return the revived string.
  6302. Index++;
  6303. return value;
  6304. }
  6305. // Unterminated string.
  6306. abort();
  6307. default:
  6308. // Parse numbers and literals.
  6309. begin = Index;
  6310. // Advance past the negative sign, if one is specified.
  6311. if (charCode == 45) {
  6312. isSigned = true;
  6313. charCode = source.charCodeAt(++Index);
  6314. }
  6315. // Parse an integer or floating-point value.
  6316. if (charCode >= 48 && charCode <= 57) {
  6317. // Leading zeroes are interpreted as octal literals.
  6318. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  6319. // Illegal octal literal.
  6320. abort();
  6321. }
  6322. isSigned = false;
  6323. // Parse the integer component.
  6324. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  6325. // Floats cannot contain a leading decimal point; however, this
  6326. // case is already accounted for by the parser.
  6327. if (source.charCodeAt(Index) == 46) {
  6328. position = ++Index;
  6329. // Parse the decimal component.
  6330. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  6331. if (position == Index) {
  6332. // Illegal trailing decimal.
  6333. abort();
  6334. }
  6335. Index = position;
  6336. }
  6337. // Parse exponents. The `e` denoting the exponent is
  6338. // case-insensitive.
  6339. charCode = source.charCodeAt(Index);
  6340. if (charCode == 101 || charCode == 69) {
  6341. charCode = source.charCodeAt(++Index);
  6342. // Skip past the sign following the exponent, if one is
  6343. // specified.
  6344. if (charCode == 43 || charCode == 45) {
  6345. Index++;
  6346. }
  6347. // Parse the exponential component.
  6348. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  6349. if (position == Index) {
  6350. // Illegal empty exponent.
  6351. abort();
  6352. }
  6353. Index = position;
  6354. }
  6355. // Coerce the parsed value to a JavaScript number.
  6356. return +source.slice(begin, Index);
  6357. }
  6358. // A negative sign may only precede numbers.
  6359. if (isSigned) {
  6360. abort();
  6361. }
  6362. // `true`, `false`, and `null` literals.
  6363. if (source.slice(Index, Index + 4) == "true") {
  6364. Index += 4;
  6365. return true;
  6366. } else if (source.slice(Index, Index + 5) == "false") {
  6367. Index += 5;
  6368. return false;
  6369. } else if (source.slice(Index, Index + 4) == "null") {
  6370. Index += 4;
  6371. return null;
  6372. }
  6373. // Unrecognized token.
  6374. abort();
  6375. }
  6376. }
  6377. // Return the sentinel `$` character if the parser has reached the end
  6378. // of the source string.
  6379. return "$";
  6380. };
  6381. // Internal: Parses a JSON `value` token.
  6382. var get = function (value) {
  6383. var results, hasMembers;
  6384. if (value == "$") {
  6385. // Unexpected end of input.
  6386. abort();
  6387. }
  6388. if (typeof value == "string") {
  6389. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  6390. // Remove the sentinel `@` character.
  6391. return value.slice(1);
  6392. }
  6393. // Parse object and array literals.
  6394. if (value == "[") {
  6395. // Parses a JSON array, returning a new JavaScript array.
  6396. results = [];
  6397. for (;; hasMembers || (hasMembers = true)) {
  6398. value = lex();
  6399. // A closing square bracket marks the end of the array literal.
  6400. if (value == "]") {
  6401. break;
  6402. }
  6403. // If the array literal contains elements, the current token
  6404. // should be a comma separating the previous element from the
  6405. // next.
  6406. if (hasMembers) {
  6407. if (value == ",") {
  6408. value = lex();
  6409. if (value == "]") {
  6410. // Unexpected trailing `,` in array literal.
  6411. abort();
  6412. }
  6413. } else {
  6414. // A `,` must separate each array element.
  6415. abort();
  6416. }
  6417. }
  6418. // Elisions and leading commas are not permitted.
  6419. if (value == ",") {
  6420. abort();
  6421. }
  6422. results.push(get(value));
  6423. }
  6424. return results;
  6425. } else if (value == "{") {
  6426. // Parses a JSON object, returning a new JavaScript object.
  6427. results = {};
  6428. for (;; hasMembers || (hasMembers = true)) {
  6429. value = lex();
  6430. // A closing curly brace marks the end of the object literal.
  6431. if (value == "}") {
  6432. break;
  6433. }
  6434. // If the object literal contains members, the current token
  6435. // should be a comma separator.
  6436. if (hasMembers) {
  6437. if (value == ",") {
  6438. value = lex();
  6439. if (value == "}") {
  6440. // Unexpected trailing `,` in object literal.
  6441. abort();
  6442. }
  6443. } else {
  6444. // A `,` must separate each object member.
  6445. abort();
  6446. }
  6447. }
  6448. // Leading commas are not permitted, object property names must be
  6449. // double-quoted strings, and a `:` must separate each property
  6450. // name and value.
  6451. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  6452. abort();
  6453. }
  6454. results[value.slice(1)] = get(lex());
  6455. }
  6456. return results;
  6457. }
  6458. // Unexpected token encountered.
  6459. abort();
  6460. }
  6461. return value;
  6462. };
  6463. // Internal: Updates a traversed object member.
  6464. var update = function(source, property, callback) {
  6465. var element = walk(source, property, callback);
  6466. if (element === undef) {
  6467. delete source[property];
  6468. } else {
  6469. source[property] = element;
  6470. }
  6471. };
  6472. // Internal: Recursively traverses a parsed JSON object, invoking the
  6473. // `callback` function for each value. This is an implementation of the
  6474. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  6475. var walk = function (source, property, callback) {
  6476. var value = source[property], length;
  6477. if (typeof value == "object" && value) {
  6478. // `forEach` can't be used to traverse an array in Opera <= 8.54
  6479. // because its `Object#hasOwnProperty` implementation returns `false`
  6480. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  6481. if (getClass.call(value) == arrayClass) {
  6482. for (length = value.length; length--;) {
  6483. update(value, length, callback);
  6484. }
  6485. } else {
  6486. forEach(value, function (property) {
  6487. update(value, property, callback);
  6488. });
  6489. }
  6490. }
  6491. return callback.call(source, property, value);
  6492. };
  6493. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  6494. JSON3.parse = function (source, callback) {
  6495. var result, value;
  6496. Index = 0;
  6497. Source = "" + source;
  6498. result = get(lex());
  6499. // If a JSON string contains multiple tokens, it is invalid.
  6500. if (lex() != "$") {
  6501. abort();
  6502. }
  6503. // Reset the parser state.
  6504. Index = Source = null;
  6505. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  6506. };
  6507. }
  6508. }
  6509. // Export for asynchronous module loaders.
  6510. if (isLoader) {
  6511. define(function () {
  6512. return JSON3;
  6513. });
  6514. }
  6515. }(this));
  6516. },{}],46:[function(require,module,exports){
  6517. var util = require('util');
  6518. var hark = require('hark');
  6519. var webrtcSupport = require('webrtcsupport');
  6520. var getUserMedia = require('getusermedia');
  6521. var getScreenMedia = require('getscreenmedia');
  6522. var WildEmitter = require('wildemitter');
  6523. var GainController = require('mediastream-gain');
  6524. var mockconsole = require('mockconsole');
  6525. function isAllTracksEnded(stream) {
  6526. var isAllTracksEnded = true;
  6527. stream.getTracks().forEach(function (t) {
  6528. isAllTracksEnded = t.readyState === 'ended' && isAllTracksEnded;
  6529. });
  6530. return isAllTracksEnded;
  6531. }
  6532. function LocalMedia(opts) {
  6533. WildEmitter.call(this);
  6534. var config = this.config = {
  6535. autoAdjustMic: false,
  6536. detectSpeakingEvents: false,
  6537. audioFallback: false,
  6538. media: {
  6539. audio: true,
  6540. video: true
  6541. },
  6542. logger: mockconsole
  6543. };
  6544. var item;
  6545. for (item in opts) {
  6546. if (opts.hasOwnProperty(item)) {
  6547. this.config[item] = opts[item];
  6548. }
  6549. }
  6550. this.logger = config.logger;
  6551. this._log = this.logger.log.bind(this.logger, 'LocalMedia:');
  6552. this._logerror = this.logger.error.bind(this.logger, 'LocalMedia:');
  6553. this.screenSharingSupport = webrtcSupport.supportScreenSharing;
  6554. this.localStreams = [];
  6555. this.localScreens = [];
  6556. if (!webrtcSupport.supportGetUserMedia) {
  6557. this._logerror('Your browser does not support local media capture.');
  6558. }
  6559. }
  6560. util.inherits(LocalMedia, WildEmitter);
  6561. LocalMedia.prototype.start = function (mediaConstraints, cb) {
  6562. var self = this;
  6563. var constraints = mediaConstraints || this.config.media;
  6564. getUserMedia(constraints, function (err, stream) {
  6565. if (!err) {
  6566. if (constraints.audio && self.config.detectSpeakingEvents) {
  6567. self.setupAudioMonitor(stream, self.config.harkOptions);
  6568. }
  6569. self.localStreams.push(stream);
  6570. if (self.config.autoAdjustMic) {
  6571. self.gainController = new GainController(stream);
  6572. // start out somewhat muted if we can track audio
  6573. self.setMicIfEnabled(0.5);
  6574. }
  6575. stream.getTracks().forEach(function (track) {
  6576. track.addEventListener('ended', function () {
  6577. if (isAllTracksEnded(stream)) {
  6578. self.emit('localStreamStopped', stream);
  6579. }
  6580. });
  6581. });
  6582. self.emit('localStream', stream);
  6583. } else {
  6584. // Fallback for users without a camera
  6585. if (self.config.audioFallback && err.name === 'DevicesNotFoundError' && constraints.video !== false) {
  6586. constraints.video = false;
  6587. self.start(constraints, cb);
  6588. return;
  6589. }
  6590. }
  6591. if (cb) {
  6592. return cb(err, stream);
  6593. }
  6594. });
  6595. };
  6596. LocalMedia.prototype.stop = function (stream) {
  6597. // FIXME: duplicates cleanup code until fixed in FF
  6598. if (stream) {
  6599. stream.getTracks().forEach(function (track) { track.stop(); });
  6600. var idx = this.localStreams.indexOf(stream);
  6601. if (idx > -1) {
  6602. this.localStreams.splice(idx, 1);
  6603. if (webrtcSupport.prefix === 'moz') {
  6604. this.emit('localStreamStopped', stream);
  6605. }
  6606. } else {
  6607. idx = this.localScreens.indexOf(stream);
  6608. if (idx > -1) {
  6609. this.localScreens.splice(idx, 1);
  6610. if (webrtcSupport.prefix === 'moz') {
  6611. this.emit('localScreenStopped', stream);
  6612. }
  6613. }
  6614. }
  6615. } else {
  6616. this.stopStreams();
  6617. this.stopScreenShare();
  6618. }
  6619. };
  6620. LocalMedia.prototype.stopStreams = function () {
  6621. var self = this;
  6622. if (this.audioMonitor) {
  6623. this.audioMonitor.stop();
  6624. delete this.audioMonitor;
  6625. }
  6626. var oldLocalStream = this.localStreams;
  6627. this.localStreams = [];
  6628. oldLocalStream.forEach(function (stream) {
  6629. stream.getTracks().forEach(function (track) { track.stop(); });
  6630. if (webrtcSupport.prefix === 'moz') {
  6631. self.emit('localStreamStopped', stream);
  6632. }
  6633. });
  6634. };
  6635. LocalMedia.prototype.startScreenShare = function (cb) {
  6636. var self = this;
  6637. getScreenMedia(function (err, stream) {
  6638. if (!err) {
  6639. self.localScreens.push(stream);
  6640. stream.getTracks().forEach(function (track) {
  6641. track.addEventListener('ended', function () {
  6642. if (isAllTracksEnded(stream)) {
  6643. self.emit('localScreenStopped', stream);
  6644. }
  6645. });
  6646. });
  6647. self.emit('localScreen', stream);
  6648. }
  6649. // enable the callback
  6650. if (cb) {
  6651. return cb(err, stream);
  6652. }
  6653. });
  6654. };
  6655. LocalMedia.prototype.stopScreenShare = function (stream) {
  6656. var self = this;
  6657. if (stream) {
  6658. stream.getTracks().forEach(function (track) { track.stop(); });
  6659. var idx = this.localScreens.indexOf(stream);
  6660. if (idx > -1) {
  6661. this.localScreens.splice(idx, 1);
  6662. if (webrtcSupport.prefix === 'moz') {
  6663. this.emit('localScreenStopped', stream);
  6664. }
  6665. }
  6666. } else {
  6667. var oldLocalScreens = this.localScreens;
  6668. this.localScreens = [];
  6669. oldLocalScreens.forEach(function (stream) {
  6670. stream.getTracks().forEach(function (track) { track.stop(); });
  6671. if (webrtcSupport.prefix === 'moz') {
  6672. self.emit('localScreenStopped', stream);
  6673. }
  6674. });
  6675. }
  6676. };
  6677. // Audio controls
  6678. LocalMedia.prototype.mute = function () {
  6679. this._audioEnabled(false);
  6680. this.hardMuted = true;
  6681. this.emit('audioOff');
  6682. };
  6683. LocalMedia.prototype.unmute = function () {
  6684. this._audioEnabled(true);
  6685. this.hardMuted = false;
  6686. this.emit('audioOn');
  6687. };
  6688. LocalMedia.prototype.setupAudioMonitor = function (stream, harkOptions) {
  6689. this._log('Setup audio');
  6690. var audio = this.audioMonitor = hark(stream, harkOptions);
  6691. var self = this;
  6692. var timeout;
  6693. audio.on('speaking', function () {
  6694. self.emit('speaking');
  6695. if (self.hardMuted) {
  6696. return;
  6697. }
  6698. self.setMicIfEnabled(1);
  6699. });
  6700. audio.on('stopped_speaking', function () {
  6701. if (timeout) {
  6702. clearTimeout(timeout);
  6703. }
  6704. timeout = setTimeout(function () {
  6705. self.emit('stoppedSpeaking');
  6706. if (self.hardMuted) {
  6707. return;
  6708. }
  6709. self.setMicIfEnabled(0.5);
  6710. }, 1000);
  6711. });
  6712. audio.on('volume_change', function (volume, treshold) {
  6713. self.emit('volumeChange', volume, treshold);
  6714. });
  6715. };
  6716. // We do this as a seperate method in order to
  6717. // still leave the "setMicVolume" as a working
  6718. // method.
  6719. LocalMedia.prototype.setMicIfEnabled = function (volume) {
  6720. if (!this.config.autoAdjustMic) {
  6721. return;
  6722. }
  6723. this.gainController.setGain(volume);
  6724. };
  6725. // Video controls
  6726. LocalMedia.prototype.pauseVideo = function () {
  6727. this._videoEnabled(false);
  6728. this.emit('videoOff');
  6729. };
  6730. LocalMedia.prototype.resumeVideo = function () {
  6731. this._videoEnabled(true);
  6732. this.emit('videoOn');
  6733. };
  6734. // Combined controls
  6735. LocalMedia.prototype.pause = function () {
  6736. this.mute();
  6737. this.pauseVideo();
  6738. };
  6739. LocalMedia.prototype.resume = function () {
  6740. this.unmute();
  6741. this.resumeVideo();
  6742. };
  6743. // Internal methods for enabling/disabling audio/video
  6744. LocalMedia.prototype._audioEnabled = function (bool) {
  6745. // work around for chrome 27 bug where disabling tracks
  6746. // doesn't seem to work (works in canary, remove when working)
  6747. this.setMicIfEnabled(bool ? 1 : 0);
  6748. this.localStreams.forEach(function (stream) {
  6749. stream.getAudioTracks().forEach(function (track) {
  6750. track.enabled = !!bool;
  6751. });
  6752. });
  6753. };
  6754. LocalMedia.prototype._videoEnabled = function (bool) {
  6755. this.localStreams.forEach(function (stream) {
  6756. stream.getVideoTracks().forEach(function (track) {
  6757. track.enabled = !!bool;
  6758. });
  6759. });
  6760. };
  6761. // check if all audio streams are enabled
  6762. LocalMedia.prototype.isAudioEnabled = function () {
  6763. var enabled = true;
  6764. this.localStreams.forEach(function (stream) {
  6765. stream.getAudioTracks().forEach(function (track) {
  6766. enabled = enabled && track.enabled;
  6767. });
  6768. });
  6769. return enabled;
  6770. };
  6771. // check if all video streams are enabled
  6772. LocalMedia.prototype.isVideoEnabled = function () {
  6773. var enabled = true;
  6774. this.localStreams.forEach(function (stream) {
  6775. stream.getVideoTracks().forEach(function (track) {
  6776. enabled = enabled && track.enabled;
  6777. });
  6778. });
  6779. return enabled;
  6780. };
  6781. // Backwards Compat
  6782. LocalMedia.prototype.startLocalMedia = LocalMedia.prototype.start;
  6783. LocalMedia.prototype.stopLocalMedia = LocalMedia.prototype.stop;
  6784. // fallback for old .localStream behaviour
  6785. Object.defineProperty(LocalMedia.prototype, 'localStream', {
  6786. get: function () {
  6787. return this.localStreams.length > 0 ? this.localStreams[0] : null;
  6788. }
  6789. });
  6790. // fallback for old .localScreen behaviour
  6791. Object.defineProperty(LocalMedia.prototype, 'localScreen', {
  6792. get: function () {
  6793. return this.localScreens.length > 0 ? this.localScreens[0] : null;
  6794. }
  6795. });
  6796. module.exports = LocalMedia;
  6797. },{"getscreenmedia":27,"getusermedia":29,"hark":40,"mediastream-gain":48,"mockconsole":50,"util":89,"webrtcsupport":99,"wildemitter":100}],47:[function(require,module,exports){
  6798. (function (global){
  6799. /**
  6800. * lodash (Custom Build) <https://lodash.com/>
  6801. * Build: `lodash modularize exports="npm" -o ./`
  6802. * Copyright jQuery Foundation and other contributors <https://jquery.org/>
  6803. * Released under MIT license <https://lodash.com/license>
  6804. * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
  6805. * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
  6806. */
  6807. /** Used as the size to enable large array optimizations. */
  6808. var LARGE_ARRAY_SIZE = 200;
  6809. /** Used to stand-in for `undefined` hash values. */
  6810. var HASH_UNDEFINED = '__lodash_hash_undefined__';
  6811. /** Used as references for various `Number` constants. */
  6812. var MAX_SAFE_INTEGER = 9007199254740991;
  6813. /** `Object#toString` result references. */
  6814. var argsTag = '[object Arguments]',
  6815. arrayTag = '[object Array]',
  6816. boolTag = '[object Boolean]',
  6817. dateTag = '[object Date]',
  6818. errorTag = '[object Error]',
  6819. funcTag = '[object Function]',
  6820. genTag = '[object GeneratorFunction]',
  6821. mapTag = '[object Map]',
  6822. numberTag = '[object Number]',
  6823. objectTag = '[object Object]',
  6824. promiseTag = '[object Promise]',
  6825. regexpTag = '[object RegExp]',
  6826. setTag = '[object Set]',
  6827. stringTag = '[object String]',
  6828. symbolTag = '[object Symbol]',
  6829. weakMapTag = '[object WeakMap]';
  6830. var arrayBufferTag = '[object ArrayBuffer]',
  6831. dataViewTag = '[object DataView]',
  6832. float32Tag = '[object Float32Array]',
  6833. float64Tag = '[object Float64Array]',
  6834. int8Tag = '[object Int8Array]',
  6835. int16Tag = '[object Int16Array]',
  6836. int32Tag = '[object Int32Array]',
  6837. uint8Tag = '[object Uint8Array]',
  6838. uint8ClampedTag = '[object Uint8ClampedArray]',
  6839. uint16Tag = '[object Uint16Array]',
  6840. uint32Tag = '[object Uint32Array]';
  6841. /**
  6842. * Used to match `RegExp`
  6843. * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
  6844. */
  6845. var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
  6846. /** Used to match `RegExp` flags from their coerced string values. */
  6847. var reFlags = /\w*$/;
  6848. /** Used to detect host constructors (Safari). */
  6849. var reIsHostCtor = /^\[object .+?Constructor\]$/;
  6850. /** Used to detect unsigned integer values. */
  6851. var reIsUint = /^(?:0|[1-9]\d*)$/;
  6852. /** Used to identify `toStringTag` values supported by `_.clone`. */
  6853. var cloneableTags = {};
  6854. cloneableTags[argsTag] = cloneableTags[arrayTag] =
  6855. cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
  6856. cloneableTags[boolTag] = cloneableTags[dateTag] =
  6857. cloneableTags[float32Tag] = cloneableTags[float64Tag] =
  6858. cloneableTags[int8Tag] = cloneableTags[int16Tag] =
  6859. cloneableTags[int32Tag] = cloneableTags[mapTag] =
  6860. cloneableTags[numberTag] = cloneableTags[objectTag] =
  6861. cloneableTags[regexpTag] = cloneableTags[setTag] =
  6862. cloneableTags[stringTag] = cloneableTags[symbolTag] =
  6863. cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
  6864. cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
  6865. cloneableTags[errorTag] = cloneableTags[funcTag] =
  6866. cloneableTags[weakMapTag] = false;
  6867. /** Detect free variable `global` from Node.js. */
  6868. var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
  6869. /** Detect free variable `self`. */
  6870. var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
  6871. /** Used as a reference to the global object. */
  6872. var root = freeGlobal || freeSelf || Function('return this')();
  6873. /** Detect free variable `exports`. */
  6874. var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
  6875. /** Detect free variable `module`. */
  6876. var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
  6877. /** Detect the popular CommonJS extension `module.exports`. */
  6878. var moduleExports = freeModule && freeModule.exports === freeExports;
  6879. /**
  6880. * Adds the key-value `pair` to `map`.
  6881. *
  6882. * @private
  6883. * @param {Object} map The map to modify.
  6884. * @param {Array} pair The key-value pair to add.
  6885. * @returns {Object} Returns `map`.
  6886. */
  6887. function addMapEntry(map, pair) {
  6888. // Don't return `map.set` because it's not chainable in IE 11.
  6889. map.set(pair[0], pair[1]);
  6890. return map;
  6891. }
  6892. /**
  6893. * Adds `value` to `set`.
  6894. *
  6895. * @private
  6896. * @param {Object} set The set to modify.
  6897. * @param {*} value The value to add.
  6898. * @returns {Object} Returns `set`.
  6899. */
  6900. function addSetEntry(set, value) {
  6901. // Don't return `set.add` because it's not chainable in IE 11.
  6902. set.add(value);
  6903. return set;
  6904. }
  6905. /**
  6906. * A specialized version of `_.forEach` for arrays without support for
  6907. * iteratee shorthands.
  6908. *
  6909. * @private
  6910. * @param {Array} [array] The array to iterate over.
  6911. * @param {Function} iteratee The function invoked per iteration.
  6912. * @returns {Array} Returns `array`.
  6913. */
  6914. function arrayEach(array, iteratee) {
  6915. var index = -1,
  6916. length = array ? array.length : 0;
  6917. while (++index < length) {
  6918. if (iteratee(array[index], index, array) === false) {
  6919. break;
  6920. }
  6921. }
  6922. return array;
  6923. }
  6924. /**
  6925. * Appends the elements of `values` to `array`.
  6926. *
  6927. * @private
  6928. * @param {Array} array The array to modify.
  6929. * @param {Array} values The values to append.
  6930. * @returns {Array} Returns `array`.
  6931. */
  6932. function arrayPush(array, values) {
  6933. var index = -1,
  6934. length = values.length,
  6935. offset = array.length;
  6936. while (++index < length) {
  6937. array[offset + index] = values[index];
  6938. }
  6939. return array;
  6940. }
  6941. /**
  6942. * A specialized version of `_.reduce` for arrays without support for
  6943. * iteratee shorthands.
  6944. *
  6945. * @private
  6946. * @param {Array} [array] The array to iterate over.
  6947. * @param {Function} iteratee The function invoked per iteration.
  6948. * @param {*} [accumulator] The initial value.
  6949. * @param {boolean} [initAccum] Specify using the first element of `array` as
  6950. * the initial value.
  6951. * @returns {*} Returns the accumulated value.
  6952. */
  6953. function arrayReduce(array, iteratee, accumulator, initAccum) {
  6954. var index = -1,
  6955. length = array ? array.length : 0;
  6956. if (initAccum && length) {
  6957. accumulator = array[++index];
  6958. }
  6959. while (++index < length) {
  6960. accumulator = iteratee(accumulator, array[index], index, array);
  6961. }
  6962. return accumulator;
  6963. }
  6964. /**
  6965. * The base implementation of `_.times` without support for iteratee shorthands
  6966. * or max array length checks.
  6967. *
  6968. * @private
  6969. * @param {number} n The number of times to invoke `iteratee`.
  6970. * @param {Function} iteratee The function invoked per iteration.
  6971. * @returns {Array} Returns the array of results.
  6972. */
  6973. function baseTimes(n, iteratee) {
  6974. var index = -1,
  6975. result = Array(n);
  6976. while (++index < n) {
  6977. result[index] = iteratee(index);
  6978. }
  6979. return result;
  6980. }
  6981. /**
  6982. * Gets the value at `key` of `object`.
  6983. *
  6984. * @private
  6985. * @param {Object} [object] The object to query.
  6986. * @param {string} key The key of the property to get.
  6987. * @returns {*} Returns the property value.
  6988. */
  6989. function getValue(object, key) {
  6990. return object == null ? undefined : object[key];
  6991. }
  6992. /**
  6993. * Checks if `value` is a host object in IE < 9.
  6994. *
  6995. * @private
  6996. * @param {*} value The value to check.
  6997. * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
  6998. */
  6999. function isHostObject(value) {
  7000. // Many host objects are `Object` objects that can coerce to strings
  7001. // despite having improperly defined `toString` methods.
  7002. var result = false;
  7003. if (value != null && typeof value.toString != 'function') {
  7004. try {
  7005. result = !!(value + '');
  7006. } catch (e) {}
  7007. }
  7008. return result;
  7009. }
  7010. /**
  7011. * Converts `map` to its key-value pairs.
  7012. *
  7013. * @private
  7014. * @param {Object} map The map to convert.
  7015. * @returns {Array} Returns the key-value pairs.
  7016. */
  7017. function mapToArray(map) {
  7018. var index = -1,
  7019. result = Array(map.size);
  7020. map.forEach(function(value, key) {
  7021. result[++index] = [key, value];
  7022. });
  7023. return result;
  7024. }
  7025. /**
  7026. * Creates a unary function that invokes `func` with its argument transformed.
  7027. *
  7028. * @private
  7029. * @param {Function} func The function to wrap.
  7030. * @param {Function} transform The argument transform.
  7031. * @returns {Function} Returns the new function.
  7032. */
  7033. function overArg(func, transform) {
  7034. return function(arg) {
  7035. return func(transform(arg));
  7036. };
  7037. }
  7038. /**
  7039. * Converts `set` to an array of its values.
  7040. *
  7041. * @private
  7042. * @param {Object} set The set to convert.
  7043. * @returns {Array} Returns the values.
  7044. */
  7045. function setToArray(set) {
  7046. var index = -1,
  7047. result = Array(set.size);
  7048. set.forEach(function(value) {
  7049. result[++index] = value;
  7050. });
  7051. return result;
  7052. }
  7053. /** Used for built-in method references. */
  7054. var arrayProto = Array.prototype,
  7055. funcProto = Function.prototype,
  7056. objectProto = Object.prototype;
  7057. /** Used to detect overreaching core-js shims. */
  7058. var coreJsData = root['__core-js_shared__'];
  7059. /** Used to detect methods masquerading as native. */
  7060. var maskSrcKey = (function() {
  7061. var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
  7062. return uid ? ('Symbol(src)_1.' + uid) : '';
  7063. }());
  7064. /** Used to resolve the decompiled source of functions. */
  7065. var funcToString = funcProto.toString;
  7066. /** Used to check objects for own properties. */
  7067. var hasOwnProperty = objectProto.hasOwnProperty;
  7068. /**
  7069. * Used to resolve the
  7070. * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
  7071. * of values.
  7072. */
  7073. var objectToString = objectProto.toString;
  7074. /** Used to detect if a method is native. */
  7075. var reIsNative = RegExp('^' +
  7076. funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
  7077. .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
  7078. );
  7079. /** Built-in value references. */
  7080. var Buffer = moduleExports ? root.Buffer : undefined,
  7081. Symbol = root.Symbol,
  7082. Uint8Array = root.Uint8Array,
  7083. getPrototype = overArg(Object.getPrototypeOf, Object),
  7084. objectCreate = Object.create,
  7085. propertyIsEnumerable = objectProto.propertyIsEnumerable,
  7086. splice = arrayProto.splice;
  7087. /* Built-in method references for those with the same name as other `lodash` methods. */
  7088. var nativeGetSymbols = Object.getOwnPropertySymbols,
  7089. nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
  7090. nativeKeys = overArg(Object.keys, Object);
  7091. /* Built-in method references that are verified to be native. */
  7092. var DataView = getNative(root, 'DataView'),
  7093. Map = getNative(root, 'Map'),
  7094. Promise = getNative(root, 'Promise'),
  7095. Set = getNative(root, 'Set'),
  7096. WeakMap = getNative(root, 'WeakMap'),
  7097. nativeCreate = getNative(Object, 'create');
  7098. /** Used to detect maps, sets, and weakmaps. */
  7099. var dataViewCtorString = toSource(DataView),
  7100. mapCtorString = toSource(Map),
  7101. promiseCtorString = toSource(Promise),
  7102. setCtorString = toSource(Set),
  7103. weakMapCtorString = toSource(WeakMap);
  7104. /** Used to convert symbols to primitives and strings. */
  7105. var symbolProto = Symbol ? Symbol.prototype : undefined,
  7106. symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
  7107. /**
  7108. * Creates a hash object.
  7109. *
  7110. * @private
  7111. * @constructor
  7112. * @param {Array} [entries] The key-value pairs to cache.
  7113. */
  7114. function Hash(entries) {
  7115. var index = -1,
  7116. length = entries ? entries.length : 0;
  7117. this.clear();
  7118. while (++index < length) {
  7119. var entry = entries[index];
  7120. this.set(entry[0], entry[1]);
  7121. }
  7122. }
  7123. /**
  7124. * Removes all key-value entries from the hash.
  7125. *
  7126. * @private
  7127. * @name clear
  7128. * @memberOf Hash
  7129. */
  7130. function hashClear() {
  7131. this.__data__ = nativeCreate ? nativeCreate(null) : {};
  7132. }
  7133. /**
  7134. * Removes `key` and its value from the hash.
  7135. *
  7136. * @private
  7137. * @name delete
  7138. * @memberOf Hash
  7139. * @param {Object} hash The hash to modify.
  7140. * @param {string} key The key of the value to remove.
  7141. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  7142. */
  7143. function hashDelete(key) {
  7144. return this.has(key) && delete this.__data__[key];
  7145. }
  7146. /**
  7147. * Gets the hash value for `key`.
  7148. *
  7149. * @private
  7150. * @name get
  7151. * @memberOf Hash
  7152. * @param {string} key The key of the value to get.
  7153. * @returns {*} Returns the entry value.
  7154. */
  7155. function hashGet(key) {
  7156. var data = this.__data__;
  7157. if (nativeCreate) {
  7158. var result = data[key];
  7159. return result === HASH_UNDEFINED ? undefined : result;
  7160. }
  7161. return hasOwnProperty.call(data, key) ? data[key] : undefined;
  7162. }
  7163. /**
  7164. * Checks if a hash value for `key` exists.
  7165. *
  7166. * @private
  7167. * @name has
  7168. * @memberOf Hash
  7169. * @param {string} key The key of the entry to check.
  7170. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7171. */
  7172. function hashHas(key) {
  7173. var data = this.__data__;
  7174. return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
  7175. }
  7176. /**
  7177. * Sets the hash `key` to `value`.
  7178. *
  7179. * @private
  7180. * @name set
  7181. * @memberOf Hash
  7182. * @param {string} key The key of the value to set.
  7183. * @param {*} value The value to set.
  7184. * @returns {Object} Returns the hash instance.
  7185. */
  7186. function hashSet(key, value) {
  7187. var data = this.__data__;
  7188. data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
  7189. return this;
  7190. }
  7191. // Add methods to `Hash`.
  7192. Hash.prototype.clear = hashClear;
  7193. Hash.prototype['delete'] = hashDelete;
  7194. Hash.prototype.get = hashGet;
  7195. Hash.prototype.has = hashHas;
  7196. Hash.prototype.set = hashSet;
  7197. /**
  7198. * Creates an list cache object.
  7199. *
  7200. * @private
  7201. * @constructor
  7202. * @param {Array} [entries] The key-value pairs to cache.
  7203. */
  7204. function ListCache(entries) {
  7205. var index = -1,
  7206. length = entries ? entries.length : 0;
  7207. this.clear();
  7208. while (++index < length) {
  7209. var entry = entries[index];
  7210. this.set(entry[0], entry[1]);
  7211. }
  7212. }
  7213. /**
  7214. * Removes all key-value entries from the list cache.
  7215. *
  7216. * @private
  7217. * @name clear
  7218. * @memberOf ListCache
  7219. */
  7220. function listCacheClear() {
  7221. this.__data__ = [];
  7222. }
  7223. /**
  7224. * Removes `key` and its value from the list cache.
  7225. *
  7226. * @private
  7227. * @name delete
  7228. * @memberOf ListCache
  7229. * @param {string} key The key of the value to remove.
  7230. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  7231. */
  7232. function listCacheDelete(key) {
  7233. var data = this.__data__,
  7234. index = assocIndexOf(data, key);
  7235. if (index < 0) {
  7236. return false;
  7237. }
  7238. var lastIndex = data.length - 1;
  7239. if (index == lastIndex) {
  7240. data.pop();
  7241. } else {
  7242. splice.call(data, index, 1);
  7243. }
  7244. return true;
  7245. }
  7246. /**
  7247. * Gets the list cache value for `key`.
  7248. *
  7249. * @private
  7250. * @name get
  7251. * @memberOf ListCache
  7252. * @param {string} key The key of the value to get.
  7253. * @returns {*} Returns the entry value.
  7254. */
  7255. function listCacheGet(key) {
  7256. var data = this.__data__,
  7257. index = assocIndexOf(data, key);
  7258. return index < 0 ? undefined : data[index][1];
  7259. }
  7260. /**
  7261. * Checks if a list cache value for `key` exists.
  7262. *
  7263. * @private
  7264. * @name has
  7265. * @memberOf ListCache
  7266. * @param {string} key The key of the entry to check.
  7267. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7268. */
  7269. function listCacheHas(key) {
  7270. return assocIndexOf(this.__data__, key) > -1;
  7271. }
  7272. /**
  7273. * Sets the list cache `key` to `value`.
  7274. *
  7275. * @private
  7276. * @name set
  7277. * @memberOf ListCache
  7278. * @param {string} key The key of the value to set.
  7279. * @param {*} value The value to set.
  7280. * @returns {Object} Returns the list cache instance.
  7281. */
  7282. function listCacheSet(key, value) {
  7283. var data = this.__data__,
  7284. index = assocIndexOf(data, key);
  7285. if (index < 0) {
  7286. data.push([key, value]);
  7287. } else {
  7288. data[index][1] = value;
  7289. }
  7290. return this;
  7291. }
  7292. // Add methods to `ListCache`.
  7293. ListCache.prototype.clear = listCacheClear;
  7294. ListCache.prototype['delete'] = listCacheDelete;
  7295. ListCache.prototype.get = listCacheGet;
  7296. ListCache.prototype.has = listCacheHas;
  7297. ListCache.prototype.set = listCacheSet;
  7298. /**
  7299. * Creates a map cache object to store key-value pairs.
  7300. *
  7301. * @private
  7302. * @constructor
  7303. * @param {Array} [entries] The key-value pairs to cache.
  7304. */
  7305. function MapCache(entries) {
  7306. var index = -1,
  7307. length = entries ? entries.length : 0;
  7308. this.clear();
  7309. while (++index < length) {
  7310. var entry = entries[index];
  7311. this.set(entry[0], entry[1]);
  7312. }
  7313. }
  7314. /**
  7315. * Removes all key-value entries from the map.
  7316. *
  7317. * @private
  7318. * @name clear
  7319. * @memberOf MapCache
  7320. */
  7321. function mapCacheClear() {
  7322. this.__data__ = {
  7323. 'hash': new Hash,
  7324. 'map': new (Map || ListCache),
  7325. 'string': new Hash
  7326. };
  7327. }
  7328. /**
  7329. * Removes `key` and its value from the map.
  7330. *
  7331. * @private
  7332. * @name delete
  7333. * @memberOf MapCache
  7334. * @param {string} key The key of the value to remove.
  7335. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  7336. */
  7337. function mapCacheDelete(key) {
  7338. return getMapData(this, key)['delete'](key);
  7339. }
  7340. /**
  7341. * Gets the map value for `key`.
  7342. *
  7343. * @private
  7344. * @name get
  7345. * @memberOf MapCache
  7346. * @param {string} key The key of the value to get.
  7347. * @returns {*} Returns the entry value.
  7348. */
  7349. function mapCacheGet(key) {
  7350. return getMapData(this, key).get(key);
  7351. }
  7352. /**
  7353. * Checks if a map value for `key` exists.
  7354. *
  7355. * @private
  7356. * @name has
  7357. * @memberOf MapCache
  7358. * @param {string} key The key of the entry to check.
  7359. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7360. */
  7361. function mapCacheHas(key) {
  7362. return getMapData(this, key).has(key);
  7363. }
  7364. /**
  7365. * Sets the map `key` to `value`.
  7366. *
  7367. * @private
  7368. * @name set
  7369. * @memberOf MapCache
  7370. * @param {string} key The key of the value to set.
  7371. * @param {*} value The value to set.
  7372. * @returns {Object} Returns the map cache instance.
  7373. */
  7374. function mapCacheSet(key, value) {
  7375. getMapData(this, key).set(key, value);
  7376. return this;
  7377. }
  7378. // Add methods to `MapCache`.
  7379. MapCache.prototype.clear = mapCacheClear;
  7380. MapCache.prototype['delete'] = mapCacheDelete;
  7381. MapCache.prototype.get = mapCacheGet;
  7382. MapCache.prototype.has = mapCacheHas;
  7383. MapCache.prototype.set = mapCacheSet;
  7384. /**
  7385. * Creates a stack cache object to store key-value pairs.
  7386. *
  7387. * @private
  7388. * @constructor
  7389. * @param {Array} [entries] The key-value pairs to cache.
  7390. */
  7391. function Stack(entries) {
  7392. this.__data__ = new ListCache(entries);
  7393. }
  7394. /**
  7395. * Removes all key-value entries from the stack.
  7396. *
  7397. * @private
  7398. * @name clear
  7399. * @memberOf Stack
  7400. */
  7401. function stackClear() {
  7402. this.__data__ = new ListCache;
  7403. }
  7404. /**
  7405. * Removes `key` and its value from the stack.
  7406. *
  7407. * @private
  7408. * @name delete
  7409. * @memberOf Stack
  7410. * @param {string} key The key of the value to remove.
  7411. * @returns {boolean} Returns `true` if the entry was removed, else `false`.
  7412. */
  7413. function stackDelete(key) {
  7414. return this.__data__['delete'](key);
  7415. }
  7416. /**
  7417. * Gets the stack value for `key`.
  7418. *
  7419. * @private
  7420. * @name get
  7421. * @memberOf Stack
  7422. * @param {string} key The key of the value to get.
  7423. * @returns {*} Returns the entry value.
  7424. */
  7425. function stackGet(key) {
  7426. return this.__data__.get(key);
  7427. }
  7428. /**
  7429. * Checks if a stack value for `key` exists.
  7430. *
  7431. * @private
  7432. * @name has
  7433. * @memberOf Stack
  7434. * @param {string} key The key of the entry to check.
  7435. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
  7436. */
  7437. function stackHas(key) {
  7438. return this.__data__.has(key);
  7439. }
  7440. /**
  7441. * Sets the stack `key` to `value`.
  7442. *
  7443. * @private
  7444. * @name set
  7445. * @memberOf Stack
  7446. * @param {string} key The key of the value to set.
  7447. * @param {*} value The value to set.
  7448. * @returns {Object} Returns the stack cache instance.
  7449. */
  7450. function stackSet(key, value) {
  7451. var cache = this.__data__;
  7452. if (cache instanceof ListCache) {
  7453. var pairs = cache.__data__;
  7454. if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
  7455. pairs.push([key, value]);
  7456. return this;
  7457. }
  7458. cache = this.__data__ = new MapCache(pairs);
  7459. }
  7460. cache.set(key, value);
  7461. return this;
  7462. }
  7463. // Add methods to `Stack`.
  7464. Stack.prototype.clear = stackClear;
  7465. Stack.prototype['delete'] = stackDelete;
  7466. Stack.prototype.get = stackGet;
  7467. Stack.prototype.has = stackHas;
  7468. Stack.prototype.set = stackSet;
  7469. /**
  7470. * Creates an array of the enumerable property names of the array-like `value`.
  7471. *
  7472. * @private
  7473. * @param {*} value The value to query.
  7474. * @param {boolean} inherited Specify returning inherited property names.
  7475. * @returns {Array} Returns the array of property names.
  7476. */
  7477. function arrayLikeKeys(value, inherited) {
  7478. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  7479. // Safari 9 makes `arguments.length` enumerable in strict mode.
  7480. var result = (isArray(value) || isArguments(value))
  7481. ? baseTimes(value.length, String)
  7482. : [];
  7483. var length = result.length,
  7484. skipIndexes = !!length;
  7485. for (var key in value) {
  7486. if ((inherited || hasOwnProperty.call(value, key)) &&
  7487. !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
  7488. result.push(key);
  7489. }
  7490. }
  7491. return result;
  7492. }
  7493. /**
  7494. * Assigns `value` to `key` of `object` if the existing value is not equivalent
  7495. * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  7496. * for equality comparisons.
  7497. *
  7498. * @private
  7499. * @param {Object} object The object to modify.
  7500. * @param {string} key The key of the property to assign.
  7501. * @param {*} value The value to assign.
  7502. */
  7503. function assignValue(object, key, value) {
  7504. var objValue = object[key];
  7505. if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
  7506. (value === undefined && !(key in object))) {
  7507. object[key] = value;
  7508. }
  7509. }
  7510. /**
  7511. * Gets the index at which the `key` is found in `array` of key-value pairs.
  7512. *
  7513. * @private
  7514. * @param {Array} array The array to inspect.
  7515. * @param {*} key The key to search for.
  7516. * @returns {number} Returns the index of the matched value, else `-1`.
  7517. */
  7518. function assocIndexOf(array, key) {
  7519. var length = array.length;
  7520. while (length--) {
  7521. if (eq(array[length][0], key)) {
  7522. return length;
  7523. }
  7524. }
  7525. return -1;
  7526. }
  7527. /**
  7528. * The base implementation of `_.assign` without support for multiple sources
  7529. * or `customizer` functions.
  7530. *
  7531. * @private
  7532. * @param {Object} object The destination object.
  7533. * @param {Object} source The source object.
  7534. * @returns {Object} Returns `object`.
  7535. */
  7536. function baseAssign(object, source) {
  7537. return object && copyObject(source, keys(source), object);
  7538. }
  7539. /**
  7540. * The base implementation of `_.clone` and `_.cloneDeep` which tracks
  7541. * traversed objects.
  7542. *
  7543. * @private
  7544. * @param {*} value The value to clone.
  7545. * @param {boolean} [isDeep] Specify a deep clone.
  7546. * @param {boolean} [isFull] Specify a clone including symbols.
  7547. * @param {Function} [customizer] The function to customize cloning.
  7548. * @param {string} [key] The key of `value`.
  7549. * @param {Object} [object] The parent object of `value`.
  7550. * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
  7551. * @returns {*} Returns the cloned value.
  7552. */
  7553. function baseClone(value, isDeep, isFull, customizer, key, object, stack) {
  7554. var result;
  7555. if (customizer) {
  7556. result = object ? customizer(value, key, object, stack) : customizer(value);
  7557. }
  7558. if (result !== undefined) {
  7559. return result;
  7560. }
  7561. if (!isObject(value)) {
  7562. return value;
  7563. }
  7564. var isArr = isArray(value);
  7565. if (isArr) {
  7566. result = initCloneArray(value);
  7567. if (!isDeep) {
  7568. return copyArray(value, result);
  7569. }
  7570. } else {
  7571. var tag = getTag(value),
  7572. isFunc = tag == funcTag || tag == genTag;
  7573. if (isBuffer(value)) {
  7574. return cloneBuffer(value, isDeep);
  7575. }
  7576. if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
  7577. if (isHostObject(value)) {
  7578. return object ? value : {};
  7579. }
  7580. result = initCloneObject(isFunc ? {} : value);
  7581. if (!isDeep) {
  7582. return copySymbols(value, baseAssign(result, value));
  7583. }
  7584. } else {
  7585. if (!cloneableTags[tag]) {
  7586. return object ? value : {};
  7587. }
  7588. result = initCloneByTag(value, tag, baseClone, isDeep);
  7589. }
  7590. }
  7591. // Check for circular references and return its corresponding clone.
  7592. stack || (stack = new Stack);
  7593. var stacked = stack.get(value);
  7594. if (stacked) {
  7595. return stacked;
  7596. }
  7597. stack.set(value, result);
  7598. if (!isArr) {
  7599. var props = isFull ? getAllKeys(value) : keys(value);
  7600. }
  7601. arrayEach(props || value, function(subValue, key) {
  7602. if (props) {
  7603. key = subValue;
  7604. subValue = value[key];
  7605. }
  7606. // Recursively populate clone (susceptible to call stack limits).
  7607. assignValue(result, key, baseClone(subValue, isDeep, isFull, customizer, key, value, stack));
  7608. });
  7609. return result;
  7610. }
  7611. /**
  7612. * The base implementation of `_.create` without support for assigning
  7613. * properties to the created object.
  7614. *
  7615. * @private
  7616. * @param {Object} prototype The object to inherit from.
  7617. * @returns {Object} Returns the new object.
  7618. */
  7619. function baseCreate(proto) {
  7620. return isObject(proto) ? objectCreate(proto) : {};
  7621. }
  7622. /**
  7623. * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
  7624. * `keysFunc` and `symbolsFunc` to get the enumerable property names and
  7625. * symbols of `object`.
  7626. *
  7627. * @private
  7628. * @param {Object} object The object to query.
  7629. * @param {Function} keysFunc The function to get the keys of `object`.
  7630. * @param {Function} symbolsFunc The function to get the symbols of `object`.
  7631. * @returns {Array} Returns the array of property names and symbols.
  7632. */
  7633. function baseGetAllKeys(object, keysFunc, symbolsFunc) {
  7634. var result = keysFunc(object);
  7635. return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
  7636. }
  7637. /**
  7638. * The base implementation of `getTag`.
  7639. *
  7640. * @private
  7641. * @param {*} value The value to query.
  7642. * @returns {string} Returns the `toStringTag`.
  7643. */
  7644. function baseGetTag(value) {
  7645. return objectToString.call(value);
  7646. }
  7647. /**
  7648. * The base implementation of `_.isNative` without bad shim checks.
  7649. *
  7650. * @private
  7651. * @param {*} value The value to check.
  7652. * @returns {boolean} Returns `true` if `value` is a native function,
  7653. * else `false`.
  7654. */
  7655. function baseIsNative(value) {
  7656. if (!isObject(value) || isMasked(value)) {
  7657. return false;
  7658. }
  7659. var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
  7660. return pattern.test(toSource(value));
  7661. }
  7662. /**
  7663. * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
  7664. *
  7665. * @private
  7666. * @param {Object} object The object to query.
  7667. * @returns {Array} Returns the array of property names.
  7668. */
  7669. function baseKeys(object) {
  7670. if (!isPrototype(object)) {
  7671. return nativeKeys(object);
  7672. }
  7673. var result = [];
  7674. for (var key in Object(object)) {
  7675. if (hasOwnProperty.call(object, key) && key != 'constructor') {
  7676. result.push(key);
  7677. }
  7678. }
  7679. return result;
  7680. }
  7681. /**
  7682. * Creates a clone of `buffer`.
  7683. *
  7684. * @private
  7685. * @param {Buffer} buffer The buffer to clone.
  7686. * @param {boolean} [isDeep] Specify a deep clone.
  7687. * @returns {Buffer} Returns the cloned buffer.
  7688. */
  7689. function cloneBuffer(buffer, isDeep) {
  7690. if (isDeep) {
  7691. return buffer.slice();
  7692. }
  7693. var result = new buffer.constructor(buffer.length);
  7694. buffer.copy(result);
  7695. return result;
  7696. }
  7697. /**
  7698. * Creates a clone of `arrayBuffer`.
  7699. *
  7700. * @private
  7701. * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
  7702. * @returns {ArrayBuffer} Returns the cloned array buffer.
  7703. */
  7704. function cloneArrayBuffer(arrayBuffer) {
  7705. var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
  7706. new Uint8Array(result).set(new Uint8Array(arrayBuffer));
  7707. return result;
  7708. }
  7709. /**
  7710. * Creates a clone of `dataView`.
  7711. *
  7712. * @private
  7713. * @param {Object} dataView The data view to clone.
  7714. * @param {boolean} [isDeep] Specify a deep clone.
  7715. * @returns {Object} Returns the cloned data view.
  7716. */
  7717. function cloneDataView(dataView, isDeep) {
  7718. var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
  7719. return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
  7720. }
  7721. /**
  7722. * Creates a clone of `map`.
  7723. *
  7724. * @private
  7725. * @param {Object} map The map to clone.
  7726. * @param {Function} cloneFunc The function to clone values.
  7727. * @param {boolean} [isDeep] Specify a deep clone.
  7728. * @returns {Object} Returns the cloned map.
  7729. */
  7730. function cloneMap(map, isDeep, cloneFunc) {
  7731. var array = isDeep ? cloneFunc(mapToArray(map), true) : mapToArray(map);
  7732. return arrayReduce(array, addMapEntry, new map.constructor);
  7733. }
  7734. /**
  7735. * Creates a clone of `regexp`.
  7736. *
  7737. * @private
  7738. * @param {Object} regexp The regexp to clone.
  7739. * @returns {Object} Returns the cloned regexp.
  7740. */
  7741. function cloneRegExp(regexp) {
  7742. var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
  7743. result.lastIndex = regexp.lastIndex;
  7744. return result;
  7745. }
  7746. /**
  7747. * Creates a clone of `set`.
  7748. *
  7749. * @private
  7750. * @param {Object} set The set to clone.
  7751. * @param {Function} cloneFunc The function to clone values.
  7752. * @param {boolean} [isDeep] Specify a deep clone.
  7753. * @returns {Object} Returns the cloned set.
  7754. */
  7755. function cloneSet(set, isDeep, cloneFunc) {
  7756. var array = isDeep ? cloneFunc(setToArray(set), true) : setToArray(set);
  7757. return arrayReduce(array, addSetEntry, new set.constructor);
  7758. }
  7759. /**
  7760. * Creates a clone of the `symbol` object.
  7761. *
  7762. * @private
  7763. * @param {Object} symbol The symbol object to clone.
  7764. * @returns {Object} Returns the cloned symbol object.
  7765. */
  7766. function cloneSymbol(symbol) {
  7767. return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
  7768. }
  7769. /**
  7770. * Creates a clone of `typedArray`.
  7771. *
  7772. * @private
  7773. * @param {Object} typedArray The typed array to clone.
  7774. * @param {boolean} [isDeep] Specify a deep clone.
  7775. * @returns {Object} Returns the cloned typed array.
  7776. */
  7777. function cloneTypedArray(typedArray, isDeep) {
  7778. var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
  7779. return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
  7780. }
  7781. /**
  7782. * Copies the values of `source` to `array`.
  7783. *
  7784. * @private
  7785. * @param {Array} source The array to copy values from.
  7786. * @param {Array} [array=[]] The array to copy values to.
  7787. * @returns {Array} Returns `array`.
  7788. */
  7789. function copyArray(source, array) {
  7790. var index = -1,
  7791. length = source.length;
  7792. array || (array = Array(length));
  7793. while (++index < length) {
  7794. array[index] = source[index];
  7795. }
  7796. return array;
  7797. }
  7798. /**
  7799. * Copies properties of `source` to `object`.
  7800. *
  7801. * @private
  7802. * @param {Object} source The object to copy properties from.
  7803. * @param {Array} props The property identifiers to copy.
  7804. * @param {Object} [object={}] The object to copy properties to.
  7805. * @param {Function} [customizer] The function to customize copied values.
  7806. * @returns {Object} Returns `object`.
  7807. */
  7808. function copyObject(source, props, object, customizer) {
  7809. object || (object = {});
  7810. var index = -1,
  7811. length = props.length;
  7812. while (++index < length) {
  7813. var key = props[index];
  7814. var newValue = customizer
  7815. ? customizer(object[key], source[key], key, object, source)
  7816. : undefined;
  7817. assignValue(object, key, newValue === undefined ? source[key] : newValue);
  7818. }
  7819. return object;
  7820. }
  7821. /**
  7822. * Copies own symbol properties of `source` to `object`.
  7823. *
  7824. * @private
  7825. * @param {Object} source The object to copy symbols from.
  7826. * @param {Object} [object={}] The object to copy symbols to.
  7827. * @returns {Object} Returns `object`.
  7828. */
  7829. function copySymbols(source, object) {
  7830. return copyObject(source, getSymbols(source), object);
  7831. }
  7832. /**
  7833. * Creates an array of own enumerable property names and symbols of `object`.
  7834. *
  7835. * @private
  7836. * @param {Object} object The object to query.
  7837. * @returns {Array} Returns the array of property names and symbols.
  7838. */
  7839. function getAllKeys(object) {
  7840. return baseGetAllKeys(object, keys, getSymbols);
  7841. }
  7842. /**
  7843. * Gets the data for `map`.
  7844. *
  7845. * @private
  7846. * @param {Object} map The map to query.
  7847. * @param {string} key The reference key.
  7848. * @returns {*} Returns the map data.
  7849. */
  7850. function getMapData(map, key) {
  7851. var data = map.__data__;
  7852. return isKeyable(key)
  7853. ? data[typeof key == 'string' ? 'string' : 'hash']
  7854. : data.map;
  7855. }
  7856. /**
  7857. * Gets the native function at `key` of `object`.
  7858. *
  7859. * @private
  7860. * @param {Object} object The object to query.
  7861. * @param {string} key The key of the method to get.
  7862. * @returns {*} Returns the function if it's native, else `undefined`.
  7863. */
  7864. function getNative(object, key) {
  7865. var value = getValue(object, key);
  7866. return baseIsNative(value) ? value : undefined;
  7867. }
  7868. /**
  7869. * Creates an array of the own enumerable symbol properties of `object`.
  7870. *
  7871. * @private
  7872. * @param {Object} object The object to query.
  7873. * @returns {Array} Returns the array of symbols.
  7874. */
  7875. var getSymbols = nativeGetSymbols ? overArg(nativeGetSymbols, Object) : stubArray;
  7876. /**
  7877. * Gets the `toStringTag` of `value`.
  7878. *
  7879. * @private
  7880. * @param {*} value The value to query.
  7881. * @returns {string} Returns the `toStringTag`.
  7882. */
  7883. var getTag = baseGetTag;
  7884. // Fallback for data views, maps, sets, and weak maps in IE 11,
  7885. // for data views in Edge < 14, and promises in Node.js.
  7886. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
  7887. (Map && getTag(new Map) != mapTag) ||
  7888. (Promise && getTag(Promise.resolve()) != promiseTag) ||
  7889. (Set && getTag(new Set) != setTag) ||
  7890. (WeakMap && getTag(new WeakMap) != weakMapTag)) {
  7891. getTag = function(value) {
  7892. var result = objectToString.call(value),
  7893. Ctor = result == objectTag ? value.constructor : undefined,
  7894. ctorString = Ctor ? toSource(Ctor) : undefined;
  7895. if (ctorString) {
  7896. switch (ctorString) {
  7897. case dataViewCtorString: return dataViewTag;
  7898. case mapCtorString: return mapTag;
  7899. case promiseCtorString: return promiseTag;
  7900. case setCtorString: return setTag;
  7901. case weakMapCtorString: return weakMapTag;
  7902. }
  7903. }
  7904. return result;
  7905. };
  7906. }
  7907. /**
  7908. * Initializes an array clone.
  7909. *
  7910. * @private
  7911. * @param {Array} array The array to clone.
  7912. * @returns {Array} Returns the initialized clone.
  7913. */
  7914. function initCloneArray(array) {
  7915. var length = array.length,
  7916. result = array.constructor(length);
  7917. // Add properties assigned by `RegExp#exec`.
  7918. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
  7919. result.index = array.index;
  7920. result.input = array.input;
  7921. }
  7922. return result;
  7923. }
  7924. /**
  7925. * Initializes an object clone.
  7926. *
  7927. * @private
  7928. * @param {Object} object The object to clone.
  7929. * @returns {Object} Returns the initialized clone.
  7930. */
  7931. function initCloneObject(object) {
  7932. return (typeof object.constructor == 'function' && !isPrototype(object))
  7933. ? baseCreate(getPrototype(object))
  7934. : {};
  7935. }
  7936. /**
  7937. * Initializes an object clone based on its `toStringTag`.
  7938. *
  7939. * **Note:** This function only supports cloning values with tags of
  7940. * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
  7941. *
  7942. * @private
  7943. * @param {Object} object The object to clone.
  7944. * @param {string} tag The `toStringTag` of the object to clone.
  7945. * @param {Function} cloneFunc The function to clone values.
  7946. * @param {boolean} [isDeep] Specify a deep clone.
  7947. * @returns {Object} Returns the initialized clone.
  7948. */
  7949. function initCloneByTag(object, tag, cloneFunc, isDeep) {
  7950. var Ctor = object.constructor;
  7951. switch (tag) {
  7952. case arrayBufferTag:
  7953. return cloneArrayBuffer(object);
  7954. case boolTag:
  7955. case dateTag:
  7956. return new Ctor(+object);
  7957. case dataViewTag:
  7958. return cloneDataView(object, isDeep);
  7959. case float32Tag: case float64Tag:
  7960. case int8Tag: case int16Tag: case int32Tag:
  7961. case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
  7962. return cloneTypedArray(object, isDeep);
  7963. case mapTag:
  7964. return cloneMap(object, isDeep, cloneFunc);
  7965. case numberTag:
  7966. case stringTag:
  7967. return new Ctor(object);
  7968. case regexpTag:
  7969. return cloneRegExp(object);
  7970. case setTag:
  7971. return cloneSet(object, isDeep, cloneFunc);
  7972. case symbolTag:
  7973. return cloneSymbol(object);
  7974. }
  7975. }
  7976. /**
  7977. * Checks if `value` is a valid array-like index.
  7978. *
  7979. * @private
  7980. * @param {*} value The value to check.
  7981. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
  7982. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
  7983. */
  7984. function isIndex(value, length) {
  7985. length = length == null ? MAX_SAFE_INTEGER : length;
  7986. return !!length &&
  7987. (typeof value == 'number' || reIsUint.test(value)) &&
  7988. (value > -1 && value % 1 == 0 && value < length);
  7989. }
  7990. /**
  7991. * Checks if `value` is suitable for use as unique object key.
  7992. *
  7993. * @private
  7994. * @param {*} value The value to check.
  7995. * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
  7996. */
  7997. function isKeyable(value) {
  7998. var type = typeof value;
  7999. return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
  8000. ? (value !== '__proto__')
  8001. : (value === null);
  8002. }
  8003. /**
  8004. * Checks if `func` has its source masked.
  8005. *
  8006. * @private
  8007. * @param {Function} func The function to check.
  8008. * @returns {boolean} Returns `true` if `func` is masked, else `false`.
  8009. */
  8010. function isMasked(func) {
  8011. return !!maskSrcKey && (maskSrcKey in func);
  8012. }
  8013. /**
  8014. * Checks if `value` is likely a prototype object.
  8015. *
  8016. * @private
  8017. * @param {*} value The value to check.
  8018. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
  8019. */
  8020. function isPrototype(value) {
  8021. var Ctor = value && value.constructor,
  8022. proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
  8023. return value === proto;
  8024. }
  8025. /**
  8026. * Converts `func` to its source code.
  8027. *
  8028. * @private
  8029. * @param {Function} func The function to process.
  8030. * @returns {string} Returns the source code.
  8031. */
  8032. function toSource(func) {
  8033. if (func != null) {
  8034. try {
  8035. return funcToString.call(func);
  8036. } catch (e) {}
  8037. try {
  8038. return (func + '');
  8039. } catch (e) {}
  8040. }
  8041. return '';
  8042. }
  8043. /**
  8044. * This method is like `_.clone` except that it recursively clones `value`.
  8045. *
  8046. * @static
  8047. * @memberOf _
  8048. * @since 1.0.0
  8049. * @category Lang
  8050. * @param {*} value The value to recursively clone.
  8051. * @returns {*} Returns the deep cloned value.
  8052. * @see _.clone
  8053. * @example
  8054. *
  8055. * var objects = [{ 'a': 1 }, { 'b': 2 }];
  8056. *
  8057. * var deep = _.cloneDeep(objects);
  8058. * console.log(deep[0] === objects[0]);
  8059. * // => false
  8060. */
  8061. function cloneDeep(value) {
  8062. return baseClone(value, true, true);
  8063. }
  8064. /**
  8065. * Performs a
  8066. * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
  8067. * comparison between two values to determine if they are equivalent.
  8068. *
  8069. * @static
  8070. * @memberOf _
  8071. * @since 4.0.0
  8072. * @category Lang
  8073. * @param {*} value The value to compare.
  8074. * @param {*} other The other value to compare.
  8075. * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
  8076. * @example
  8077. *
  8078. * var object = { 'a': 1 };
  8079. * var other = { 'a': 1 };
  8080. *
  8081. * _.eq(object, object);
  8082. * // => true
  8083. *
  8084. * _.eq(object, other);
  8085. * // => false
  8086. *
  8087. * _.eq('a', 'a');
  8088. * // => true
  8089. *
  8090. * _.eq('a', Object('a'));
  8091. * // => false
  8092. *
  8093. * _.eq(NaN, NaN);
  8094. * // => true
  8095. */
  8096. function eq(value, other) {
  8097. return value === other || (value !== value && other !== other);
  8098. }
  8099. /**
  8100. * Checks if `value` is likely an `arguments` object.
  8101. *
  8102. * @static
  8103. * @memberOf _
  8104. * @since 0.1.0
  8105. * @category Lang
  8106. * @param {*} value The value to check.
  8107. * @returns {boolean} Returns `true` if `value` is an `arguments` object,
  8108. * else `false`.
  8109. * @example
  8110. *
  8111. * _.isArguments(function() { return arguments; }());
  8112. * // => true
  8113. *
  8114. * _.isArguments([1, 2, 3]);
  8115. * // => false
  8116. */
  8117. function isArguments(value) {
  8118. // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
  8119. return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
  8120. (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
  8121. }
  8122. /**
  8123. * Checks if `value` is classified as an `Array` object.
  8124. *
  8125. * @static
  8126. * @memberOf _
  8127. * @since 0.1.0
  8128. * @category Lang
  8129. * @param {*} value The value to check.
  8130. * @returns {boolean} Returns `true` if `value` is an array, else `false`.
  8131. * @example
  8132. *
  8133. * _.isArray([1, 2, 3]);
  8134. * // => true
  8135. *
  8136. * _.isArray(document.body.children);
  8137. * // => false
  8138. *
  8139. * _.isArray('abc');
  8140. * // => false
  8141. *
  8142. * _.isArray(_.noop);
  8143. * // => false
  8144. */
  8145. var isArray = Array.isArray;
  8146. /**
  8147. * Checks if `value` is array-like. A value is considered array-like if it's
  8148. * not a function and has a `value.length` that's an integer greater than or
  8149. * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
  8150. *
  8151. * @static
  8152. * @memberOf _
  8153. * @since 4.0.0
  8154. * @category Lang
  8155. * @param {*} value The value to check.
  8156. * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
  8157. * @example
  8158. *
  8159. * _.isArrayLike([1, 2, 3]);
  8160. * // => true
  8161. *
  8162. * _.isArrayLike(document.body.children);
  8163. * // => true
  8164. *
  8165. * _.isArrayLike('abc');
  8166. * // => true
  8167. *
  8168. * _.isArrayLike(_.noop);
  8169. * // => false
  8170. */
  8171. function isArrayLike(value) {
  8172. return value != null && isLength(value.length) && !isFunction(value);
  8173. }
  8174. /**
  8175. * This method is like `_.isArrayLike` except that it also checks if `value`
  8176. * is an object.
  8177. *
  8178. * @static
  8179. * @memberOf _
  8180. * @since 4.0.0
  8181. * @category Lang
  8182. * @param {*} value The value to check.
  8183. * @returns {boolean} Returns `true` if `value` is an array-like object,
  8184. * else `false`.
  8185. * @example
  8186. *
  8187. * _.isArrayLikeObject([1, 2, 3]);
  8188. * // => true
  8189. *
  8190. * _.isArrayLikeObject(document.body.children);
  8191. * // => true
  8192. *
  8193. * _.isArrayLikeObject('abc');
  8194. * // => false
  8195. *
  8196. * _.isArrayLikeObject(_.noop);
  8197. * // => false
  8198. */
  8199. function isArrayLikeObject(value) {
  8200. return isObjectLike(value) && isArrayLike(value);
  8201. }
  8202. /**
  8203. * Checks if `value` is a buffer.
  8204. *
  8205. * @static
  8206. * @memberOf _
  8207. * @since 4.3.0
  8208. * @category Lang
  8209. * @param {*} value The value to check.
  8210. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
  8211. * @example
  8212. *
  8213. * _.isBuffer(new Buffer(2));
  8214. * // => true
  8215. *
  8216. * _.isBuffer(new Uint8Array(2));
  8217. * // => false
  8218. */
  8219. var isBuffer = nativeIsBuffer || stubFalse;
  8220. /**
  8221. * Checks if `value` is classified as a `Function` object.
  8222. *
  8223. * @static
  8224. * @memberOf _
  8225. * @since 0.1.0
  8226. * @category Lang
  8227. * @param {*} value The value to check.
  8228. * @returns {boolean} Returns `true` if `value` is a function, else `false`.
  8229. * @example
  8230. *
  8231. * _.isFunction(_);
  8232. * // => true
  8233. *
  8234. * _.isFunction(/abc/);
  8235. * // => false
  8236. */
  8237. function isFunction(value) {
  8238. // The use of `Object#toString` avoids issues with the `typeof` operator
  8239. // in Safari 8-9 which returns 'object' for typed array and other constructors.
  8240. var tag = isObject(value) ? objectToString.call(value) : '';
  8241. return tag == funcTag || tag == genTag;
  8242. }
  8243. /**
  8244. * Checks if `value` is a valid array-like length.
  8245. *
  8246. * **Note:** This method is loosely based on
  8247. * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
  8248. *
  8249. * @static
  8250. * @memberOf _
  8251. * @since 4.0.0
  8252. * @category Lang
  8253. * @param {*} value The value to check.
  8254. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
  8255. * @example
  8256. *
  8257. * _.isLength(3);
  8258. * // => true
  8259. *
  8260. * _.isLength(Number.MIN_VALUE);
  8261. * // => false
  8262. *
  8263. * _.isLength(Infinity);
  8264. * // => false
  8265. *
  8266. * _.isLength('3');
  8267. * // => false
  8268. */
  8269. function isLength(value) {
  8270. return typeof value == 'number' &&
  8271. value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
  8272. }
  8273. /**
  8274. * Checks if `value` is the
  8275. * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
  8276. * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
  8277. *
  8278. * @static
  8279. * @memberOf _
  8280. * @since 0.1.0
  8281. * @category Lang
  8282. * @param {*} value The value to check.
  8283. * @returns {boolean} Returns `true` if `value` is an object, else `false`.
  8284. * @example
  8285. *
  8286. * _.isObject({});
  8287. * // => true
  8288. *
  8289. * _.isObject([1, 2, 3]);
  8290. * // => true
  8291. *
  8292. * _.isObject(_.noop);
  8293. * // => true
  8294. *
  8295. * _.isObject(null);
  8296. * // => false
  8297. */
  8298. function isObject(value) {
  8299. var type = typeof value;
  8300. return !!value && (type == 'object' || type == 'function');
  8301. }
  8302. /**
  8303. * Checks if `value` is object-like. A value is object-like if it's not `null`
  8304. * and has a `typeof` result of "object".
  8305. *
  8306. * @static
  8307. * @memberOf _
  8308. * @since 4.0.0
  8309. * @category Lang
  8310. * @param {*} value The value to check.
  8311. * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
  8312. * @example
  8313. *
  8314. * _.isObjectLike({});
  8315. * // => true
  8316. *
  8317. * _.isObjectLike([1, 2, 3]);
  8318. * // => true
  8319. *
  8320. * _.isObjectLike(_.noop);
  8321. * // => false
  8322. *
  8323. * _.isObjectLike(null);
  8324. * // => false
  8325. */
  8326. function isObjectLike(value) {
  8327. return !!value && typeof value == 'object';
  8328. }
  8329. /**
  8330. * Creates an array of the own enumerable property names of `object`.
  8331. *
  8332. * **Note:** Non-object values are coerced to objects. See the
  8333. * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
  8334. * for more details.
  8335. *
  8336. * @static
  8337. * @since 0.1.0
  8338. * @memberOf _
  8339. * @category Object
  8340. * @param {Object} object The object to query.
  8341. * @returns {Array} Returns the array of property names.
  8342. * @example
  8343. *
  8344. * function Foo() {
  8345. * this.a = 1;
  8346. * this.b = 2;
  8347. * }
  8348. *
  8349. * Foo.prototype.c = 3;
  8350. *
  8351. * _.keys(new Foo);
  8352. * // => ['a', 'b'] (iteration order is not guaranteed)
  8353. *
  8354. * _.keys('hi');
  8355. * // => ['0', '1']
  8356. */
  8357. function keys(object) {
  8358. return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
  8359. }
  8360. /**
  8361. * This method returns a new empty array.
  8362. *
  8363. * @static
  8364. * @memberOf _
  8365. * @since 4.13.0
  8366. * @category Util
  8367. * @returns {Array} Returns the new empty array.
  8368. * @example
  8369. *
  8370. * var arrays = _.times(2, _.stubArray);
  8371. *
  8372. * console.log(arrays);
  8373. * // => [[], []]
  8374. *
  8375. * console.log(arrays[0] === arrays[1]);
  8376. * // => false
  8377. */
  8378. function stubArray() {
  8379. return [];
  8380. }
  8381. /**
  8382. * This method returns `false`.
  8383. *
  8384. * @static
  8385. * @memberOf _
  8386. * @since 4.13.0
  8387. * @category Util
  8388. * @returns {boolean} Returns `false`.
  8389. * @example
  8390. *
  8391. * _.times(2, _.stubFalse);
  8392. * // => [false, false]
  8393. */
  8394. function stubFalse() {
  8395. return false;
  8396. }
  8397. module.exports = cloneDeep;
  8398. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8399. },{}],48:[function(require,module,exports){
  8400. var support = require('webrtcsupport');
  8401. function GainController(stream) {
  8402. this.support = support.webAudio && support.mediaStream;
  8403. // set our starting value
  8404. this.gain = 1;
  8405. if (this.support) {
  8406. var context = this.context = new support.AudioContext();
  8407. this.microphone = context.createMediaStreamSource(stream);
  8408. this.gainFilter = context.createGain();
  8409. this.destination = context.createMediaStreamDestination();
  8410. this.outputStream = this.destination.stream;
  8411. this.microphone.connect(this.gainFilter);
  8412. this.gainFilter.connect(this.destination);
  8413. stream.addTrack(this.outputStream.getAudioTracks()[0]);
  8414. stream.removeTrack(stream.getAudioTracks()[0]);
  8415. }
  8416. this.stream = stream;
  8417. }
  8418. // setting
  8419. GainController.prototype.setGain = function (val) {
  8420. // check for support
  8421. if (!this.support) return;
  8422. this.gainFilter.gain.value = val;
  8423. this.gain = val;
  8424. };
  8425. GainController.prototype.getGain = function () {
  8426. return this.gain;
  8427. };
  8428. GainController.prototype.off = function () {
  8429. return this.setGain(0);
  8430. };
  8431. GainController.prototype.on = function () {
  8432. this.setGain(1);
  8433. };
  8434. module.exports = GainController;
  8435. },{"webrtcsupport":49}],49:[function(require,module,exports){
  8436. // created by @HenrikJoreteg
  8437. var prefix;
  8438. var version;
  8439. if (window.mozRTCPeerConnection || navigator.mozGetUserMedia) {
  8440. prefix = 'moz';
  8441. version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  8442. } else if (window.webkitRTCPeerConnection || navigator.webkitGetUserMedia) {
  8443. prefix = 'webkit';
  8444. version = navigator.userAgent.match(/Chrom(e|ium)/) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  8445. }
  8446. var PC = window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  8447. var IceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
  8448. var SessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
  8449. var MediaStream = window.webkitMediaStream || window.MediaStream;
  8450. var screenSharing = window.location.protocol === 'https:' &&
  8451. ((prefix === 'webkit' && version >= 26) ||
  8452. (prefix === 'moz' && version >= 33))
  8453. var AudioContext = window.AudioContext || window.webkitAudioContext;
  8454. var videoEl = document.createElement('video');
  8455. var supportVp8 = videoEl && videoEl.canPlayType && videoEl.canPlayType('video/webm; codecs="vp8", vorbis') === "probably";
  8456. var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia || navigator.mozGetUserMedia;
  8457. // export support flags and constructors.prototype && PC
  8458. module.exports = {
  8459. prefix: prefix,
  8460. browserVersion: version,
  8461. support: !!PC && supportVp8 && !!getUserMedia,
  8462. // new support style
  8463. supportRTCPeerConnection: !!PC,
  8464. supportVp8: supportVp8,
  8465. supportGetUserMedia: !!getUserMedia,
  8466. supportDataChannel: !!(PC && PC.prototype && PC.prototype.createDataChannel),
  8467. supportWebAudio: !!(AudioContext && AudioContext.prototype.createMediaStreamSource),
  8468. supportMediaStream: !!(MediaStream && MediaStream.prototype.removeTrack),
  8469. supportScreenSharing: !!screenSharing,
  8470. // old deprecated style. Dont use this anymore
  8471. dataChannel: !!(PC && PC.prototype && PC.prototype.createDataChannel),
  8472. webAudio: !!(AudioContext && AudioContext.prototype.createMediaStreamSource),
  8473. mediaStream: !!(MediaStream && MediaStream.prototype.removeTrack),
  8474. screenSharing: !!screenSharing,
  8475. // constructors
  8476. AudioContext: AudioContext,
  8477. PeerConnection: PC,
  8478. SessionDescription: SessionDescription,
  8479. IceCandidate: IceCandidate,
  8480. MediaStream: MediaStream,
  8481. getUserMedia: getUserMedia
  8482. };
  8483. },{}],50:[function(require,module,exports){
  8484. var methods = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(",");
  8485. var l = methods.length;
  8486. var fn = function () {};
  8487. var mockconsole = {};
  8488. while (l--) {
  8489. mockconsole[methods[l]] = fn;
  8490. }
  8491. module.exports = mockconsole;
  8492. },{}],51:[function(require,module,exports){
  8493. /**
  8494. * HOP ref.
  8495. */
  8496. var has = Object.prototype.hasOwnProperty;
  8497. /**
  8498. * Return own keys in `obj`.
  8499. *
  8500. * @param {Object} obj
  8501. * @return {Array}
  8502. * @api public
  8503. */
  8504. exports.keys = Object.keys || function(obj){
  8505. var keys = [];
  8506. for (var key in obj) {
  8507. if (has.call(obj, key)) {
  8508. keys.push(key);
  8509. }
  8510. }
  8511. return keys;
  8512. };
  8513. /**
  8514. * Return own values in `obj`.
  8515. *
  8516. * @param {Object} obj
  8517. * @return {Array}
  8518. * @api public
  8519. */
  8520. exports.values = function(obj){
  8521. var vals = [];
  8522. for (var key in obj) {
  8523. if (has.call(obj, key)) {
  8524. vals.push(obj[key]);
  8525. }
  8526. }
  8527. return vals;
  8528. };
  8529. /**
  8530. * Merge `b` into `a`.
  8531. *
  8532. * @param {Object} a
  8533. * @param {Object} b
  8534. * @return {Object} a
  8535. * @api public
  8536. */
  8537. exports.merge = function(a, b){
  8538. for (var key in b) {
  8539. if (has.call(b, key)) {
  8540. a[key] = b[key];
  8541. }
  8542. }
  8543. return a;
  8544. };
  8545. /**
  8546. * Return length of `obj`.
  8547. *
  8548. * @param {Object} obj
  8549. * @return {Number}
  8550. * @api public
  8551. */
  8552. exports.length = function(obj){
  8553. return exports.keys(obj).length;
  8554. };
  8555. /**
  8556. * Check if `obj` is empty.
  8557. *
  8558. * @param {Object} obj
  8559. * @return {Boolean}
  8560. * @api public
  8561. */
  8562. exports.isEmpty = function(obj){
  8563. return 0 == exports.length(obj);
  8564. };
  8565. },{}],52:[function(require,module,exports){
  8566. (function (global){
  8567. /**
  8568. * JSON parse.
  8569. *
  8570. * @see Based on jQuery#parseJSON (MIT) and JSON2
  8571. * @api private
  8572. */
  8573. var rvalidchars = /^[\],:{}\s]*$/;
  8574. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  8575. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  8576. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  8577. var rtrimLeft = /^\s+/;
  8578. var rtrimRight = /\s+$/;
  8579. module.exports = function parsejson(data) {
  8580. if ('string' != typeof data || !data) {
  8581. return null;
  8582. }
  8583. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  8584. // Attempt to parse using the native JSON parser first
  8585. if (global.JSON && JSON.parse) {
  8586. return JSON.parse(data);
  8587. }
  8588. if (rvalidchars.test(data.replace(rvalidescape, '@')
  8589. .replace(rvalidtokens, ']')
  8590. .replace(rvalidbraces, ''))) {
  8591. return (new Function('return ' + data))();
  8592. }
  8593. };
  8594. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8595. },{}],53:[function(require,module,exports){
  8596. /**
  8597. * Compiles a querystring
  8598. * Returns string representation of the object
  8599. *
  8600. * @param {Object}
  8601. * @api private
  8602. */
  8603. exports.encode = function (obj) {
  8604. var str = '';
  8605. for (var i in obj) {
  8606. if (obj.hasOwnProperty(i)) {
  8607. if (str.length) str += '&';
  8608. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  8609. }
  8610. }
  8611. return str;
  8612. };
  8613. /**
  8614. * Parses a simple querystring into an object
  8615. *
  8616. * @param {String} qs
  8617. * @api private
  8618. */
  8619. exports.decode = function(qs){
  8620. var qry = {};
  8621. var pairs = qs.split('&');
  8622. for (var i = 0, l = pairs.length; i < l; i++) {
  8623. var pair = pairs[i].split('=');
  8624. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  8625. }
  8626. return qry;
  8627. };
  8628. },{}],54:[function(require,module,exports){
  8629. /**
  8630. * Parses an URI
  8631. *
  8632. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  8633. * @api private
  8634. */
  8635. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  8636. var parts = [
  8637. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  8638. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  8639. ];
  8640. module.exports = function parseuri(str) {
  8641. var m = re.exec(str || '')
  8642. , uri = {}
  8643. , i = 14;
  8644. while (i--) {
  8645. uri[parts[i]] = m[i] || '';
  8646. }
  8647. return uri;
  8648. };
  8649. },{}],55:[function(require,module,exports){
  8650. // shim for using process in browser
  8651. var process = module.exports = {};
  8652. // cached from whatever global is present so that test runners that stub it
  8653. // don't break things. But we need to wrap it in a try catch in case it is
  8654. // wrapped in strict mode code which doesn't define any globals. It's inside a
  8655. // function because try/catches deoptimize in certain engines.
  8656. var cachedSetTimeout;
  8657. var cachedClearTimeout;
  8658. function defaultSetTimout() {
  8659. throw new Error('setTimeout has not been defined');
  8660. }
  8661. function defaultClearTimeout () {
  8662. throw new Error('clearTimeout has not been defined');
  8663. }
  8664. (function () {
  8665. try {
  8666. if (typeof setTimeout === 'function') {
  8667. cachedSetTimeout = setTimeout;
  8668. } else {
  8669. cachedSetTimeout = defaultSetTimout;
  8670. }
  8671. } catch (e) {
  8672. cachedSetTimeout = defaultSetTimout;
  8673. }
  8674. try {
  8675. if (typeof clearTimeout === 'function') {
  8676. cachedClearTimeout = clearTimeout;
  8677. } else {
  8678. cachedClearTimeout = defaultClearTimeout;
  8679. }
  8680. } catch (e) {
  8681. cachedClearTimeout = defaultClearTimeout;
  8682. }
  8683. } ())
  8684. function runTimeout(fun) {
  8685. if (cachedSetTimeout === setTimeout) {
  8686. //normal enviroments in sane situations
  8687. return setTimeout(fun, 0);
  8688. }
  8689. // if setTimeout wasn't available but was latter defined
  8690. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  8691. cachedSetTimeout = setTimeout;
  8692. return setTimeout(fun, 0);
  8693. }
  8694. try {
  8695. // when when somebody has screwed with setTimeout but no I.E. maddness
  8696. return cachedSetTimeout(fun, 0);
  8697. } catch(e){
  8698. try {
  8699. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  8700. return cachedSetTimeout.call(null, fun, 0);
  8701. } catch(e){
  8702. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  8703. return cachedSetTimeout.call(this, fun, 0);
  8704. }
  8705. }
  8706. }
  8707. function runClearTimeout(marker) {
  8708. if (cachedClearTimeout === clearTimeout) {
  8709. //normal enviroments in sane situations
  8710. return clearTimeout(marker);
  8711. }
  8712. // if clearTimeout wasn't available but was latter defined
  8713. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  8714. cachedClearTimeout = clearTimeout;
  8715. return clearTimeout(marker);
  8716. }
  8717. try {
  8718. // when when somebody has screwed with setTimeout but no I.E. maddness
  8719. return cachedClearTimeout(marker);
  8720. } catch (e){
  8721. try {
  8722. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  8723. return cachedClearTimeout.call(null, marker);
  8724. } catch (e){
  8725. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  8726. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  8727. return cachedClearTimeout.call(this, marker);
  8728. }
  8729. }
  8730. }
  8731. var queue = [];
  8732. var draining = false;
  8733. var currentQueue;
  8734. var queueIndex = -1;
  8735. function cleanUpNextTick() {
  8736. if (!draining || !currentQueue) {
  8737. return;
  8738. }
  8739. draining = false;
  8740. if (currentQueue.length) {
  8741. queue = currentQueue.concat(queue);
  8742. } else {
  8743. queueIndex = -1;
  8744. }
  8745. if (queue.length) {
  8746. drainQueue();
  8747. }
  8748. }
  8749. function drainQueue() {
  8750. if (draining) {
  8751. return;
  8752. }
  8753. var timeout = runTimeout(cleanUpNextTick);
  8754. draining = true;
  8755. var len = queue.length;
  8756. while(len) {
  8757. currentQueue = queue;
  8758. queue = [];
  8759. while (++queueIndex < len) {
  8760. if (currentQueue) {
  8761. currentQueue[queueIndex].run();
  8762. }
  8763. }
  8764. queueIndex = -1;
  8765. len = queue.length;
  8766. }
  8767. currentQueue = null;
  8768. draining = false;
  8769. runClearTimeout(timeout);
  8770. }
  8771. process.nextTick = function (fun) {
  8772. var args = new Array(arguments.length - 1);
  8773. if (arguments.length > 1) {
  8774. for (var i = 1; i < arguments.length; i++) {
  8775. args[i - 1] = arguments[i];
  8776. }
  8777. }
  8778. queue.push(new Item(fun, args));
  8779. if (queue.length === 1 && !draining) {
  8780. runTimeout(drainQueue);
  8781. }
  8782. };
  8783. // v8 likes predictible objects
  8784. function Item(fun, array) {
  8785. this.fun = fun;
  8786. this.array = array;
  8787. }
  8788. Item.prototype.run = function () {
  8789. this.fun.apply(null, this.array);
  8790. };
  8791. process.title = 'browser';
  8792. process.browser = true;
  8793. process.env = {};
  8794. process.argv = [];
  8795. process.version = ''; // empty string to avoid regexp issues
  8796. process.versions = {};
  8797. function noop() {}
  8798. process.on = noop;
  8799. process.addListener = noop;
  8800. process.once = noop;
  8801. process.off = noop;
  8802. process.removeListener = noop;
  8803. process.removeAllListeners = noop;
  8804. process.emit = noop;
  8805. process.binding = function (name) {
  8806. throw new Error('process.binding is not supported');
  8807. };
  8808. process.cwd = function () { return '/' };
  8809. process.chdir = function (dir) {
  8810. throw new Error('process.chdir is not supported');
  8811. };
  8812. process.umask = function() { return 0; };
  8813. },{}],56:[function(require,module,exports){
  8814. var util = require('util');
  8815. var SJJ = require('sdp-jingle-json');
  8816. var WildEmitter = require('wildemitter');
  8817. var Peerconn = require('traceablepeerconnection');
  8818. var adapter = require('webrtc-adapter');
  8819. var cloneDeep = require('lodash.clonedeep');
  8820. function PeerConnection(config, constraints) {
  8821. var self = this;
  8822. var item;
  8823. WildEmitter.call(this);
  8824. config = config || {};
  8825. config.iceServers = config.iceServers || [];
  8826. var detectedBrowser = adapter.browserDetails.browser;
  8827. // make sure this only gets enabled in Google Chrome
  8828. // EXPERIMENTAL FLAG, might get removed without notice
  8829. this.enableChromeNativeSimulcast = false;
  8830. if (constraints && constraints.optional &&
  8831. detectedBrowser === 'chrome' &&
  8832. navigator.appVersion.match(/Chromium\//) === null) {
  8833. constraints.optional.forEach(function (constraint) {
  8834. if (constraint.enableChromeNativeSimulcast) {
  8835. self.enableChromeNativeSimulcast = true;
  8836. }
  8837. });
  8838. }
  8839. // EXPERIMENTAL FLAG, might get removed without notice
  8840. this.enableMultiStreamHacks = false;
  8841. if (constraints && constraints.optional &&
  8842. detectedBrowser === 'chrome') {
  8843. constraints.optional.forEach(function (constraint) {
  8844. if (constraint.enableMultiStreamHacks) {
  8845. self.enableMultiStreamHacks = true;
  8846. }
  8847. });
  8848. }
  8849. // EXPERIMENTAL FLAG, might get removed without notice
  8850. this.restrictBandwidth = 0;
  8851. if (constraints && constraints.optional) {
  8852. constraints.optional.forEach(function (constraint) {
  8853. if (constraint.andyetRestrictBandwidth) {
  8854. self.restrictBandwidth = constraint.andyetRestrictBandwidth;
  8855. }
  8856. });
  8857. }
  8858. // EXPERIMENTAL FLAG, might get removed without notice
  8859. // bundle up ice candidates, only works for jingle mode
  8860. // number > 0 is the delay to wait for additional candidates
  8861. // ~20ms seems good
  8862. this.batchIceCandidates = 0;
  8863. if (constraints && constraints.optional) {
  8864. constraints.optional.forEach(function (constraint) {
  8865. if (constraint.andyetBatchIce) {
  8866. self.batchIceCandidates = constraint.andyetBatchIce;
  8867. }
  8868. });
  8869. }
  8870. this.batchedIceCandidates = [];
  8871. // EXPERIMENTAL FLAG, might get removed without notice
  8872. // this attemps to strip out candidates with an already known foundation
  8873. // and type -- i.e. those which are gathered via the same TURN server
  8874. // but different transports (TURN udp, tcp and tls respectively)
  8875. if (constraints && constraints.optional && detectedBrowser === 'chrome') {
  8876. constraints.optional.forEach(function (constraint) {
  8877. if (constraint.andyetFasterICE) {
  8878. self.eliminateDuplicateCandidates = constraint.andyetFasterICE;
  8879. }
  8880. });
  8881. }
  8882. // EXPERIMENTAL FLAG, might get removed without notice
  8883. // when using a server such as the jitsi videobridge we don't need to signal
  8884. // our candidates
  8885. if (constraints && constraints.optional) {
  8886. constraints.optional.forEach(function (constraint) {
  8887. if (constraint.andyetDontSignalCandidates) {
  8888. self.dontSignalCandidates = constraint.andyetDontSignalCandidates;
  8889. }
  8890. });
  8891. }
  8892. // EXPERIMENTAL FLAG, might get removed without notice
  8893. this.assumeSetLocalSuccess = false;
  8894. if (constraints && constraints.optional) {
  8895. constraints.optional.forEach(function (constraint) {
  8896. if (constraint.andyetAssumeSetLocalSuccess) {
  8897. self.assumeSetLocalSuccess = constraint.andyetAssumeSetLocalSuccess;
  8898. }
  8899. });
  8900. }
  8901. // EXPERIMENTAL FLAG, might get removed without notice
  8902. // working around https://bugzilla.mozilla.org/show_bug.cgi?id=1087551
  8903. // pass in a timeout for this
  8904. if (detectedBrowser === 'firefox') {
  8905. if (constraints && constraints.optional) {
  8906. this.wtFirefox = 0;
  8907. constraints.optional.forEach(function (constraint) {
  8908. if (constraint.andyetFirefoxMakesMeSad) {
  8909. self.wtFirefox = constraint.andyetFirefoxMakesMeSad;
  8910. if (self.wtFirefox > 0) {
  8911. self.firefoxcandidatebuffer = [];
  8912. }
  8913. }
  8914. });
  8915. }
  8916. }
  8917. this.pc = new Peerconn(config, constraints);
  8918. this.getLocalStreams = this.pc.getLocalStreams.bind(this.pc);
  8919. this.getRemoteStreams = this.pc.getRemoteStreams.bind(this.pc);
  8920. this.addStream = this.pc.addStream.bind(this.pc);
  8921. this.removeStream = this.pc.removeStream.bind(this.pc);
  8922. // proxy events
  8923. this.pc.on('*', function () {
  8924. self.emit.apply(self, arguments);
  8925. });
  8926. // proxy some events directly
  8927. this.pc.onremovestream = this.emit.bind(this, 'removeStream');
  8928. this.pc.onaddstream = this.emit.bind(this, 'addStream');
  8929. this.pc.onnegotiationneeded = this.emit.bind(this, 'negotiationNeeded');
  8930. this.pc.oniceconnectionstatechange = this.emit.bind(this, 'iceConnectionStateChange');
  8931. this.pc.onsignalingstatechange = this.emit.bind(this, 'signalingStateChange');
  8932. // handle ice candidate and data channel events
  8933. this.pc.onicecandidate = this._onIce.bind(this);
  8934. this.pc.ondatachannel = this._onDataChannel.bind(this);
  8935. this.localDescription = {
  8936. contents: []
  8937. };
  8938. this.remoteDescription = {
  8939. contents: []
  8940. };
  8941. this.config = {
  8942. debug: false,
  8943. sid: '',
  8944. isInitiator: true,
  8945. sdpSessionID: Date.now(),
  8946. useJingle: false
  8947. };
  8948. this.iceCredentials = {
  8949. local: {},
  8950. remote: {}
  8951. };
  8952. // apply our config
  8953. for (item in config) {
  8954. this.config[item] = config[item];
  8955. }
  8956. if (this.config.debug) {
  8957. this.on('*', function () {
  8958. var logger = config.logger || console;
  8959. logger.log('PeerConnection event:', arguments);
  8960. });
  8961. }
  8962. this.hadLocalStunCandidate = false;
  8963. this.hadRemoteStunCandidate = false;
  8964. this.hadLocalRelayCandidate = false;
  8965. this.hadRemoteRelayCandidate = false;
  8966. this.hadLocalIPv6Candidate = false;
  8967. this.hadRemoteIPv6Candidate = false;
  8968. // keeping references for all our data channels
  8969. // so they dont get garbage collected
  8970. // can be removed once the following bugs have been fixed
  8971. // https://crbug.com/405545
  8972. // https://bugzilla.mozilla.org/show_bug.cgi?id=964092
  8973. // to be filed for opera
  8974. this._remoteDataChannels = [];
  8975. this._localDataChannels = [];
  8976. this._candidateBuffer = [];
  8977. }
  8978. util.inherits(PeerConnection, WildEmitter);
  8979. Object.defineProperty(PeerConnection.prototype, 'signalingState', {
  8980. get: function () {
  8981. return this.pc.signalingState;
  8982. }
  8983. });
  8984. Object.defineProperty(PeerConnection.prototype, 'iceConnectionState', {
  8985. get: function () {
  8986. return this.pc.iceConnectionState;
  8987. }
  8988. });
  8989. PeerConnection.prototype._role = function () {
  8990. return this.isInitiator ? 'initiator' : 'responder';
  8991. };
  8992. // Add a stream to the peer connection object
  8993. PeerConnection.prototype.addStream = function (stream) {
  8994. this.localStream = stream;
  8995. this.pc.addStream(stream);
  8996. };
  8997. // helper function to check if a remote candidate is a stun/relay
  8998. // candidate or an ipv6 candidate
  8999. PeerConnection.prototype._checkLocalCandidate = function (candidate) {
  9000. var cand = SJJ.toCandidateJSON(candidate);
  9001. if (cand.type == 'srflx') {
  9002. this.hadLocalStunCandidate = true;
  9003. } else if (cand.type == 'relay') {
  9004. this.hadLocalRelayCandidate = true;
  9005. }
  9006. if (cand.ip.indexOf(':') != -1) {
  9007. this.hadLocalIPv6Candidate = true;
  9008. }
  9009. };
  9010. // helper function to check if a remote candidate is a stun/relay
  9011. // candidate or an ipv6 candidate
  9012. PeerConnection.prototype._checkRemoteCandidate = function (candidate) {
  9013. var cand = SJJ.toCandidateJSON(candidate);
  9014. if (cand.type == 'srflx') {
  9015. this.hadRemoteStunCandidate = true;
  9016. } else if (cand.type == 'relay') {
  9017. this.hadRemoteRelayCandidate = true;
  9018. }
  9019. if (cand.ip.indexOf(':') != -1) {
  9020. this.hadRemoteIPv6Candidate = true;
  9021. }
  9022. };
  9023. // Init and add ice candidate object with correct constructor
  9024. PeerConnection.prototype.processIce = function (update, cb) {
  9025. cb = cb || function () {};
  9026. var self = this;
  9027. // ignore any added ice candidates to avoid errors. why does the
  9028. // spec not do this?
  9029. if (this.pc.signalingState === 'closed') return cb();
  9030. if (update.contents || (update.jingle && update.jingle.contents)) {
  9031. var contentNames = this.remoteDescription.contents.map(function (c) { return c.name; });
  9032. var contents = update.contents || update.jingle.contents;
  9033. contents.forEach(function (content) {
  9034. var transport = content.transport || {};
  9035. var candidates = transport.candidates || [];
  9036. var mline = contentNames.indexOf(content.name);
  9037. var mid = content.name;
  9038. var remoteContent = self.remoteDescription.contents.find(function (c) {
  9039. return c.name === content.name;
  9040. });
  9041. // process candidates as a callback, in case we need to
  9042. // update ufrag and pwd with offer/answer
  9043. var processCandidates = function () {
  9044. candidates.forEach(
  9045. function (candidate) {
  9046. var iceCandidate = SJJ.toCandidateSDP(candidate) + '\r\n';
  9047. self.pc.addIceCandidate(
  9048. new RTCIceCandidate({
  9049. candidate: iceCandidate,
  9050. sdpMLineIndex: mline,
  9051. sdpMid: mid
  9052. }), function () {
  9053. // well, this success callback is pretty meaningless
  9054. },
  9055. function (err) {
  9056. self.emit('error', err);
  9057. }
  9058. );
  9059. self._checkRemoteCandidate(iceCandidate);
  9060. });
  9061. cb();
  9062. };
  9063. if (self.iceCredentials.remote[content.name] && transport.ufrag &&
  9064. self.iceCredentials.remote[content.name].ufrag !== transport.ufrag) {
  9065. if (remoteContent) {
  9066. remoteContent.transport.ufrag = transport.ufrag;
  9067. remoteContent.transport.pwd = transport.pwd;
  9068. var offer = {
  9069. type: 'offer',
  9070. jingle: self.remoteDescription
  9071. };
  9072. offer.sdp = SJJ.toSessionSDP(offer.jingle, {
  9073. sid: self.config.sdpSessionID,
  9074. role: self._role(),
  9075. direction: 'incoming'
  9076. });
  9077. self.pc.setRemoteDescription(new RTCSessionDescription(offer),
  9078. function () {
  9079. processCandidates();
  9080. },
  9081. function (err) {
  9082. self.emit('error', err);
  9083. }
  9084. );
  9085. } else {
  9086. self.emit('error', 'ice restart failed to find matching content');
  9087. }
  9088. } else {
  9089. processCandidates();
  9090. }
  9091. });
  9092. } else {
  9093. // working around https://code.google.com/p/webrtc/issues/detail?id=3669
  9094. if (update.candidate && update.candidate.candidate.indexOf('a=') !== 0) {
  9095. update.candidate.candidate = 'a=' + update.candidate.candidate;
  9096. }
  9097. if (this.wtFirefox && this.firefoxcandidatebuffer !== null) {
  9098. // we cant add this yet due to https://bugzilla.mozilla.org/show_bug.cgi?id=1087551
  9099. if (this.pc.localDescription && this.pc.localDescription.type === 'offer') {
  9100. this.firefoxcandidatebuffer.push(update.candidate);
  9101. return cb();
  9102. }
  9103. }
  9104. self.pc.addIceCandidate(
  9105. new RTCIceCandidate(update.candidate),
  9106. function () { },
  9107. function (err) {
  9108. self.emit('error', err);
  9109. }
  9110. );
  9111. self._checkRemoteCandidate(update.candidate.candidate);
  9112. cb();
  9113. }
  9114. };
  9115. // Generate and emit an offer with the given constraints
  9116. PeerConnection.prototype.offer = function (constraints, cb) {
  9117. var self = this;
  9118. var hasConstraints = arguments.length === 2;
  9119. var mediaConstraints = hasConstraints && constraints ? constraints : {
  9120. offerToReceiveAudio: 1,
  9121. offerToReceiveVideo: 1
  9122. };
  9123. cb = hasConstraints ? cb : constraints;
  9124. cb = cb || function () {};
  9125. if (this.pc.signalingState === 'closed') return cb('Already closed');
  9126. // Actually generate the offer
  9127. this.pc.createOffer(
  9128. function (offer) {
  9129. // does not work for jingle, but jingle.js doesn't need
  9130. // this hack...
  9131. var expandedOffer = {
  9132. type: 'offer',
  9133. sdp: offer.sdp
  9134. };
  9135. if (self.assumeSetLocalSuccess) {
  9136. self.emit('offer', expandedOffer);
  9137. cb(null, expandedOffer);
  9138. }
  9139. self._candidateBuffer = [];
  9140. self.pc.setLocalDescription(offer,
  9141. function () {
  9142. var jingle;
  9143. if (self.config.useJingle) {
  9144. jingle = SJJ.toSessionJSON(offer.sdp, {
  9145. role: self._role(),
  9146. direction: 'outgoing'
  9147. });
  9148. jingle.sid = self.config.sid;
  9149. self.localDescription = jingle;
  9150. // Save ICE credentials
  9151. jingle.contents.forEach(function (content) {
  9152. var transport = content.transport || {};
  9153. if (transport.ufrag) {
  9154. self.iceCredentials.local[content.name] = {
  9155. ufrag: transport.ufrag,
  9156. pwd: transport.pwd
  9157. };
  9158. }
  9159. });
  9160. expandedOffer.jingle = jingle;
  9161. }
  9162. expandedOffer.sdp.split('\r\n').forEach(function (line) {
  9163. if (line.indexOf('a=candidate:') === 0) {
  9164. self._checkLocalCandidate(line);
  9165. }
  9166. });
  9167. if (!self.assumeSetLocalSuccess) {
  9168. self.emit('offer', expandedOffer);
  9169. cb(null, expandedOffer);
  9170. }
  9171. },
  9172. function (err) {
  9173. self.emit('error', err);
  9174. cb(err);
  9175. }
  9176. );
  9177. },
  9178. function (err) {
  9179. self.emit('error', err);
  9180. cb(err);
  9181. },
  9182. mediaConstraints
  9183. );
  9184. };
  9185. // Process an incoming offer so that ICE may proceed before deciding
  9186. // to answer the request.
  9187. PeerConnection.prototype.handleOffer = function (offer, cb) {
  9188. cb = cb || function () {};
  9189. var self = this;
  9190. offer.type = 'offer';
  9191. if (offer.jingle) {
  9192. if (this.enableChromeNativeSimulcast) {
  9193. offer.jingle.contents.forEach(function (content) {
  9194. if (content.name === 'video') {
  9195. content.application.googConferenceFlag = true;
  9196. }
  9197. });
  9198. }
  9199. if (this.enableMultiStreamHacks) {
  9200. // add a mixed video stream as first stream
  9201. offer.jingle.contents.forEach(function (content) {
  9202. if (content.name === 'video') {
  9203. var sources = content.application.sources || [];
  9204. if (sources.length === 0 || sources[0].ssrc !== "3735928559") {
  9205. sources.unshift({
  9206. ssrc: "3735928559", // 0xdeadbeef
  9207. parameters: [
  9208. {
  9209. key: "cname",
  9210. value: "deadbeef"
  9211. },
  9212. {
  9213. key: "msid",
  9214. value: "mixyourfecintothis please"
  9215. }
  9216. ]
  9217. });
  9218. content.application.sources = sources;
  9219. }
  9220. }
  9221. });
  9222. }
  9223. if (self.restrictBandwidth > 0) {
  9224. if (offer.jingle.contents.length >= 2 && offer.jingle.contents[1].name === 'video') {
  9225. var content = offer.jingle.contents[1];
  9226. var hasBw = content.application && content.application.bandwidth && content.application.bandwidth.bandwidth;
  9227. if (!hasBw) {
  9228. offer.jingle.contents[1].application.bandwidth = { type: 'AS', bandwidth: self.restrictBandwidth.toString() };
  9229. offer.sdp = SJJ.toSessionSDP(offer.jingle, {
  9230. sid: self.config.sdpSessionID,
  9231. role: self._role(),
  9232. direction: 'outgoing'
  9233. });
  9234. }
  9235. }
  9236. }
  9237. // Save ICE credentials
  9238. offer.jingle.contents.forEach(function (content) {
  9239. var transport = content.transport || {};
  9240. if (transport.ufrag) {
  9241. self.iceCredentials.remote[content.name] = {
  9242. ufrag: transport.ufrag,
  9243. pwd: transport.pwd
  9244. };
  9245. }
  9246. });
  9247. offer.sdp = SJJ.toSessionSDP(offer.jingle, {
  9248. sid: self.config.sdpSessionID,
  9249. role: self._role(),
  9250. direction: 'incoming'
  9251. });
  9252. self.remoteDescription = offer.jingle;
  9253. }
  9254. offer.sdp.split('\r\n').forEach(function (line) {
  9255. if (line.indexOf('a=candidate:') === 0) {
  9256. self._checkRemoteCandidate(line);
  9257. }
  9258. });
  9259. self.pc.setRemoteDescription(new RTCSessionDescription(offer),
  9260. function () {
  9261. cb();
  9262. },
  9263. cb
  9264. );
  9265. };
  9266. // Answer an offer with audio only
  9267. PeerConnection.prototype.answerAudioOnly = function (cb) {
  9268. var mediaConstraints = {
  9269. mandatory: {
  9270. OfferToReceiveAudio: true,
  9271. OfferToReceiveVideo: false
  9272. }
  9273. };
  9274. this._answer(mediaConstraints, cb);
  9275. };
  9276. // Answer an offer without offering to recieve
  9277. PeerConnection.prototype.answerBroadcastOnly = function (cb) {
  9278. var mediaConstraints = {
  9279. mandatory: {
  9280. OfferToReceiveAudio: false,
  9281. OfferToReceiveVideo: false
  9282. }
  9283. };
  9284. this._answer(mediaConstraints, cb);
  9285. };
  9286. // Answer an offer with given constraints default is audio/video
  9287. PeerConnection.prototype.answer = function (constraints, cb) {
  9288. var hasConstraints = arguments.length === 2;
  9289. var callback = hasConstraints ? cb : constraints;
  9290. var mediaConstraints = hasConstraints && constraints ? constraints : {
  9291. mandatory: {
  9292. OfferToReceiveAudio: true,
  9293. OfferToReceiveVideo: true
  9294. }
  9295. };
  9296. this._answer(mediaConstraints, callback);
  9297. };
  9298. // Process an answer
  9299. PeerConnection.prototype.handleAnswer = function (answer, cb) {
  9300. cb = cb || function () {};
  9301. var self = this;
  9302. if (answer.jingle) {
  9303. answer.sdp = SJJ.toSessionSDP(answer.jingle, {
  9304. sid: self.config.sdpSessionID,
  9305. role: self._role(),
  9306. direction: 'incoming'
  9307. });
  9308. self.remoteDescription = answer.jingle;
  9309. // Save ICE credentials
  9310. answer.jingle.contents.forEach(function (content) {
  9311. var transport = content.transport || {};
  9312. if (transport.ufrag) {
  9313. self.iceCredentials.remote[content.name] = {
  9314. ufrag: transport.ufrag,
  9315. pwd: transport.pwd
  9316. };
  9317. }
  9318. });
  9319. }
  9320. answer.sdp.split('\r\n').forEach(function (line) {
  9321. if (line.indexOf('a=candidate:') === 0) {
  9322. self._checkRemoteCandidate(line);
  9323. }
  9324. });
  9325. self.pc.setRemoteDescription(
  9326. new RTCSessionDescription(answer),
  9327. function () {
  9328. if (self.wtFirefox) {
  9329. window.setTimeout(function () {
  9330. self.firefoxcandidatebuffer.forEach(function (candidate) {
  9331. // add candidates later
  9332. self.pc.addIceCandidate(
  9333. new RTCIceCandidate(candidate),
  9334. function () { },
  9335. function (err) {
  9336. self.emit('error', err);
  9337. }
  9338. );
  9339. self._checkRemoteCandidate(candidate.candidate);
  9340. });
  9341. self.firefoxcandidatebuffer = null;
  9342. }, self.wtFirefox);
  9343. }
  9344. cb(null);
  9345. },
  9346. cb
  9347. );
  9348. };
  9349. // Close the peer connection
  9350. PeerConnection.prototype.close = function () {
  9351. this.pc.close();
  9352. this._localDataChannels = [];
  9353. this._remoteDataChannels = [];
  9354. this.emit('close');
  9355. };
  9356. // Internal code sharing for various types of answer methods
  9357. PeerConnection.prototype._answer = function (constraints, cb) {
  9358. cb = cb || function () {};
  9359. var self = this;
  9360. if (!this.pc.remoteDescription) {
  9361. // the old API is used, call handleOffer
  9362. throw new Error('remoteDescription not set');
  9363. }
  9364. if (this.pc.signalingState === 'closed') return cb('Already closed');
  9365. self.pc.createAnswer(
  9366. function (answer) {
  9367. var sim = [];
  9368. if (self.enableChromeNativeSimulcast) {
  9369. // native simulcast part 1: add another SSRC
  9370. answer.jingle = SJJ.toSessionJSON(answer.sdp, {
  9371. role: self._role(),
  9372. direction: 'outgoing'
  9373. });
  9374. if (answer.jingle.contents.length >= 2 && answer.jingle.contents[1].name === 'video') {
  9375. var groups = answer.jingle.contents[1].application.sourceGroups || [];
  9376. var hasSim = false;
  9377. groups.forEach(function (group) {
  9378. if (group.semantics == 'SIM') hasSim = true;
  9379. });
  9380. if (!hasSim &&
  9381. answer.jingle.contents[1].application.sources.length) {
  9382. var newssrc = JSON.parse(JSON.stringify(answer.jingle.contents[1].application.sources[0]));
  9383. newssrc.ssrc = '' + Math.floor(Math.random() * 0xffffffff); // FIXME: look for conflicts
  9384. answer.jingle.contents[1].application.sources.push(newssrc);
  9385. sim.push(answer.jingle.contents[1].application.sources[0].ssrc);
  9386. sim.push(newssrc.ssrc);
  9387. groups.push({
  9388. semantics: 'SIM',
  9389. sources: sim
  9390. });
  9391. // also create an RTX one for the SIM one
  9392. var rtxssrc = JSON.parse(JSON.stringify(newssrc));
  9393. rtxssrc.ssrc = '' + Math.floor(Math.random() * 0xffffffff); // FIXME: look for conflicts
  9394. answer.jingle.contents[1].application.sources.push(rtxssrc);
  9395. groups.push({
  9396. semantics: 'FID',
  9397. sources: [newssrc.ssrc, rtxssrc.ssrc]
  9398. });
  9399. answer.jingle.contents[1].application.sourceGroups = groups;
  9400. answer.sdp = SJJ.toSessionSDP(answer.jingle, {
  9401. sid: self.config.sdpSessionID,
  9402. role: self._role(),
  9403. direction: 'outgoing'
  9404. });
  9405. }
  9406. }
  9407. }
  9408. var expandedAnswer = {
  9409. type: 'answer',
  9410. sdp: answer.sdp
  9411. };
  9412. if (self.assumeSetLocalSuccess) {
  9413. // not safe to do when doing simulcast mangling
  9414. var copy = cloneDeep(expandedAnswer);
  9415. self.emit('answer', copy);
  9416. cb(null, copy);
  9417. }
  9418. self._candidateBuffer = [];
  9419. self.pc.setLocalDescription(answer,
  9420. function () {
  9421. if (self.config.useJingle) {
  9422. var jingle = SJJ.toSessionJSON(answer.sdp, {
  9423. role: self._role(),
  9424. direction: 'outgoing'
  9425. });
  9426. jingle.sid = self.config.sid;
  9427. self.localDescription = jingle;
  9428. expandedAnswer.jingle = jingle;
  9429. }
  9430. if (self.enableChromeNativeSimulcast) {
  9431. // native simulcast part 2:
  9432. // signal multiple tracks to the receiver
  9433. // for anything in the SIM group
  9434. if (!expandedAnswer.jingle) {
  9435. expandedAnswer.jingle = SJJ.toSessionJSON(answer.sdp, {
  9436. role: self._role(),
  9437. direction: 'outgoing'
  9438. });
  9439. }
  9440. expandedAnswer.jingle.contents[1].application.sources.forEach(function (source, idx) {
  9441. // the floor idx/2 is a hack that relies on a particular order
  9442. // of groups, alternating between sim and rtx
  9443. source.parameters = source.parameters.map(function (parameter) {
  9444. if (parameter.key === 'msid') {
  9445. parameter.value += '-' + Math.floor(idx / 2);
  9446. }
  9447. return parameter;
  9448. });
  9449. });
  9450. expandedAnswer.sdp = SJJ.toSessionSDP(expandedAnswer.jingle, {
  9451. sid: self.sdpSessionID,
  9452. role: self._role(),
  9453. direction: 'outgoing'
  9454. });
  9455. }
  9456. expandedAnswer.sdp.split('\r\n').forEach(function (line) {
  9457. if (line.indexOf('a=candidate:') === 0) {
  9458. self._checkLocalCandidate(line);
  9459. }
  9460. });
  9461. if (!self.assumeSetLocalSuccess) {
  9462. var copy = cloneDeep(expandedAnswer);
  9463. self.emit('answer', copy);
  9464. cb(null, copy);
  9465. }
  9466. },
  9467. function (err) {
  9468. self.emit('error', err);
  9469. cb(err);
  9470. }
  9471. );
  9472. },
  9473. function (err) {
  9474. self.emit('error', err);
  9475. cb(err);
  9476. },
  9477. constraints
  9478. );
  9479. };
  9480. // Internal method for emitting ice candidates on our peer object
  9481. PeerConnection.prototype._onIce = function (event) {
  9482. var self = this;
  9483. if (event.candidate) {
  9484. if (this.dontSignalCandidates) return;
  9485. var ice = event.candidate;
  9486. var expandedCandidate = {
  9487. candidate: {
  9488. candidate: ice.candidate,
  9489. sdpMid: ice.sdpMid,
  9490. sdpMLineIndex: ice.sdpMLineIndex
  9491. }
  9492. };
  9493. this._checkLocalCandidate(ice.candidate);
  9494. var cand = SJJ.toCandidateJSON(ice.candidate);
  9495. var already;
  9496. var idx;
  9497. if (this.eliminateDuplicateCandidates && cand.type === 'relay') {
  9498. // drop candidates with same foundation, component
  9499. // take local type pref into account so we don't ignore udp
  9500. // ones when we know about a TCP one. unlikely but...
  9501. already = this._candidateBuffer.filter(
  9502. function (c) {
  9503. return c.type === 'relay';
  9504. }).map(function (c) {
  9505. return c.foundation + ':' + c.component;
  9506. }
  9507. );
  9508. idx = already.indexOf(cand.foundation + ':' + cand.component);
  9509. // remember: local type pref of udp is 0, tcp 1, tls 2
  9510. if (idx > -1 && ((cand.priority >> 24) >= (already[idx].priority >> 24))) {
  9511. // drop it, same foundation with higher (worse) type pref
  9512. return;
  9513. }
  9514. }
  9515. if (this.config.bundlePolicy === 'max-bundle') {
  9516. // drop candidates which are duplicate for audio/video/data
  9517. // duplicate means same host/port but different sdpMid
  9518. already = this._candidateBuffer.filter(
  9519. function (c) {
  9520. return cand.type === c.type;
  9521. }).map(function (cand) {
  9522. return cand.address + ':' + cand.port;
  9523. }
  9524. );
  9525. idx = already.indexOf(cand.address + ':' + cand.port);
  9526. if (idx > -1) return;
  9527. }
  9528. // also drop rtcp candidates since we know the peer supports RTCP-MUX
  9529. // this is a workaround until browsers implement this natively
  9530. if (this.config.rtcpMuxPolicy === 'require' && cand.component === '2') {
  9531. return;
  9532. }
  9533. this._candidateBuffer.push(cand);
  9534. if (self.config.useJingle) {
  9535. if (!ice.sdpMid) { // firefox doesn't set this
  9536. if (self.pc.remoteDescription && self.pc.remoteDescription.type === 'offer') {
  9537. // preserve name from remote
  9538. ice.sdpMid = self.remoteDescription.contents[ice.sdpMLineIndex].name;
  9539. } else {
  9540. ice.sdpMid = self.localDescription.contents[ice.sdpMLineIndex].name;
  9541. }
  9542. }
  9543. if (!self.iceCredentials.local[ice.sdpMid]) {
  9544. var jingle = SJJ.toSessionJSON(self.pc.localDescription.sdp, {
  9545. role: self._role(),
  9546. direction: 'outgoing'
  9547. });
  9548. jingle.contents.forEach(function (content) {
  9549. var transport = content.transport || {};
  9550. if (transport.ufrag) {
  9551. self.iceCredentials.local[content.name] = {
  9552. ufrag: transport.ufrag,
  9553. pwd: transport.pwd
  9554. };
  9555. }
  9556. });
  9557. }
  9558. expandedCandidate.jingle = {
  9559. contents: [{
  9560. name: ice.sdpMid,
  9561. creator: self._role(),
  9562. transport: {
  9563. transportType: 'iceUdp',
  9564. ufrag: self.iceCredentials.local[ice.sdpMid].ufrag,
  9565. pwd: self.iceCredentials.local[ice.sdpMid].pwd,
  9566. candidates: [
  9567. cand
  9568. ]
  9569. }
  9570. }]
  9571. };
  9572. if (self.batchIceCandidates > 0) {
  9573. if (self.batchedIceCandidates.length === 0) {
  9574. window.setTimeout(function () {
  9575. var contents = {};
  9576. self.batchedIceCandidates.forEach(function (content) {
  9577. content = content.contents[0];
  9578. if (!contents[content.name]) contents[content.name] = content;
  9579. contents[content.name].transport.candidates.push(content.transport.candidates[0]);
  9580. });
  9581. var newCand = {
  9582. jingle: {
  9583. contents: []
  9584. }
  9585. };
  9586. Object.keys(contents).forEach(function (name) {
  9587. newCand.jingle.contents.push(contents[name]);
  9588. });
  9589. self.batchedIceCandidates = [];
  9590. self.emit('ice', newCand);
  9591. }, self.batchIceCandidates);
  9592. }
  9593. self.batchedIceCandidates.push(expandedCandidate.jingle);
  9594. return;
  9595. }
  9596. }
  9597. this.emit('ice', expandedCandidate);
  9598. } else {
  9599. this.emit('endOfCandidates');
  9600. }
  9601. };
  9602. // Internal method for processing a new data channel being added by the
  9603. // other peer.
  9604. PeerConnection.prototype._onDataChannel = function (event) {
  9605. // make sure we keep a reference so this doesn't get garbage collected
  9606. var channel = event.channel;
  9607. this._remoteDataChannels.push(channel);
  9608. this.emit('addChannel', channel);
  9609. };
  9610. // Create a data channel spec reference:
  9611. // http://dev.w3.org/2011/webrtc/editor/webrtc.html#idl-def-RTCDataChannelInit
  9612. PeerConnection.prototype.createDataChannel = function (name, opts) {
  9613. var channel = this.pc.createDataChannel(name, opts);
  9614. // make sure we keep a reference so this doesn't get garbage collected
  9615. this._localDataChannels.push(channel);
  9616. return channel;
  9617. };
  9618. PeerConnection.prototype.getStats = function (cb) {
  9619. this.pc.getStats(null,
  9620. function (res) {
  9621. cb(null, res);
  9622. },
  9623. function (err) {
  9624. cb(err);
  9625. }
  9626. );
  9627. };
  9628. module.exports = PeerConnection;
  9629. },{"lodash.clonedeep":47,"sdp-jingle-json":57,"traceablepeerconnection":76,"util":89,"webrtc-adapter":90,"wildemitter":100}],57:[function(require,module,exports){
  9630. var toSDP = require('./lib/tosdp');
  9631. var toJSON = require('./lib/tojson');
  9632. // Converstion from JSON to SDP
  9633. exports.toIncomingSDPOffer = function (session) {
  9634. return toSDP.toSessionSDP(session, {
  9635. role: 'responder',
  9636. direction: 'incoming'
  9637. });
  9638. };
  9639. exports.toOutgoingSDPOffer = function (session) {
  9640. return toSDP.toSessionSDP(session, {
  9641. role: 'initiator',
  9642. direction: 'outgoing'
  9643. });
  9644. };
  9645. exports.toIncomingSDPAnswer = function (session) {
  9646. return toSDP.toSessionSDP(session, {
  9647. role: 'initiator',
  9648. direction: 'incoming'
  9649. });
  9650. };
  9651. exports.toOutgoingSDPAnswer = function (session) {
  9652. return toSDP.toSessionSDP(session, {
  9653. role: 'responder',
  9654. direction: 'outgoing'
  9655. });
  9656. };
  9657. exports.toIncomingMediaSDPOffer = function (media) {
  9658. return toSDP.toMediaSDP(media, {
  9659. role: 'responder',
  9660. direction: 'incoming'
  9661. });
  9662. };
  9663. exports.toOutgoingMediaSDPOffer = function (media) {
  9664. return toSDP.toMediaSDP(media, {
  9665. role: 'initiator',
  9666. direction: 'outgoing'
  9667. });
  9668. };
  9669. exports.toIncomingMediaSDPAnswer = function (media) {
  9670. return toSDP.toMediaSDP(media, {
  9671. role: 'initiator',
  9672. direction: 'incoming'
  9673. });
  9674. };
  9675. exports.toOutgoingMediaSDPAnswer = function (media) {
  9676. return toSDP.toMediaSDP(media, {
  9677. role: 'responder',
  9678. direction: 'outgoing'
  9679. });
  9680. };
  9681. exports.toCandidateSDP = toSDP.toCandidateSDP;
  9682. exports.toMediaSDP = toSDP.toMediaSDP;
  9683. exports.toSessionSDP = toSDP.toSessionSDP;
  9684. // Conversion from SDP to JSON
  9685. exports.toIncomingJSONOffer = function (sdp, creators) {
  9686. return toJSON.toSessionJSON(sdp, {
  9687. role: 'responder',
  9688. direction: 'incoming',
  9689. creators: creators
  9690. });
  9691. };
  9692. exports.toOutgoingJSONOffer = function (sdp, creators) {
  9693. return toJSON.toSessionJSON(sdp, {
  9694. role: 'initiator',
  9695. direction: 'outgoing',
  9696. creators: creators
  9697. });
  9698. };
  9699. exports.toIncomingJSONAnswer = function (sdp, creators) {
  9700. return toJSON.toSessionJSON(sdp, {
  9701. role: 'initiator',
  9702. direction: 'incoming',
  9703. creators: creators
  9704. });
  9705. };
  9706. exports.toOutgoingJSONAnswer = function (sdp, creators) {
  9707. return toJSON.toSessionJSON(sdp, {
  9708. role: 'responder',
  9709. direction: 'outgoing',
  9710. creators: creators
  9711. });
  9712. };
  9713. exports.toIncomingMediaJSONOffer = function (sdp, creator) {
  9714. return toJSON.toMediaJSON(sdp, {
  9715. role: 'responder',
  9716. direction: 'incoming',
  9717. creator: creator
  9718. });
  9719. };
  9720. exports.toOutgoingMediaJSONOffer = function (sdp, creator) {
  9721. return toJSON.toMediaJSON(sdp, {
  9722. role: 'initiator',
  9723. direction: 'outgoing',
  9724. creator: creator
  9725. });
  9726. };
  9727. exports.toIncomingMediaJSONAnswer = function (sdp, creator) {
  9728. return toJSON.toMediaJSON(sdp, {
  9729. role: 'initiator',
  9730. direction: 'incoming',
  9731. creator: creator
  9732. });
  9733. };
  9734. exports.toOutgoingMediaJSONAnswer = function (sdp, creator) {
  9735. return toJSON.toMediaJSON(sdp, {
  9736. role: 'responder',
  9737. direction: 'outgoing',
  9738. creator: creator
  9739. });
  9740. };
  9741. exports.toCandidateJSON = toJSON.toCandidateJSON;
  9742. exports.toMediaJSON = toJSON.toMediaJSON;
  9743. exports.toSessionJSON = toJSON.toSessionJSON;
  9744. },{"./lib/tojson":60,"./lib/tosdp":61}],58:[function(require,module,exports){
  9745. exports.lines = function (sdp) {
  9746. return sdp.split('\r\n').filter(function (line) {
  9747. return line.length > 0;
  9748. });
  9749. };
  9750. exports.findLine = function (prefix, mediaLines, sessionLines) {
  9751. var prefixLength = prefix.length;
  9752. for (var i = 0; i < mediaLines.length; i++) {
  9753. if (mediaLines[i].substr(0, prefixLength) === prefix) {
  9754. return mediaLines[i];
  9755. }
  9756. }
  9757. // Continue searching in parent session section
  9758. if (!sessionLines) {
  9759. return false;
  9760. }
  9761. for (var j = 0; j < sessionLines.length; j++) {
  9762. if (sessionLines[j].substr(0, prefixLength) === prefix) {
  9763. return sessionLines[j];
  9764. }
  9765. }
  9766. return false;
  9767. };
  9768. exports.findLines = function (prefix, mediaLines, sessionLines) {
  9769. var results = [];
  9770. var prefixLength = prefix.length;
  9771. for (var i = 0; i < mediaLines.length; i++) {
  9772. if (mediaLines[i].substr(0, prefixLength) === prefix) {
  9773. results.push(mediaLines[i]);
  9774. }
  9775. }
  9776. if (results.length || !sessionLines) {
  9777. return results;
  9778. }
  9779. for (var j = 0; j < sessionLines.length; j++) {
  9780. if (sessionLines[j].substr(0, prefixLength) === prefix) {
  9781. results.push(sessionLines[j]);
  9782. }
  9783. }
  9784. return results;
  9785. };
  9786. exports.mline = function (line) {
  9787. var parts = line.substr(2).split(' ');
  9788. var parsed = {
  9789. media: parts[0],
  9790. port: parts[1],
  9791. proto: parts[2],
  9792. formats: []
  9793. };
  9794. for (var i = 3; i < parts.length; i++) {
  9795. if (parts[i]) {
  9796. parsed.formats.push(parts[i]);
  9797. }
  9798. }
  9799. return parsed;
  9800. };
  9801. exports.rtpmap = function (line) {
  9802. var parts = line.substr(9).split(' ');
  9803. var parsed = {
  9804. id: parts.shift()
  9805. };
  9806. parts = parts[0].split('/');
  9807. parsed.name = parts[0];
  9808. parsed.clockrate = parts[1];
  9809. parsed.channels = parts.length == 3 ? parts[2] : '1';
  9810. return parsed;
  9811. };
  9812. exports.sctpmap = function (line) {
  9813. // based on -05 draft
  9814. var parts = line.substr(10).split(' ');
  9815. var parsed = {
  9816. number: parts.shift(),
  9817. protocol: parts.shift(),
  9818. streams: parts.shift()
  9819. };
  9820. return parsed;
  9821. };
  9822. exports.fmtp = function (line) {
  9823. var kv, key, value;
  9824. var parts = line.substr(line.indexOf(' ') + 1).split(';');
  9825. var parsed = [];
  9826. for (var i = 0; i < parts.length; i++) {
  9827. kv = parts[i].split('=');
  9828. key = kv[0].trim();
  9829. value = kv[1];
  9830. if (key && value) {
  9831. parsed.push({key: key, value: value});
  9832. } else if (key) {
  9833. parsed.push({key: '', value: key});
  9834. }
  9835. }
  9836. return parsed;
  9837. };
  9838. exports.crypto = function (line) {
  9839. var parts = line.substr(9).split(' ');
  9840. var parsed = {
  9841. tag: parts[0],
  9842. cipherSuite: parts[1],
  9843. keyParams: parts[2],
  9844. sessionParams: parts.slice(3).join(' ')
  9845. };
  9846. return parsed;
  9847. };
  9848. exports.fingerprint = function (line) {
  9849. var parts = line.substr(14).split(' ');
  9850. return {
  9851. hash: parts[0],
  9852. value: parts[1]
  9853. };
  9854. };
  9855. exports.extmap = function (line) {
  9856. var parts = line.substr(9).split(' ');
  9857. var parsed = {};
  9858. var idpart = parts.shift();
  9859. var sp = idpart.indexOf('/');
  9860. if (sp >= 0) {
  9861. parsed.id = idpart.substr(0, sp);
  9862. parsed.senders = idpart.substr(sp + 1);
  9863. } else {
  9864. parsed.id = idpart;
  9865. parsed.senders = 'sendrecv';
  9866. }
  9867. parsed.uri = parts.shift() || '';
  9868. return parsed;
  9869. };
  9870. exports.rtcpfb = function (line) {
  9871. var parts = line.substr(10).split(' ');
  9872. var parsed = {};
  9873. parsed.id = parts.shift();
  9874. parsed.type = parts.shift();
  9875. if (parsed.type === 'trr-int') {
  9876. parsed.value = parts.shift();
  9877. } else {
  9878. parsed.subtype = parts.shift() || '';
  9879. }
  9880. parsed.parameters = parts;
  9881. return parsed;
  9882. };
  9883. exports.candidate = function (line) {
  9884. var parts;
  9885. if (line.indexOf('a=candidate:') === 0) {
  9886. parts = line.substring(12).split(' ');
  9887. } else { // no a=candidate
  9888. parts = line.substring(10).split(' ');
  9889. }
  9890. var candidate = {
  9891. foundation: parts[0],
  9892. component: parts[1],
  9893. protocol: parts[2].toLowerCase(),
  9894. priority: parts[3],
  9895. ip: parts[4],
  9896. port: parts[5],
  9897. // skip parts[6] == 'typ'
  9898. type: parts[7],
  9899. generation: '0'
  9900. };
  9901. for (var i = 8; i < parts.length; i += 2) {
  9902. if (parts[i] === 'raddr') {
  9903. candidate.relAddr = parts[i + 1];
  9904. } else if (parts[i] === 'rport') {
  9905. candidate.relPort = parts[i + 1];
  9906. } else if (parts[i] === 'generation') {
  9907. candidate.generation = parts[i + 1];
  9908. } else if (parts[i] === 'tcptype') {
  9909. candidate.tcpType = parts[i + 1];
  9910. }
  9911. }
  9912. candidate.network = '1';
  9913. return candidate;
  9914. };
  9915. exports.sourceGroups = function (lines) {
  9916. var parsed = [];
  9917. for (var i = 0; i < lines.length; i++) {
  9918. var parts = lines[i].substr(13).split(' ');
  9919. parsed.push({
  9920. semantics: parts.shift(),
  9921. sources: parts
  9922. });
  9923. }
  9924. return parsed;
  9925. };
  9926. exports.sources = function (lines) {
  9927. // http://tools.ietf.org/html/rfc5576
  9928. var parsed = [];
  9929. var sources = {};
  9930. for (var i = 0; i < lines.length; i++) {
  9931. var parts = lines[i].substr(7).split(' ');
  9932. var ssrc = parts.shift();
  9933. if (!sources[ssrc]) {
  9934. var source = {
  9935. ssrc: ssrc,
  9936. parameters: []
  9937. };
  9938. parsed.push(source);
  9939. // Keep an index
  9940. sources[ssrc] = source;
  9941. }
  9942. parts = parts.join(' ').split(':');
  9943. var attribute = parts.shift();
  9944. var value = parts.join(':') || null;
  9945. sources[ssrc].parameters.push({
  9946. key: attribute,
  9947. value: value
  9948. });
  9949. }
  9950. return parsed;
  9951. };
  9952. exports.groups = function (lines) {
  9953. // http://tools.ietf.org/html/rfc5888
  9954. var parsed = [];
  9955. var parts;
  9956. for (var i = 0; i < lines.length; i++) {
  9957. parts = lines[i].substr(8).split(' ');
  9958. parsed.push({
  9959. semantics: parts.shift(),
  9960. contents: parts
  9961. });
  9962. }
  9963. return parsed;
  9964. };
  9965. exports.bandwidth = function (line) {
  9966. var parts = line.substr(2).split(':');
  9967. var parsed = {};
  9968. parsed.type = parts.shift();
  9969. parsed.bandwidth = parts.shift();
  9970. return parsed;
  9971. };
  9972. exports.msid = function (line) {
  9973. var data = line.substr(7);
  9974. var parts = data.split(' ');
  9975. return {
  9976. msid: data,
  9977. mslabel: parts[0],
  9978. label: parts[1]
  9979. };
  9980. };
  9981. },{}],59:[function(require,module,exports){
  9982. module.exports = {
  9983. initiator: {
  9984. incoming: {
  9985. initiator: 'recvonly',
  9986. responder: 'sendonly',
  9987. both: 'sendrecv',
  9988. none: 'inactive',
  9989. recvonly: 'initiator',
  9990. sendonly: 'responder',
  9991. sendrecv: 'both',
  9992. inactive: 'none'
  9993. },
  9994. outgoing: {
  9995. initiator: 'sendonly',
  9996. responder: 'recvonly',
  9997. both: 'sendrecv',
  9998. none: 'inactive',
  9999. recvonly: 'responder',
  10000. sendonly: 'initiator',
  10001. sendrecv: 'both',
  10002. inactive: 'none'
  10003. }
  10004. },
  10005. responder: {
  10006. incoming: {
  10007. initiator: 'sendonly',
  10008. responder: 'recvonly',
  10009. both: 'sendrecv',
  10010. none: 'inactive',
  10011. recvonly: 'responder',
  10012. sendonly: 'initiator',
  10013. sendrecv: 'both',
  10014. inactive: 'none'
  10015. },
  10016. outgoing: {
  10017. initiator: 'recvonly',
  10018. responder: 'sendonly',
  10019. both: 'sendrecv',
  10020. none: 'inactive',
  10021. recvonly: 'initiator',
  10022. sendonly: 'responder',
  10023. sendrecv: 'both',
  10024. inactive: 'none'
  10025. }
  10026. }
  10027. };
  10028. },{}],60:[function(require,module,exports){
  10029. var SENDERS = require('./senders');
  10030. var parsers = require('./parsers');
  10031. var idCounter = Math.random();
  10032. exports._setIdCounter = function (counter) {
  10033. idCounter = counter;
  10034. };
  10035. exports.toSessionJSON = function (sdp, opts) {
  10036. var i;
  10037. var creators = opts.creators || [];
  10038. var role = opts.role || 'initiator';
  10039. var direction = opts.direction || 'outgoing';
  10040. // Divide the SDP into session and media sections.
  10041. var media = sdp.split('\r\nm=');
  10042. for (i = 1; i < media.length; i++) {
  10043. media[i] = 'm=' + media[i];
  10044. if (i !== media.length - 1) {
  10045. media[i] += '\r\n';
  10046. }
  10047. }
  10048. var session = media.shift() + '\r\n';
  10049. var sessionLines = parsers.lines(session);
  10050. var parsed = {};
  10051. var contents = [];
  10052. for (i = 0; i < media.length; i++) {
  10053. contents.push(exports.toMediaJSON(media[i], session, {
  10054. role: role,
  10055. direction: direction,
  10056. creator: creators[i] || 'initiator'
  10057. }));
  10058. }
  10059. parsed.contents = contents;
  10060. var groupLines = parsers.findLines('a=group:', sessionLines);
  10061. if (groupLines.length) {
  10062. parsed.groups = parsers.groups(groupLines);
  10063. }
  10064. return parsed;
  10065. };
  10066. exports.toMediaJSON = function (media, session, opts) {
  10067. var creator = opts.creator || 'initiator';
  10068. var role = opts.role || 'initiator';
  10069. var direction = opts.direction || 'outgoing';
  10070. var lines = parsers.lines(media);
  10071. var sessionLines = parsers.lines(session);
  10072. var mline = parsers.mline(lines[0]);
  10073. var content = {
  10074. creator: creator,
  10075. name: mline.media,
  10076. application: {
  10077. applicationType: 'rtp',
  10078. media: mline.media,
  10079. payloads: [],
  10080. encryption: [],
  10081. feedback: [],
  10082. headerExtensions: []
  10083. },
  10084. transport: {
  10085. transportType: 'iceUdp',
  10086. candidates: [],
  10087. fingerprints: []
  10088. }
  10089. };
  10090. if (mline.media == 'application') {
  10091. // FIXME: the description is most likely to be independent
  10092. // of the SDP and should be processed by other parts of the library
  10093. content.application = {
  10094. applicationType: 'datachannel'
  10095. };
  10096. content.transport.sctp = [];
  10097. }
  10098. var desc = content.application;
  10099. var trans = content.transport;
  10100. // If we have a mid, use that for the content name instead.
  10101. var mid = parsers.findLine('a=mid:', lines);
  10102. if (mid) {
  10103. content.name = mid.substr(6);
  10104. }
  10105. if (parsers.findLine('a=sendrecv', lines, sessionLines)) {
  10106. content.senders = 'both';
  10107. } else if (parsers.findLine('a=sendonly', lines, sessionLines)) {
  10108. content.senders = SENDERS[role][direction].sendonly;
  10109. } else if (parsers.findLine('a=recvonly', lines, sessionLines)) {
  10110. content.senders = SENDERS[role][direction].recvonly;
  10111. } else if (parsers.findLine('a=inactive', lines, sessionLines)) {
  10112. content.senders = 'none';
  10113. }
  10114. if (desc.applicationType == 'rtp') {
  10115. var bandwidth = parsers.findLine('b=', lines);
  10116. if (bandwidth) {
  10117. desc.bandwidth = parsers.bandwidth(bandwidth);
  10118. }
  10119. var ssrc = parsers.findLine('a=ssrc:', lines);
  10120. if (ssrc) {
  10121. desc.ssrc = ssrc.substr(7).split(' ')[0];
  10122. }
  10123. var rtpmapLines = parsers.findLines('a=rtpmap:', lines);
  10124. rtpmapLines.forEach(function (line) {
  10125. var payload = parsers.rtpmap(line);
  10126. payload.parameters = [];
  10127. payload.feedback = [];
  10128. var fmtpLines = parsers.findLines('a=fmtp:' + payload.id, lines);
  10129. // There should only be one fmtp line per payload
  10130. fmtpLines.forEach(function (line) {
  10131. payload.parameters = parsers.fmtp(line);
  10132. });
  10133. var fbLines = parsers.findLines('a=rtcp-fb:' + payload.id, lines);
  10134. fbLines.forEach(function (line) {
  10135. payload.feedback.push(parsers.rtcpfb(line));
  10136. });
  10137. desc.payloads.push(payload);
  10138. });
  10139. var cryptoLines = parsers.findLines('a=crypto:', lines, sessionLines);
  10140. cryptoLines.forEach(function (line) {
  10141. desc.encryption.push(parsers.crypto(line));
  10142. });
  10143. if (parsers.findLine('a=rtcp-mux', lines)) {
  10144. desc.mux = true;
  10145. }
  10146. var fbLines = parsers.findLines('a=rtcp-fb:*', lines);
  10147. fbLines.forEach(function (line) {
  10148. desc.feedback.push(parsers.rtcpfb(line));
  10149. });
  10150. var extLines = parsers.findLines('a=extmap:', lines);
  10151. extLines.forEach(function (line) {
  10152. var ext = parsers.extmap(line);
  10153. ext.senders = SENDERS[role][direction][ext.senders];
  10154. desc.headerExtensions.push(ext);
  10155. });
  10156. var ssrcGroupLines = parsers.findLines('a=ssrc-group:', lines);
  10157. desc.sourceGroups = parsers.sourceGroups(ssrcGroupLines || []);
  10158. var ssrcLines = parsers.findLines('a=ssrc:', lines);
  10159. var sources = desc.sources = parsers.sources(ssrcLines || []);
  10160. var msidLine = parsers.findLine('a=msid:', lines);
  10161. if (msidLine) {
  10162. var msid = parsers.msid(msidLine);
  10163. ['msid', 'mslabel', 'label'].forEach(function (key) {
  10164. for (var i = 0; i < sources.length; i++) {
  10165. var found = false;
  10166. for (var j = 0; j < sources[i].parameters.length; j++) {
  10167. if (sources[i].parameters[j].key === key) {
  10168. found = true;
  10169. }
  10170. }
  10171. if (!found) {
  10172. sources[i].parameters.push({ key: key, value: msid[key] });
  10173. }
  10174. }
  10175. });
  10176. }
  10177. if (parsers.findLine('a=x-google-flag:conference', lines, sessionLines)) {
  10178. desc.googConferenceFlag = true;
  10179. }
  10180. }
  10181. // transport specific attributes
  10182. var fingerprintLines = parsers.findLines('a=fingerprint:', lines, sessionLines);
  10183. var setup = parsers.findLine('a=setup:', lines, sessionLines);
  10184. fingerprintLines.forEach(function (line) {
  10185. var fp = parsers.fingerprint(line);
  10186. if (setup) {
  10187. fp.setup = setup.substr(8);
  10188. }
  10189. trans.fingerprints.push(fp);
  10190. });
  10191. var ufragLine = parsers.findLine('a=ice-ufrag:', lines, sessionLines);
  10192. var pwdLine = parsers.findLine('a=ice-pwd:', lines, sessionLines);
  10193. if (ufragLine && pwdLine) {
  10194. trans.ufrag = ufragLine.substr(12);
  10195. trans.pwd = pwdLine.substr(10);
  10196. trans.candidates = [];
  10197. var candidateLines = parsers.findLines('a=candidate:', lines, sessionLines);
  10198. candidateLines.forEach(function (line) {
  10199. trans.candidates.push(exports.toCandidateJSON(line));
  10200. });
  10201. }
  10202. if (desc.applicationType == 'datachannel') {
  10203. var sctpmapLines = parsers.findLines('a=sctpmap:', lines);
  10204. sctpmapLines.forEach(function (line) {
  10205. var sctp = parsers.sctpmap(line);
  10206. trans.sctp.push(sctp);
  10207. });
  10208. }
  10209. return content;
  10210. };
  10211. exports.toCandidateJSON = function (line) {
  10212. var candidate = parsers.candidate(line.split('\r\n')[0]);
  10213. candidate.id = (idCounter++).toString(36).substr(0, 12);
  10214. return candidate;
  10215. };
  10216. },{"./parsers":58,"./senders":59}],61:[function(require,module,exports){
  10217. var SENDERS = require('./senders');
  10218. exports.toSessionSDP = function (session, opts) {
  10219. var role = opts.role || 'initiator';
  10220. var direction = opts.direction || 'outgoing';
  10221. var sid = opts.sid || session.sid || Date.now();
  10222. var time = opts.time || Date.now();
  10223. var sdp = [
  10224. 'v=0',
  10225. 'o=- ' + sid + ' ' + time + ' IN IP4 0.0.0.0',
  10226. 's=-',
  10227. 't=0 0'
  10228. ];
  10229. var contents = session.contents || [];
  10230. var hasSources = false;
  10231. contents.forEach(function (content) {
  10232. if (content.application.sources &&
  10233. content.application.sources.length) {
  10234. hasSources = true;
  10235. }
  10236. });
  10237. if (hasSources) {
  10238. sdp.push('a=msid-semantic: WMS *');
  10239. }
  10240. var groups = session.groups || [];
  10241. groups.forEach(function (group) {
  10242. sdp.push('a=group:' + group.semantics + ' ' + group.contents.join(' '));
  10243. });
  10244. contents.forEach(function (content) {
  10245. sdp.push(exports.toMediaSDP(content, opts));
  10246. });
  10247. return sdp.join('\r\n') + '\r\n';
  10248. };
  10249. exports.toMediaSDP = function (content, opts) {
  10250. var sdp = [];
  10251. var role = opts.role || 'initiator';
  10252. var direction = opts.direction || 'outgoing';
  10253. var desc = content.application;
  10254. var transport = content.transport;
  10255. var payloads = desc.payloads || [];
  10256. var fingerprints = (transport && transport.fingerprints) || [];
  10257. var mline = [];
  10258. if (desc.applicationType == 'datachannel') {
  10259. mline.push('application');
  10260. mline.push('1');
  10261. mline.push('DTLS/SCTP');
  10262. if (transport.sctp) {
  10263. transport.sctp.forEach(function (map) {
  10264. mline.push(map.number);
  10265. });
  10266. }
  10267. } else {
  10268. mline.push(desc.media);
  10269. mline.push('1');
  10270. if (fingerprints.length > 0) {
  10271. mline.push('UDP/TLS/RTP/SAVPF');
  10272. } else if (desc.encryption && desc.encryption.length > 0) {
  10273. mline.push('RTP/SAVPF');
  10274. } else {
  10275. mline.push('RTP/AVPF');
  10276. }
  10277. payloads.forEach(function (payload) {
  10278. mline.push(payload.id);
  10279. });
  10280. }
  10281. sdp.push('m=' + mline.join(' '));
  10282. sdp.push('c=IN IP4 0.0.0.0');
  10283. if (desc.bandwidth && desc.bandwidth.type && desc.bandwidth.bandwidth) {
  10284. sdp.push('b=' + desc.bandwidth.type + ':' + desc.bandwidth.bandwidth);
  10285. }
  10286. if (desc.applicationType == 'rtp') {
  10287. sdp.push('a=rtcp:1 IN IP4 0.0.0.0');
  10288. }
  10289. if (transport) {
  10290. if (transport.ufrag) {
  10291. sdp.push('a=ice-ufrag:' + transport.ufrag);
  10292. }
  10293. if (transport.pwd) {
  10294. sdp.push('a=ice-pwd:' + transport.pwd);
  10295. }
  10296. var pushedSetup = false;
  10297. fingerprints.forEach(function (fingerprint) {
  10298. sdp.push('a=fingerprint:' + fingerprint.hash + ' ' + fingerprint.value);
  10299. if (fingerprint.setup && !pushedSetup) {
  10300. sdp.push('a=setup:' + fingerprint.setup);
  10301. }
  10302. });
  10303. if (transport.sctp) {
  10304. transport.sctp.forEach(function (map) {
  10305. sdp.push('a=sctpmap:' + map.number + ' ' + map.protocol + ' ' + map.streams);
  10306. });
  10307. }
  10308. }
  10309. if (desc.applicationType == 'rtp') {
  10310. sdp.push('a=' + (SENDERS[role][direction][content.senders] || 'sendrecv'));
  10311. }
  10312. sdp.push('a=mid:' + content.name);
  10313. if (desc.sources && desc.sources.length) {
  10314. (desc.sources[0].parameters || []).forEach(function (param) {
  10315. if (param.key === 'msid') {
  10316. sdp.push('a=msid:' + param.value);
  10317. }
  10318. });
  10319. }
  10320. if (desc.mux) {
  10321. sdp.push('a=rtcp-mux');
  10322. }
  10323. var encryption = desc.encryption || [];
  10324. encryption.forEach(function (crypto) {
  10325. sdp.push('a=crypto:' + crypto.tag + ' ' + crypto.cipherSuite + ' ' + crypto.keyParams + (crypto.sessionParams ? ' ' + crypto.sessionParams : ''));
  10326. });
  10327. if (desc.googConferenceFlag) {
  10328. sdp.push('a=x-google-flag:conference');
  10329. }
  10330. payloads.forEach(function (payload) {
  10331. var rtpmap = 'a=rtpmap:' + payload.id + ' ' + payload.name + '/' + payload.clockrate;
  10332. if (payload.channels && payload.channels != '1') {
  10333. rtpmap += '/' + payload.channels;
  10334. }
  10335. sdp.push(rtpmap);
  10336. if (payload.parameters && payload.parameters.length) {
  10337. var fmtp = ['a=fmtp:' + payload.id];
  10338. var parameters = [];
  10339. payload.parameters.forEach(function (param) {
  10340. parameters.push((param.key ? param.key + '=' : '') + param.value);
  10341. });
  10342. fmtp.push(parameters.join(';'));
  10343. sdp.push(fmtp.join(' '));
  10344. }
  10345. if (payload.feedback) {
  10346. payload.feedback.forEach(function (fb) {
  10347. if (fb.type === 'trr-int') {
  10348. sdp.push('a=rtcp-fb:' + payload.id + ' trr-int ' + (fb.value ? fb.value : '0'));
  10349. } else {
  10350. sdp.push('a=rtcp-fb:' + payload.id + ' ' + fb.type + (fb.subtype ? ' ' + fb.subtype : ''));
  10351. }
  10352. });
  10353. }
  10354. });
  10355. if (desc.feedback) {
  10356. desc.feedback.forEach(function (fb) {
  10357. if (fb.type === 'trr-int') {
  10358. sdp.push('a=rtcp-fb:* trr-int ' + (fb.value ? fb.value : '0'));
  10359. } else {
  10360. sdp.push('a=rtcp-fb:* ' + fb.type + (fb.subtype ? ' ' + fb.subtype : ''));
  10361. }
  10362. });
  10363. }
  10364. var hdrExts = desc.headerExtensions || [];
  10365. hdrExts.forEach(function (hdr) {
  10366. sdp.push('a=extmap:' + hdr.id + (hdr.senders ? '/' + SENDERS[role][direction][hdr.senders] : '') + ' ' + hdr.uri);
  10367. });
  10368. var ssrcGroups = desc.sourceGroups || [];
  10369. ssrcGroups.forEach(function (ssrcGroup) {
  10370. sdp.push('a=ssrc-group:' + ssrcGroup.semantics + ' ' + ssrcGroup.sources.join(' '));
  10371. });
  10372. var ssrcs = desc.sources || [];
  10373. ssrcs.forEach(function (ssrc) {
  10374. for (var i = 0; i < ssrc.parameters.length; i++) {
  10375. var param = ssrc.parameters[i];
  10376. sdp.push('a=ssrc:' + (ssrc.ssrc || desc.ssrc) + ' ' + param.key + (param.value ? (':' + param.value) : ''));
  10377. }
  10378. });
  10379. var candidates = transport.candidates || [];
  10380. candidates.forEach(function (candidate) {
  10381. sdp.push(exports.toCandidateSDP(candidate));
  10382. });
  10383. return sdp.join('\r\n');
  10384. };
  10385. exports.toCandidateSDP = function (candidate) {
  10386. var sdp = [];
  10387. sdp.push(candidate.foundation);
  10388. sdp.push(candidate.component);
  10389. sdp.push(candidate.protocol.toUpperCase());
  10390. sdp.push(candidate.priority);
  10391. sdp.push(candidate.ip);
  10392. sdp.push(candidate.port);
  10393. var type = candidate.type;
  10394. sdp.push('typ');
  10395. sdp.push(type);
  10396. if (type === 'srflx' || type === 'prflx' || type === 'relay') {
  10397. if (candidate.relAddr && candidate.relPort) {
  10398. sdp.push('raddr');
  10399. sdp.push(candidate.relAddr);
  10400. sdp.push('rport');
  10401. sdp.push(candidate.relPort);
  10402. }
  10403. }
  10404. if (candidate.tcpType && candidate.protocol.toUpperCase() == 'TCP') {
  10405. sdp.push('tcptype');
  10406. sdp.push(candidate.tcpType);
  10407. }
  10408. sdp.push('generation');
  10409. sdp.push(candidate.generation || '0');
  10410. // FIXME: apparently this is wrong per spec
  10411. // but then, we need this when actually putting this into
  10412. // SDP so it's going to stay.
  10413. // decision needs to be revisited when browsers dont
  10414. // accept this any longer
  10415. return 'a=candidate:' + sdp.join(' ');
  10416. };
  10417. },{"./senders":59}],62:[function(require,module,exports){
  10418. /* eslint-env node */
  10419. 'use strict';
  10420. // SDP helpers.
  10421. var SDPUtils = {};
  10422. // Generate an alphanumeric identifier for cname or mids.
  10423. // TODO: use UUIDs instead? https://gist.github.com/jed/982883
  10424. SDPUtils.generateIdentifier = function() {
  10425. return Math.random().toString(36).substr(2, 10);
  10426. };
  10427. // The RTCP CNAME used by all peerconnections from the same JS.
  10428. SDPUtils.localCName = SDPUtils.generateIdentifier();
  10429. // Splits SDP into lines, dealing with both CRLF and LF.
  10430. SDPUtils.splitLines = function(blob) {
  10431. return blob.trim().split('\n').map(function(line) {
  10432. return line.trim();
  10433. });
  10434. };
  10435. // Splits SDP into sessionpart and mediasections. Ensures CRLF.
  10436. SDPUtils.splitSections = function(blob) {
  10437. var parts = blob.split('\nm=');
  10438. return parts.map(function(part, index) {
  10439. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  10440. });
  10441. };
  10442. // Returns lines that start with a certain prefix.
  10443. SDPUtils.matchPrefix = function(blob, prefix) {
  10444. return SDPUtils.splitLines(blob).filter(function(line) {
  10445. return line.indexOf(prefix) === 0;
  10446. });
  10447. };
  10448. // Parses an ICE candidate line. Sample input:
  10449. // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
  10450. // rport 55996"
  10451. SDPUtils.parseCandidate = function(line) {
  10452. var parts;
  10453. // Parse both variants.
  10454. if (line.indexOf('a=candidate:') === 0) {
  10455. parts = line.substring(12).split(' ');
  10456. } else {
  10457. parts = line.substring(10).split(' ');
  10458. }
  10459. var candidate = {
  10460. foundation: parts[0],
  10461. component: parts[1],
  10462. protocol: parts[2].toLowerCase(),
  10463. priority: parseInt(parts[3], 10),
  10464. ip: parts[4],
  10465. port: parseInt(parts[5], 10),
  10466. // skip parts[6] == 'typ'
  10467. type: parts[7]
  10468. };
  10469. for (var i = 8; i < parts.length; i += 2) {
  10470. switch (parts[i]) {
  10471. case 'raddr':
  10472. candidate.relatedAddress = parts[i + 1];
  10473. break;
  10474. case 'rport':
  10475. candidate.relatedPort = parseInt(parts[i + 1], 10);
  10476. break;
  10477. case 'tcptype':
  10478. candidate.tcpType = parts[i + 1];
  10479. break;
  10480. default: // Unknown extensions are silently ignored.
  10481. break;
  10482. }
  10483. }
  10484. return candidate;
  10485. };
  10486. // Translates a candidate object into SDP candidate attribute.
  10487. SDPUtils.writeCandidate = function(candidate) {
  10488. var sdp = [];
  10489. sdp.push(candidate.foundation);
  10490. sdp.push(candidate.component);
  10491. sdp.push(candidate.protocol.toUpperCase());
  10492. sdp.push(candidate.priority);
  10493. sdp.push(candidate.ip);
  10494. sdp.push(candidate.port);
  10495. var type = candidate.type;
  10496. sdp.push('typ');
  10497. sdp.push(type);
  10498. if (type !== 'host' && candidate.relatedAddress &&
  10499. candidate.relatedPort) {
  10500. sdp.push('raddr');
  10501. sdp.push(candidate.relatedAddress); // was: relAddr
  10502. sdp.push('rport');
  10503. sdp.push(candidate.relatedPort); // was: relPort
  10504. }
  10505. if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
  10506. sdp.push('tcptype');
  10507. sdp.push(candidate.tcpType);
  10508. }
  10509. return 'candidate:' + sdp.join(' ');
  10510. };
  10511. // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
  10512. // a=rtpmap:111 opus/48000/2
  10513. SDPUtils.parseRtpMap = function(line) {
  10514. var parts = line.substr(9).split(' ');
  10515. var parsed = {
  10516. payloadType: parseInt(parts.shift(), 10) // was: id
  10517. };
  10518. parts = parts[0].split('/');
  10519. parsed.name = parts[0];
  10520. parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
  10521. // was: channels
  10522. parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
  10523. return parsed;
  10524. };
  10525. // Generate an a=rtpmap line from RTCRtpCodecCapability or
  10526. // RTCRtpCodecParameters.
  10527. SDPUtils.writeRtpMap = function(codec) {
  10528. var pt = codec.payloadType;
  10529. if (codec.preferredPayloadType !== undefined) {
  10530. pt = codec.preferredPayloadType;
  10531. }
  10532. return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
  10533. (codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n';
  10534. };
  10535. // Parses an a=extmap line (headerextension from RFC 5285). Sample input:
  10536. // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  10537. SDPUtils.parseExtmap = function(line) {
  10538. var parts = line.substr(9).split(' ');
  10539. return {
  10540. id: parseInt(parts[0], 10),
  10541. uri: parts[1]
  10542. };
  10543. };
  10544. // Generates a=extmap line from RTCRtpHeaderExtensionParameters or
  10545. // RTCRtpHeaderExtension.
  10546. SDPUtils.writeExtmap = function(headerExtension) {
  10547. return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
  10548. ' ' + headerExtension.uri + '\r\n';
  10549. };
  10550. // Parses an ftmp line, returns dictionary. Sample input:
  10551. // a=fmtp:96 vbr=on;cng=on
  10552. // Also deals with vbr=on; cng=on
  10553. SDPUtils.parseFmtp = function(line) {
  10554. var parsed = {};
  10555. var kv;
  10556. var parts = line.substr(line.indexOf(' ') + 1).split(';');
  10557. for (var j = 0; j < parts.length; j++) {
  10558. kv = parts[j].trim().split('=');
  10559. parsed[kv[0].trim()] = kv[1];
  10560. }
  10561. return parsed;
  10562. };
  10563. // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
  10564. SDPUtils.writeFmtp = function(codec) {
  10565. var line = '';
  10566. var pt = codec.payloadType;
  10567. if (codec.preferredPayloadType !== undefined) {
  10568. pt = codec.preferredPayloadType;
  10569. }
  10570. if (codec.parameters && Object.keys(codec.parameters).length) {
  10571. var params = [];
  10572. Object.keys(codec.parameters).forEach(function(param) {
  10573. params.push(param + '=' + codec.parameters[param]);
  10574. });
  10575. line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
  10576. }
  10577. return line;
  10578. };
  10579. // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
  10580. // a=rtcp-fb:98 nack rpsi
  10581. SDPUtils.parseRtcpFb = function(line) {
  10582. var parts = line.substr(line.indexOf(' ') + 1).split(' ');
  10583. return {
  10584. type: parts.shift(),
  10585. parameter: parts.join(' ')
  10586. };
  10587. };
  10588. // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
  10589. SDPUtils.writeRtcpFb = function(codec) {
  10590. var lines = '';
  10591. var pt = codec.payloadType;
  10592. if (codec.preferredPayloadType !== undefined) {
  10593. pt = codec.preferredPayloadType;
  10594. }
  10595. if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
  10596. // FIXME: special handling for trr-int?
  10597. codec.rtcpFeedback.forEach(function(fb) {
  10598. lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
  10599. (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
  10600. '\r\n';
  10601. });
  10602. }
  10603. return lines;
  10604. };
  10605. // Parses an RFC 5576 ssrc media attribute. Sample input:
  10606. // a=ssrc:3735928559 cname:something
  10607. SDPUtils.parseSsrcMedia = function(line) {
  10608. var sp = line.indexOf(' ');
  10609. var parts = {
  10610. ssrc: parseInt(line.substr(7, sp - 7), 10)
  10611. };
  10612. var colon = line.indexOf(':', sp);
  10613. if (colon > -1) {
  10614. parts.attribute = line.substr(sp + 1, colon - sp - 1);
  10615. parts.value = line.substr(colon + 1);
  10616. } else {
  10617. parts.attribute = line.substr(sp + 1);
  10618. }
  10619. return parts;
  10620. };
  10621. // Extracts DTLS parameters from SDP media section or sessionpart.
  10622. // FIXME: for consistency with other functions this should only
  10623. // get the fingerprint line as input. See also getIceParameters.
  10624. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
  10625. var lines = SDPUtils.splitLines(mediaSection);
  10626. // Search in session part, too.
  10627. lines = lines.concat(SDPUtils.splitLines(sessionpart));
  10628. var fpLine = lines.filter(function(line) {
  10629. return line.indexOf('a=fingerprint:') === 0;
  10630. })[0].substr(14);
  10631. // Note: a=setup line is ignored since we use the 'auto' role.
  10632. var dtlsParameters = {
  10633. role: 'auto',
  10634. fingerprints: [{
  10635. algorithm: fpLine.split(' ')[0],
  10636. value: fpLine.split(' ')[1]
  10637. }]
  10638. };
  10639. return dtlsParameters;
  10640. };
  10641. // Serializes DTLS parameters to SDP.
  10642. SDPUtils.writeDtlsParameters = function(params, setupType) {
  10643. var sdp = 'a=setup:' + setupType + '\r\n';
  10644. params.fingerprints.forEach(function(fp) {
  10645. sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
  10646. });
  10647. return sdp;
  10648. };
  10649. // Parses ICE information from SDP media section or sessionpart.
  10650. // FIXME: for consistency with other functions this should only
  10651. // get the ice-ufrag and ice-pwd lines as input.
  10652. SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
  10653. var lines = SDPUtils.splitLines(mediaSection);
  10654. // Search in session part, too.
  10655. lines = lines.concat(SDPUtils.splitLines(sessionpart));
  10656. var iceParameters = {
  10657. usernameFragment: lines.filter(function(line) {
  10658. return line.indexOf('a=ice-ufrag:') === 0;
  10659. })[0].substr(12),
  10660. password: lines.filter(function(line) {
  10661. return line.indexOf('a=ice-pwd:') === 0;
  10662. })[0].substr(10)
  10663. };
  10664. return iceParameters;
  10665. };
  10666. // Serializes ICE parameters to SDP.
  10667. SDPUtils.writeIceParameters = function(params) {
  10668. return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
  10669. 'a=ice-pwd:' + params.password + '\r\n';
  10670. };
  10671. // Parses the SDP media section and returns RTCRtpParameters.
  10672. SDPUtils.parseRtpParameters = function(mediaSection) {
  10673. var description = {
  10674. codecs: [],
  10675. headerExtensions: [],
  10676. fecMechanisms: [],
  10677. rtcp: []
  10678. };
  10679. var lines = SDPUtils.splitLines(mediaSection);
  10680. var mline = lines[0].split(' ');
  10681. for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
  10682. var pt = mline[i];
  10683. var rtpmapline = SDPUtils.matchPrefix(
  10684. mediaSection, 'a=rtpmap:' + pt + ' ')[0];
  10685. if (rtpmapline) {
  10686. var codec = SDPUtils.parseRtpMap(rtpmapline);
  10687. var fmtps = SDPUtils.matchPrefix(
  10688. mediaSection, 'a=fmtp:' + pt + ' ');
  10689. // Only the first a=fmtp:<pt> is considered.
  10690. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
  10691. codec.rtcpFeedback = SDPUtils.matchPrefix(
  10692. mediaSection, 'a=rtcp-fb:' + pt + ' ')
  10693. .map(SDPUtils.parseRtcpFb);
  10694. description.codecs.push(codec);
  10695. // parse FEC mechanisms from rtpmap lines.
  10696. switch (codec.name.toUpperCase()) {
  10697. case 'RED':
  10698. case 'ULPFEC':
  10699. description.fecMechanisms.push(codec.name.toUpperCase());
  10700. break;
  10701. default: // only RED and ULPFEC are recognized as FEC mechanisms.
  10702. break;
  10703. }
  10704. }
  10705. }
  10706. SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
  10707. description.headerExtensions.push(SDPUtils.parseExtmap(line));
  10708. });
  10709. // FIXME: parse rtcp.
  10710. return description;
  10711. };
  10712. // Generates parts of the SDP media section describing the capabilities /
  10713. // parameters.
  10714. SDPUtils.writeRtpDescription = function(kind, caps) {
  10715. var sdp = '';
  10716. // Build the mline.
  10717. sdp += 'm=' + kind + ' ';
  10718. sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
  10719. sdp += ' UDP/TLS/RTP/SAVPF ';
  10720. sdp += caps.codecs.map(function(codec) {
  10721. if (codec.preferredPayloadType !== undefined) {
  10722. return codec.preferredPayloadType;
  10723. }
  10724. return codec.payloadType;
  10725. }).join(' ') + '\r\n';
  10726. sdp += 'c=IN IP4 0.0.0.0\r\n';
  10727. sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
  10728. // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
  10729. caps.codecs.forEach(function(codec) {
  10730. sdp += SDPUtils.writeRtpMap(codec);
  10731. sdp += SDPUtils.writeFmtp(codec);
  10732. sdp += SDPUtils.writeRtcpFb(codec);
  10733. });
  10734. var maxptime = 0;
  10735. caps.codecs.forEach(function(codec) {
  10736. if (codec.maxptime > maxptime) {
  10737. maxptime = codec.maxptime;
  10738. }
  10739. });
  10740. if (maxptime > 0) {
  10741. sdp += 'a=maxptime:' + maxptime + '\r\n';
  10742. }
  10743. sdp += 'a=rtcp-mux\r\n';
  10744. caps.headerExtensions.forEach(function(extension) {
  10745. sdp += SDPUtils.writeExtmap(extension);
  10746. });
  10747. // FIXME: write fecMechanisms.
  10748. return sdp;
  10749. };
  10750. // Parses the SDP media section and returns an array of
  10751. // RTCRtpEncodingParameters.
  10752. SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
  10753. var encodingParameters = [];
  10754. var description = SDPUtils.parseRtpParameters(mediaSection);
  10755. var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
  10756. var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
  10757. // filter a=ssrc:... cname:, ignore PlanB-msid
  10758. var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  10759. .map(function(line) {
  10760. return SDPUtils.parseSsrcMedia(line);
  10761. })
  10762. .filter(function(parts) {
  10763. return parts.attribute === 'cname';
  10764. });
  10765. var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
  10766. var secondarySsrc;
  10767. var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
  10768. .map(function(line) {
  10769. var parts = line.split(' ');
  10770. parts.shift();
  10771. return parts.map(function(part) {
  10772. return parseInt(part, 10);
  10773. });
  10774. });
  10775. if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
  10776. secondarySsrc = flows[0][1];
  10777. }
  10778. description.codecs.forEach(function(codec) {
  10779. if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
  10780. var encParam = {
  10781. ssrc: primarySsrc,
  10782. codecPayloadType: parseInt(codec.parameters.apt, 10),
  10783. rtx: {
  10784. ssrc: secondarySsrc
  10785. }
  10786. };
  10787. encodingParameters.push(encParam);
  10788. if (hasRed) {
  10789. encParam = JSON.parse(JSON.stringify(encParam));
  10790. encParam.fec = {
  10791. ssrc: secondarySsrc,
  10792. mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
  10793. };
  10794. encodingParameters.push(encParam);
  10795. }
  10796. }
  10797. });
  10798. if (encodingParameters.length === 0 && primarySsrc) {
  10799. encodingParameters.push({
  10800. ssrc: primarySsrc
  10801. });
  10802. }
  10803. // we support both b=AS and b=TIAS but interpret AS as TIAS.
  10804. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
  10805. if (bandwidth.length) {
  10806. if (bandwidth[0].indexOf('b=TIAS:') === 0) {
  10807. bandwidth = parseInt(bandwidth[0].substr(7), 10);
  10808. } else if (bandwidth[0].indexOf('b=AS:') === 0) {
  10809. bandwidth = parseInt(bandwidth[0].substr(5), 10);
  10810. }
  10811. encodingParameters.forEach(function(params) {
  10812. params.maxBitrate = bandwidth;
  10813. });
  10814. }
  10815. return encodingParameters;
  10816. };
  10817. SDPUtils.writeSessionBoilerplate = function() {
  10818. // FIXME: sess-id should be an NTP timestamp.
  10819. return 'v=0\r\n' +
  10820. 'o=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\n' +
  10821. 's=-\r\n' +
  10822. 't=0 0\r\n';
  10823. };
  10824. SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
  10825. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  10826. // Map ICE parameters (ufrag, pwd) to SDP.
  10827. sdp += SDPUtils.writeIceParameters(
  10828. transceiver.iceGatherer.getLocalParameters());
  10829. // Map DTLS parameters to SDP.
  10830. sdp += SDPUtils.writeDtlsParameters(
  10831. transceiver.dtlsTransport.getLocalParameters(),
  10832. type === 'offer' ? 'actpass' : 'active');
  10833. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  10834. if (transceiver.rtpSender && transceiver.rtpReceiver) {
  10835. sdp += 'a=sendrecv\r\n';
  10836. } else if (transceiver.rtpSender) {
  10837. sdp += 'a=sendonly\r\n';
  10838. } else if (transceiver.rtpReceiver) {
  10839. sdp += 'a=recvonly\r\n';
  10840. } else {
  10841. sdp += 'a=inactive\r\n';
  10842. }
  10843. // FIXME: for RTX there might be multiple SSRCs. Not implemented in Edge yet.
  10844. if (transceiver.rtpSender) {
  10845. var msid = 'msid:' + stream.id + ' ' +
  10846. transceiver.rtpSender.track.id + '\r\n';
  10847. sdp += 'a=' + msid;
  10848. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  10849. ' ' + msid;
  10850. if (transceiver.sendEncodingParameters[0].rtx) {
  10851. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  10852. ' ' + msid;
  10853. sdp += 'a=ssrc-group:FID ' +
  10854. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  10855. transceiver.sendEncodingParameters[0].rtx.ssrc +
  10856. '\r\n';
  10857. }
  10858. }
  10859. // FIXME: this should be written by writeRtpDescription.
  10860. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  10861. ' cname:' + SDPUtils.localCName + '\r\n';
  10862. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  10863. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  10864. ' cname:' + SDPUtils.localCName + '\r\n';
  10865. }
  10866. return sdp;
  10867. };
  10868. // Gets the direction from the mediaSection or the sessionpart.
  10869. SDPUtils.getDirection = function(mediaSection, sessionpart) {
  10870. // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
  10871. var lines = SDPUtils.splitLines(mediaSection);
  10872. for (var i = 0; i < lines.length; i++) {
  10873. switch (lines[i]) {
  10874. case 'a=sendrecv':
  10875. case 'a=sendonly':
  10876. case 'a=recvonly':
  10877. case 'a=inactive':
  10878. return lines[i].substr(2);
  10879. default:
  10880. // FIXME: What should happen here?
  10881. }
  10882. }
  10883. if (sessionpart) {
  10884. return SDPUtils.getDirection(sessionpart);
  10885. }
  10886. return 'sendrecv';
  10887. };
  10888. // Expose public methods.
  10889. module.exports = SDPUtils;
  10890. },{}],63:[function(require,module,exports){
  10891. module.exports = require('./lib/');
  10892. },{"./lib/":64}],64:[function(require,module,exports){
  10893. /**
  10894. * Module dependencies.
  10895. */
  10896. var url = require('./url');
  10897. var parser = require('socket.io-parser');
  10898. var Manager = require('./manager');
  10899. var debug = require('debug')('socket.io-client');
  10900. /**
  10901. * Module exports.
  10902. */
  10903. module.exports = exports = lookup;
  10904. /**
  10905. * Managers cache.
  10906. */
  10907. var cache = exports.managers = {};
  10908. /**
  10909. * Looks up an existing `Manager` for multiplexing.
  10910. * If the user summons:
  10911. *
  10912. * `io('http://localhost/a');`
  10913. * `io('http://localhost/b');`
  10914. *
  10915. * We reuse the existing instance based on same scheme/port/host,
  10916. * and we initialize sockets for each namespace.
  10917. *
  10918. * @api public
  10919. */
  10920. function lookup(uri, opts) {
  10921. if (typeof uri == 'object') {
  10922. opts = uri;
  10923. uri = undefined;
  10924. }
  10925. opts = opts || {};
  10926. var parsed = url(uri);
  10927. var source = parsed.source;
  10928. var id = parsed.id;
  10929. var io;
  10930. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  10931. debug('ignoring socket cache for %s', source);
  10932. io = Manager(source, opts);
  10933. } else {
  10934. if (!cache[id]) {
  10935. debug('new io instance for %s', source);
  10936. cache[id] = Manager(source, opts);
  10937. }
  10938. io = cache[id];
  10939. }
  10940. return io.socket(parsed.path);
  10941. }
  10942. /**
  10943. * Protocol version.
  10944. *
  10945. * @api public
  10946. */
  10947. exports.protocol = parser.protocol;
  10948. /**
  10949. * `connect`.
  10950. *
  10951. * @param {String} uri
  10952. * @api public
  10953. */
  10954. exports.connect = lookup;
  10955. /**
  10956. * Expose constructors for standalone build.
  10957. *
  10958. * @api public
  10959. */
  10960. exports.Manager = require('./manager');
  10961. exports.Socket = require('./socket');
  10962. },{"./manager":65,"./socket":67,"./url":68,"debug":69,"socket.io-parser":71}],65:[function(require,module,exports){
  10963. /**
  10964. * Module dependencies.
  10965. */
  10966. var url = require('./url');
  10967. var eio = require('engine.io-client');
  10968. var Socket = require('./socket');
  10969. var Emitter = require('component-emitter');
  10970. var parser = require('socket.io-parser');
  10971. var on = require('./on');
  10972. var bind = require('component-bind');
  10973. var object = require('object-component');
  10974. var debug = require('debug')('socket.io-client:manager');
  10975. var indexOf = require('indexof');
  10976. var Backoff = require('backo2');
  10977. /**
  10978. * Module exports
  10979. */
  10980. module.exports = Manager;
  10981. /**
  10982. * `Manager` constructor.
  10983. *
  10984. * @param {String} engine instance or engine uri/opts
  10985. * @param {Object} options
  10986. * @api public
  10987. */
  10988. function Manager(uri, opts){
  10989. if (!(this instanceof Manager)) return new Manager(uri, opts);
  10990. if (uri && ('object' == typeof uri)) {
  10991. opts = uri;
  10992. uri = undefined;
  10993. }
  10994. opts = opts || {};
  10995. opts.path = opts.path || '/socket.io';
  10996. this.nsps = {};
  10997. this.subs = [];
  10998. this.opts = opts;
  10999. this.reconnection(opts.reconnection !== false);
  11000. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  11001. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  11002. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  11003. this.randomizationFactor(opts.randomizationFactor || 0.5);
  11004. this.backoff = new Backoff({
  11005. min: this.reconnectionDelay(),
  11006. max: this.reconnectionDelayMax(),
  11007. jitter: this.randomizationFactor()
  11008. });
  11009. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  11010. this.readyState = 'closed';
  11011. this.uri = uri;
  11012. this.connected = [];
  11013. this.encoding = false;
  11014. this.packetBuffer = [];
  11015. this.encoder = new parser.Encoder();
  11016. this.decoder = new parser.Decoder();
  11017. this.autoConnect = opts.autoConnect !== false;
  11018. if (this.autoConnect) this.open();
  11019. }
  11020. /**
  11021. * Propagate given event to sockets and emit on `this`
  11022. *
  11023. * @api private
  11024. */
  11025. Manager.prototype.emitAll = function() {
  11026. this.emit.apply(this, arguments);
  11027. for (var nsp in this.nsps) {
  11028. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  11029. }
  11030. };
  11031. /**
  11032. * Update `socket.id` of all sockets
  11033. *
  11034. * @api private
  11035. */
  11036. Manager.prototype.updateSocketIds = function(){
  11037. for (var nsp in this.nsps) {
  11038. this.nsps[nsp].id = this.engine.id;
  11039. }
  11040. };
  11041. /**
  11042. * Mix in `Emitter`.
  11043. */
  11044. Emitter(Manager.prototype);
  11045. /**
  11046. * Sets the `reconnection` config.
  11047. *
  11048. * @param {Boolean} true/false if it should automatically reconnect
  11049. * @return {Manager} self or value
  11050. * @api public
  11051. */
  11052. Manager.prototype.reconnection = function(v){
  11053. if (!arguments.length) return this._reconnection;
  11054. this._reconnection = !!v;
  11055. return this;
  11056. };
  11057. /**
  11058. * Sets the reconnection attempts config.
  11059. *
  11060. * @param {Number} max reconnection attempts before giving up
  11061. * @return {Manager} self or value
  11062. * @api public
  11063. */
  11064. Manager.prototype.reconnectionAttempts = function(v){
  11065. if (!arguments.length) return this._reconnectionAttempts;
  11066. this._reconnectionAttempts = v;
  11067. return this;
  11068. };
  11069. /**
  11070. * Sets the delay between reconnections.
  11071. *
  11072. * @param {Number} delay
  11073. * @return {Manager} self or value
  11074. * @api public
  11075. */
  11076. Manager.prototype.reconnectionDelay = function(v){
  11077. if (!arguments.length) return this._reconnectionDelay;
  11078. this._reconnectionDelay = v;
  11079. this.backoff && this.backoff.setMin(v);
  11080. return this;
  11081. };
  11082. Manager.prototype.randomizationFactor = function(v){
  11083. if (!arguments.length) return this._randomizationFactor;
  11084. this._randomizationFactor = v;
  11085. this.backoff && this.backoff.setJitter(v);
  11086. return this;
  11087. };
  11088. /**
  11089. * Sets the maximum delay between reconnections.
  11090. *
  11091. * @param {Number} delay
  11092. * @return {Manager} self or value
  11093. * @api public
  11094. */
  11095. Manager.prototype.reconnectionDelayMax = function(v){
  11096. if (!arguments.length) return this._reconnectionDelayMax;
  11097. this._reconnectionDelayMax = v;
  11098. this.backoff && this.backoff.setMax(v);
  11099. return this;
  11100. };
  11101. /**
  11102. * Sets the connection timeout. `false` to disable
  11103. *
  11104. * @return {Manager} self or value
  11105. * @api public
  11106. */
  11107. Manager.prototype.timeout = function(v){
  11108. if (!arguments.length) return this._timeout;
  11109. this._timeout = v;
  11110. return this;
  11111. };
  11112. /**
  11113. * Starts trying to reconnect if reconnection is enabled and we have not
  11114. * started reconnecting yet
  11115. *
  11116. * @api private
  11117. */
  11118. Manager.prototype.maybeReconnectOnOpen = function() {
  11119. // Only try to reconnect if it's the first time we're connecting
  11120. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  11121. // keeps reconnection from firing twice for the same reconnection loop
  11122. this.reconnect();
  11123. }
  11124. };
  11125. /**
  11126. * Sets the current transport `socket`.
  11127. *
  11128. * @param {Function} optional, callback
  11129. * @return {Manager} self
  11130. * @api public
  11131. */
  11132. Manager.prototype.open =
  11133. Manager.prototype.connect = function(fn){
  11134. debug('readyState %s', this.readyState);
  11135. if (~this.readyState.indexOf('open')) return this;
  11136. debug('opening %s', this.uri);
  11137. this.engine = eio(this.uri, this.opts);
  11138. var socket = this.engine;
  11139. var self = this;
  11140. this.readyState = 'opening';
  11141. this.skipReconnect = false;
  11142. // emit `open`
  11143. var openSub = on(socket, 'open', function() {
  11144. self.onopen();
  11145. fn && fn();
  11146. });
  11147. // emit `connect_error`
  11148. var errorSub = on(socket, 'error', function(data){
  11149. debug('connect_error');
  11150. self.cleanup();
  11151. self.readyState = 'closed';
  11152. self.emitAll('connect_error', data);
  11153. if (fn) {
  11154. var err = new Error('Connection error');
  11155. err.data = data;
  11156. fn(err);
  11157. } else {
  11158. // Only do this if there is no fn to handle the error
  11159. self.maybeReconnectOnOpen();
  11160. }
  11161. });
  11162. // emit `connect_timeout`
  11163. if (false !== this._timeout) {
  11164. var timeout = this._timeout;
  11165. debug('connect attempt will timeout after %d', timeout);
  11166. // set timer
  11167. var timer = setTimeout(function(){
  11168. debug('connect attempt timed out after %d', timeout);
  11169. openSub.destroy();
  11170. socket.close();
  11171. socket.emit('error', 'timeout');
  11172. self.emitAll('connect_timeout', timeout);
  11173. }, timeout);
  11174. this.subs.push({
  11175. destroy: function(){
  11176. clearTimeout(timer);
  11177. }
  11178. });
  11179. }
  11180. this.subs.push(openSub);
  11181. this.subs.push(errorSub);
  11182. return this;
  11183. };
  11184. /**
  11185. * Called upon transport open.
  11186. *
  11187. * @api private
  11188. */
  11189. Manager.prototype.onopen = function(){
  11190. debug('open');
  11191. // clear old subs
  11192. this.cleanup();
  11193. // mark as open
  11194. this.readyState = 'open';
  11195. this.emit('open');
  11196. // add new subs
  11197. var socket = this.engine;
  11198. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  11199. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  11200. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  11201. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  11202. };
  11203. /**
  11204. * Called with data.
  11205. *
  11206. * @api private
  11207. */
  11208. Manager.prototype.ondata = function(data){
  11209. this.decoder.add(data);
  11210. };
  11211. /**
  11212. * Called when parser fully decodes a packet.
  11213. *
  11214. * @api private
  11215. */
  11216. Manager.prototype.ondecoded = function(packet) {
  11217. this.emit('packet', packet);
  11218. };
  11219. /**
  11220. * Called upon socket error.
  11221. *
  11222. * @api private
  11223. */
  11224. Manager.prototype.onerror = function(err){
  11225. debug('error', err);
  11226. this.emitAll('error', err);
  11227. };
  11228. /**
  11229. * Creates a new socket for the given `nsp`.
  11230. *
  11231. * @return {Socket}
  11232. * @api public
  11233. */
  11234. Manager.prototype.socket = function(nsp){
  11235. var socket = this.nsps[nsp];
  11236. if (!socket) {
  11237. socket = new Socket(this, nsp);
  11238. this.nsps[nsp] = socket;
  11239. var self = this;
  11240. socket.on('connect', function(){
  11241. socket.id = self.engine.id;
  11242. if (!~indexOf(self.connected, socket)) {
  11243. self.connected.push(socket);
  11244. }
  11245. });
  11246. }
  11247. return socket;
  11248. };
  11249. /**
  11250. * Called upon a socket close.
  11251. *
  11252. * @param {Socket} socket
  11253. */
  11254. Manager.prototype.destroy = function(socket){
  11255. var index = indexOf(this.connected, socket);
  11256. if (~index) this.connected.splice(index, 1);
  11257. if (this.connected.length) return;
  11258. this.close();
  11259. };
  11260. /**
  11261. * Writes a packet.
  11262. *
  11263. * @param {Object} packet
  11264. * @api private
  11265. */
  11266. Manager.prototype.packet = function(packet){
  11267. debug('writing packet %j', packet);
  11268. var self = this;
  11269. if (!self.encoding) {
  11270. // encode, then write to engine with result
  11271. self.encoding = true;
  11272. this.encoder.encode(packet, function(encodedPackets) {
  11273. for (var i = 0; i < encodedPackets.length; i++) {
  11274. self.engine.write(encodedPackets[i]);
  11275. }
  11276. self.encoding = false;
  11277. self.processPacketQueue();
  11278. });
  11279. } else { // add packet to the queue
  11280. self.packetBuffer.push(packet);
  11281. }
  11282. };
  11283. /**
  11284. * If packet buffer is non-empty, begins encoding the
  11285. * next packet in line.
  11286. *
  11287. * @api private
  11288. */
  11289. Manager.prototype.processPacketQueue = function() {
  11290. if (this.packetBuffer.length > 0 && !this.encoding) {
  11291. var pack = this.packetBuffer.shift();
  11292. this.packet(pack);
  11293. }
  11294. };
  11295. /**
  11296. * Clean up transport subscriptions and packet buffer.
  11297. *
  11298. * @api private
  11299. */
  11300. Manager.prototype.cleanup = function(){
  11301. var sub;
  11302. while (sub = this.subs.shift()) sub.destroy();
  11303. this.packetBuffer = [];
  11304. this.encoding = false;
  11305. this.decoder.destroy();
  11306. };
  11307. /**
  11308. * Close the current socket.
  11309. *
  11310. * @api private
  11311. */
  11312. Manager.prototype.close =
  11313. Manager.prototype.disconnect = function(){
  11314. this.skipReconnect = true;
  11315. this.backoff.reset();
  11316. this.readyState = 'closed';
  11317. this.engine && this.engine.close();
  11318. };
  11319. /**
  11320. * Called upon engine close.
  11321. *
  11322. * @api private
  11323. */
  11324. Manager.prototype.onclose = function(reason){
  11325. debug('close');
  11326. this.cleanup();
  11327. this.backoff.reset();
  11328. this.readyState = 'closed';
  11329. this.emit('close', reason);
  11330. if (this._reconnection && !this.skipReconnect) {
  11331. this.reconnect();
  11332. }
  11333. };
  11334. /**
  11335. * Attempt a reconnection.
  11336. *
  11337. * @api private
  11338. */
  11339. Manager.prototype.reconnect = function(){
  11340. if (this.reconnecting || this.skipReconnect) return this;
  11341. var self = this;
  11342. if (this.backoff.attempts >= this._reconnectionAttempts) {
  11343. debug('reconnect failed');
  11344. this.backoff.reset();
  11345. this.emitAll('reconnect_failed');
  11346. this.reconnecting = false;
  11347. } else {
  11348. var delay = this.backoff.duration();
  11349. debug('will wait %dms before reconnect attempt', delay);
  11350. this.reconnecting = true;
  11351. var timer = setTimeout(function(){
  11352. if (self.skipReconnect) return;
  11353. debug('attempting reconnect');
  11354. self.emitAll('reconnect_attempt', self.backoff.attempts);
  11355. self.emitAll('reconnecting', self.backoff.attempts);
  11356. // check again for the case socket closed in above events
  11357. if (self.skipReconnect) return;
  11358. self.open(function(err){
  11359. if (err) {
  11360. debug('reconnect attempt error');
  11361. self.reconnecting = false;
  11362. self.reconnect();
  11363. self.emitAll('reconnect_error', err.data);
  11364. } else {
  11365. debug('reconnect success');
  11366. self.onreconnect();
  11367. }
  11368. });
  11369. }, delay);
  11370. this.subs.push({
  11371. destroy: function(){
  11372. clearTimeout(timer);
  11373. }
  11374. });
  11375. }
  11376. };
  11377. /**
  11378. * Called upon successful reconnect.
  11379. *
  11380. * @api private
  11381. */
  11382. Manager.prototype.onreconnect = function(){
  11383. var attempt = this.backoff.attempts;
  11384. this.reconnecting = false;
  11385. this.backoff.reset();
  11386. this.updateSocketIds();
  11387. this.emitAll('reconnect', attempt);
  11388. };
  11389. },{"./on":66,"./socket":67,"./url":68,"backo2":4,"component-bind":7,"component-emitter":8,"debug":69,"engine.io-client":10,"indexof":44,"object-component":51,"socket.io-parser":71}],66:[function(require,module,exports){
  11390. /**
  11391. * Module exports.
  11392. */
  11393. module.exports = on;
  11394. /**
  11395. * Helper for subscriptions.
  11396. *
  11397. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  11398. * @param {String} event name
  11399. * @param {Function} callback
  11400. * @api public
  11401. */
  11402. function on(obj, ev, fn) {
  11403. obj.on(ev, fn);
  11404. return {
  11405. destroy: function(){
  11406. obj.removeListener(ev, fn);
  11407. }
  11408. };
  11409. }
  11410. },{}],67:[function(require,module,exports){
  11411. /**
  11412. * Module dependencies.
  11413. */
  11414. var parser = require('socket.io-parser');
  11415. var Emitter = require('component-emitter');
  11416. var toArray = require('to-array');
  11417. var on = require('./on');
  11418. var bind = require('component-bind');
  11419. var debug = require('debug')('socket.io-client:socket');
  11420. var hasBin = require('has-binary');
  11421. /**
  11422. * Module exports.
  11423. */
  11424. module.exports = exports = Socket;
  11425. /**
  11426. * Internal events (blacklisted).
  11427. * These events can't be emitted by the user.
  11428. *
  11429. * @api private
  11430. */
  11431. var events = {
  11432. connect: 1,
  11433. connect_error: 1,
  11434. connect_timeout: 1,
  11435. disconnect: 1,
  11436. error: 1,
  11437. reconnect: 1,
  11438. reconnect_attempt: 1,
  11439. reconnect_failed: 1,
  11440. reconnect_error: 1,
  11441. reconnecting: 1
  11442. };
  11443. /**
  11444. * Shortcut to `Emitter#emit`.
  11445. */
  11446. var emit = Emitter.prototype.emit;
  11447. /**
  11448. * `Socket` constructor.
  11449. *
  11450. * @api public
  11451. */
  11452. function Socket(io, nsp){
  11453. this.io = io;
  11454. this.nsp = nsp;
  11455. this.json = this; // compat
  11456. this.ids = 0;
  11457. this.acks = {};
  11458. if (this.io.autoConnect) this.open();
  11459. this.receiveBuffer = [];
  11460. this.sendBuffer = [];
  11461. this.connected = false;
  11462. this.disconnected = true;
  11463. }
  11464. /**
  11465. * Mix in `Emitter`.
  11466. */
  11467. Emitter(Socket.prototype);
  11468. /**
  11469. * Subscribe to open, close and packet events
  11470. *
  11471. * @api private
  11472. */
  11473. Socket.prototype.subEvents = function() {
  11474. if (this.subs) return;
  11475. var io = this.io;
  11476. this.subs = [
  11477. on(io, 'open', bind(this, 'onopen')),
  11478. on(io, 'packet', bind(this, 'onpacket')),
  11479. on(io, 'close', bind(this, 'onclose'))
  11480. ];
  11481. };
  11482. /**
  11483. * "Opens" the socket.
  11484. *
  11485. * @api public
  11486. */
  11487. Socket.prototype.open =
  11488. Socket.prototype.connect = function(){
  11489. if (this.connected) return this;
  11490. this.subEvents();
  11491. this.io.open(); // ensure open
  11492. if ('open' == this.io.readyState) this.onopen();
  11493. return this;
  11494. };
  11495. /**
  11496. * Sends a `message` event.
  11497. *
  11498. * @return {Socket} self
  11499. * @api public
  11500. */
  11501. Socket.prototype.send = function(){
  11502. var args = toArray(arguments);
  11503. args.unshift('message');
  11504. this.emit.apply(this, args);
  11505. return this;
  11506. };
  11507. /**
  11508. * Override `emit`.
  11509. * If the event is in `events`, it's emitted normally.
  11510. *
  11511. * @param {String} event name
  11512. * @return {Socket} self
  11513. * @api public
  11514. */
  11515. Socket.prototype.emit = function(ev){
  11516. if (events.hasOwnProperty(ev)) {
  11517. emit.apply(this, arguments);
  11518. return this;
  11519. }
  11520. var args = toArray(arguments);
  11521. var parserType = parser.EVENT; // default
  11522. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  11523. var packet = { type: parserType, data: args };
  11524. // event ack callback
  11525. if ('function' == typeof args[args.length - 1]) {
  11526. debug('emitting packet with ack id %d', this.ids);
  11527. this.acks[this.ids] = args.pop();
  11528. packet.id = this.ids++;
  11529. }
  11530. if (this.connected) {
  11531. this.packet(packet);
  11532. } else {
  11533. this.sendBuffer.push(packet);
  11534. }
  11535. return this;
  11536. };
  11537. /**
  11538. * Sends a packet.
  11539. *
  11540. * @param {Object} packet
  11541. * @api private
  11542. */
  11543. Socket.prototype.packet = function(packet){
  11544. packet.nsp = this.nsp;
  11545. this.io.packet(packet);
  11546. };
  11547. /**
  11548. * Called upon engine `open`.
  11549. *
  11550. * @api private
  11551. */
  11552. Socket.prototype.onopen = function(){
  11553. debug('transport is open - connecting');
  11554. // write connect packet if necessary
  11555. if ('/' != this.nsp) {
  11556. this.packet({ type: parser.CONNECT });
  11557. }
  11558. };
  11559. /**
  11560. * Called upon engine `close`.
  11561. *
  11562. * @param {String} reason
  11563. * @api private
  11564. */
  11565. Socket.prototype.onclose = function(reason){
  11566. debug('close (%s)', reason);
  11567. this.connected = false;
  11568. this.disconnected = true;
  11569. delete this.id;
  11570. this.emit('disconnect', reason);
  11571. };
  11572. /**
  11573. * Called with socket packet.
  11574. *
  11575. * @param {Object} packet
  11576. * @api private
  11577. */
  11578. Socket.prototype.onpacket = function(packet){
  11579. if (packet.nsp != this.nsp) return;
  11580. switch (packet.type) {
  11581. case parser.CONNECT:
  11582. this.onconnect();
  11583. break;
  11584. case parser.EVENT:
  11585. this.onevent(packet);
  11586. break;
  11587. case parser.BINARY_EVENT:
  11588. this.onevent(packet);
  11589. break;
  11590. case parser.ACK:
  11591. this.onack(packet);
  11592. break;
  11593. case parser.BINARY_ACK:
  11594. this.onack(packet);
  11595. break;
  11596. case parser.DISCONNECT:
  11597. this.ondisconnect();
  11598. break;
  11599. case parser.ERROR:
  11600. this.emit('error', packet.data);
  11601. break;
  11602. }
  11603. };
  11604. /**
  11605. * Called upon a server event.
  11606. *
  11607. * @param {Object} packet
  11608. * @api private
  11609. */
  11610. Socket.prototype.onevent = function(packet){
  11611. var args = packet.data || [];
  11612. debug('emitting event %j', args);
  11613. if (null != packet.id) {
  11614. debug('attaching ack callback to event');
  11615. args.push(this.ack(packet.id));
  11616. }
  11617. if (this.connected) {
  11618. emit.apply(this, args);
  11619. } else {
  11620. this.receiveBuffer.push(args);
  11621. }
  11622. };
  11623. /**
  11624. * Produces an ack callback to emit with an event.
  11625. *
  11626. * @api private
  11627. */
  11628. Socket.prototype.ack = function(id){
  11629. var self = this;
  11630. var sent = false;
  11631. return function(){
  11632. // prevent double callbacks
  11633. if (sent) return;
  11634. sent = true;
  11635. var args = toArray(arguments);
  11636. debug('sending ack %j', args);
  11637. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  11638. self.packet({
  11639. type: type,
  11640. id: id,
  11641. data: args
  11642. });
  11643. };
  11644. };
  11645. /**
  11646. * Called upon a server acknowlegement.
  11647. *
  11648. * @param {Object} packet
  11649. * @api private
  11650. */
  11651. Socket.prototype.onack = function(packet){
  11652. debug('calling ack %s with %j', packet.id, packet.data);
  11653. var fn = this.acks[packet.id];
  11654. fn.apply(this, packet.data);
  11655. delete this.acks[packet.id];
  11656. };
  11657. /**
  11658. * Called upon server connect.
  11659. *
  11660. * @api private
  11661. */
  11662. Socket.prototype.onconnect = function(){
  11663. this.connected = true;
  11664. this.disconnected = false;
  11665. this.emit('connect');
  11666. this.emitBuffered();
  11667. };
  11668. /**
  11669. * Emit buffered events (received and emitted).
  11670. *
  11671. * @api private
  11672. */
  11673. Socket.prototype.emitBuffered = function(){
  11674. var i;
  11675. for (i = 0; i < this.receiveBuffer.length; i++) {
  11676. emit.apply(this, this.receiveBuffer[i]);
  11677. }
  11678. this.receiveBuffer = [];
  11679. for (i = 0; i < this.sendBuffer.length; i++) {
  11680. this.packet(this.sendBuffer[i]);
  11681. }
  11682. this.sendBuffer = [];
  11683. };
  11684. /**
  11685. * Called upon server disconnect.
  11686. *
  11687. * @api private
  11688. */
  11689. Socket.prototype.ondisconnect = function(){
  11690. debug('server disconnect (%s)', this.nsp);
  11691. this.destroy();
  11692. this.onclose('io server disconnect');
  11693. };
  11694. /**
  11695. * Called upon forced client/server side disconnections,
  11696. * this method ensures the manager stops tracking us and
  11697. * that reconnections don't get triggered for this.
  11698. *
  11699. * @api private.
  11700. */
  11701. Socket.prototype.destroy = function(){
  11702. if (this.subs) {
  11703. // clean subscriptions to avoid reconnections
  11704. for (var i = 0; i < this.subs.length; i++) {
  11705. this.subs[i].destroy();
  11706. }
  11707. this.subs = null;
  11708. }
  11709. this.io.destroy(this);
  11710. };
  11711. /**
  11712. * Disconnects the socket manually.
  11713. *
  11714. * @return {Socket} self
  11715. * @api public
  11716. */
  11717. Socket.prototype.close =
  11718. Socket.prototype.disconnect = function(){
  11719. if (this.connected) {
  11720. debug('performing disconnect (%s)', this.nsp);
  11721. this.packet({ type: parser.DISCONNECT });
  11722. }
  11723. // remove socket from pool
  11724. this.destroy();
  11725. if (this.connected) {
  11726. // fire events
  11727. this.onclose('io client disconnect');
  11728. }
  11729. return this;
  11730. };
  11731. },{"./on":66,"component-bind":7,"component-emitter":8,"debug":69,"has-binary":41,"socket.io-parser":71,"to-array":75}],68:[function(require,module,exports){
  11732. (function (global){
  11733. /**
  11734. * Module dependencies.
  11735. */
  11736. var parseuri = require('parseuri');
  11737. var debug = require('debug')('socket.io-client:url');
  11738. /**
  11739. * Module exports.
  11740. */
  11741. module.exports = url;
  11742. /**
  11743. * URL parser.
  11744. *
  11745. * @param {String} url
  11746. * @param {Object} An object meant to mimic window.location.
  11747. * Defaults to window.location.
  11748. * @api public
  11749. */
  11750. function url(uri, loc){
  11751. var obj = uri;
  11752. // default to window.location
  11753. var loc = loc || global.location;
  11754. if (null == uri) uri = loc.protocol + '//' + loc.host;
  11755. // relative path support
  11756. if ('string' == typeof uri) {
  11757. if ('/' == uri.charAt(0)) {
  11758. if ('/' == uri.charAt(1)) {
  11759. uri = loc.protocol + uri;
  11760. } else {
  11761. uri = loc.hostname + uri;
  11762. }
  11763. }
  11764. if (!/^(https?|wss?):\/\//.test(uri)) {
  11765. debug('protocol-less url %s', uri);
  11766. if ('undefined' != typeof loc) {
  11767. uri = loc.protocol + '//' + uri;
  11768. } else {
  11769. uri = 'https://' + uri;
  11770. }
  11771. }
  11772. // parse
  11773. debug('parse %s', uri);
  11774. obj = parseuri(uri);
  11775. }
  11776. // make sure we treat `localhost:80` and `localhost` equally
  11777. if (!obj.port) {
  11778. if (/^(http|ws)$/.test(obj.protocol)) {
  11779. obj.port = '80';
  11780. }
  11781. else if (/^(http|ws)s$/.test(obj.protocol)) {
  11782. obj.port = '443';
  11783. }
  11784. }
  11785. obj.path = obj.path || '/';
  11786. // define unique id
  11787. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  11788. // define href
  11789. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  11790. return obj;
  11791. }
  11792. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11793. },{"debug":69,"parseuri":54}],69:[function(require,module,exports){
  11794. /**
  11795. * Expose `debug()` as the module.
  11796. */
  11797. module.exports = debug;
  11798. /**
  11799. * Create a debugger with the given `name`.
  11800. *
  11801. * @param {String} name
  11802. * @return {Type}
  11803. * @api public
  11804. */
  11805. function debug(name) {
  11806. if (!debug.enabled(name)) return function(){};
  11807. return function(fmt){
  11808. fmt = coerce(fmt);
  11809. var curr = new Date;
  11810. var ms = curr - (debug[name] || curr);
  11811. debug[name] = curr;
  11812. fmt = name
  11813. + ' '
  11814. + fmt
  11815. + ' +' + debug.humanize(ms);
  11816. // This hackery is required for IE8
  11817. // where `console.log` doesn't have 'apply'
  11818. window.console
  11819. && console.log
  11820. && Function.prototype.apply.call(console.log, console, arguments);
  11821. }
  11822. }
  11823. /**
  11824. * The currently active debug mode names.
  11825. */
  11826. debug.names = [];
  11827. debug.skips = [];
  11828. /**
  11829. * Enables a debug mode by name. This can include modes
  11830. * separated by a colon and wildcards.
  11831. *
  11832. * @param {String} name
  11833. * @api public
  11834. */
  11835. debug.enable = function(name) {
  11836. try {
  11837. localStorage.debug = name;
  11838. } catch(e){}
  11839. var split = (name || '').split(/[\s,]+/)
  11840. , len = split.length;
  11841. for (var i = 0; i < len; i++) {
  11842. name = split[i].replace('*', '.*?');
  11843. if (name[0] === '-') {
  11844. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  11845. }
  11846. else {
  11847. debug.names.push(new RegExp('^' + name + '$'));
  11848. }
  11849. }
  11850. };
  11851. /**
  11852. * Disable debug output.
  11853. *
  11854. * @api public
  11855. */
  11856. debug.disable = function(){
  11857. debug.enable('');
  11858. };
  11859. /**
  11860. * Humanize the given `ms`.
  11861. *
  11862. * @param {Number} m
  11863. * @return {String}
  11864. * @api private
  11865. */
  11866. debug.humanize = function(ms) {
  11867. var sec = 1000
  11868. , min = 60 * 1000
  11869. , hour = 60 * min;
  11870. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  11871. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  11872. if (ms >= sec) return (ms / sec | 0) + 's';
  11873. return ms + 'ms';
  11874. };
  11875. /**
  11876. * Returns true if the given mode name is enabled, false otherwise.
  11877. *
  11878. * @param {String} name
  11879. * @return {Boolean}
  11880. * @api public
  11881. */
  11882. debug.enabled = function(name) {
  11883. for (var i = 0, len = debug.skips.length; i < len; i++) {
  11884. if (debug.skips[i].test(name)) {
  11885. return false;
  11886. }
  11887. }
  11888. for (var i = 0, len = debug.names.length; i < len; i++) {
  11889. if (debug.names[i].test(name)) {
  11890. return true;
  11891. }
  11892. }
  11893. return false;
  11894. };
  11895. /**
  11896. * Coerce `val`.
  11897. */
  11898. function coerce(val) {
  11899. if (val instanceof Error) return val.stack || val.message;
  11900. return val;
  11901. }
  11902. // persist
  11903. try {
  11904. if (window.localStorage) debug.enable(localStorage.debug);
  11905. } catch(e){}
  11906. },{}],70:[function(require,module,exports){
  11907. (function (global){
  11908. /*global Blob,File*/
  11909. /**
  11910. * Module requirements
  11911. */
  11912. var isArray = require('isarray');
  11913. var isBuf = require('./is-buffer');
  11914. /**
  11915. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  11916. * Anything with blobs or files should be fed through removeBlobs before coming
  11917. * here.
  11918. *
  11919. * @param {Object} packet - socket.io event packet
  11920. * @return {Object} with deconstructed packet and list of buffers
  11921. * @api public
  11922. */
  11923. exports.deconstructPacket = function(packet){
  11924. var buffers = [];
  11925. var packetData = packet.data;
  11926. function _deconstructPacket(data) {
  11927. if (!data) return data;
  11928. if (isBuf(data)) {
  11929. var placeholder = { _placeholder: true, num: buffers.length };
  11930. buffers.push(data);
  11931. return placeholder;
  11932. } else if (isArray(data)) {
  11933. var newData = new Array(data.length);
  11934. for (var i = 0; i < data.length; i++) {
  11935. newData[i] = _deconstructPacket(data[i]);
  11936. }
  11937. return newData;
  11938. } else if ('object' == typeof data && !(data instanceof Date)) {
  11939. var newData = {};
  11940. for (var key in data) {
  11941. newData[key] = _deconstructPacket(data[key]);
  11942. }
  11943. return newData;
  11944. }
  11945. return data;
  11946. }
  11947. var pack = packet;
  11948. pack.data = _deconstructPacket(packetData);
  11949. pack.attachments = buffers.length; // number of binary 'attachments'
  11950. return {packet: pack, buffers: buffers};
  11951. };
  11952. /**
  11953. * Reconstructs a binary packet from its placeholder packet and buffers
  11954. *
  11955. * @param {Object} packet - event packet with placeholders
  11956. * @param {Array} buffers - binary buffers to put in placeholder positions
  11957. * @return {Object} reconstructed packet
  11958. * @api public
  11959. */
  11960. exports.reconstructPacket = function(packet, buffers) {
  11961. var curPlaceHolder = 0;
  11962. function _reconstructPacket(data) {
  11963. if (data && data._placeholder) {
  11964. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  11965. return buf;
  11966. } else if (isArray(data)) {
  11967. for (var i = 0; i < data.length; i++) {
  11968. data[i] = _reconstructPacket(data[i]);
  11969. }
  11970. return data;
  11971. } else if (data && 'object' == typeof data) {
  11972. for (var key in data) {
  11973. data[key] = _reconstructPacket(data[key]);
  11974. }
  11975. return data;
  11976. }
  11977. return data;
  11978. }
  11979. packet.data = _reconstructPacket(packet.data);
  11980. packet.attachments = undefined; // no longer useful
  11981. return packet;
  11982. };
  11983. /**
  11984. * Asynchronously removes Blobs or Files from data via
  11985. * FileReader's readAsArrayBuffer method. Used before encoding
  11986. * data as msgpack. Calls callback with the blobless data.
  11987. *
  11988. * @param {Object} data
  11989. * @param {Function} callback
  11990. * @api private
  11991. */
  11992. exports.removeBlobs = function(data, callback) {
  11993. function _removeBlobs(obj, curKey, containingObject) {
  11994. if (!obj) return obj;
  11995. // convert any blob
  11996. if ((global.Blob && obj instanceof Blob) ||
  11997. (global.File && obj instanceof File)) {
  11998. pendingBlobs++;
  11999. // async filereader
  12000. var fileReader = new FileReader();
  12001. fileReader.onload = function() { // this.result == arraybuffer
  12002. if (containingObject) {
  12003. containingObject[curKey] = this.result;
  12004. }
  12005. else {
  12006. bloblessData = this.result;
  12007. }
  12008. // if nothing pending its callback time
  12009. if(! --pendingBlobs) {
  12010. callback(bloblessData);
  12011. }
  12012. };
  12013. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  12014. } else if (isArray(obj)) { // handle array
  12015. for (var i = 0; i < obj.length; i++) {
  12016. _removeBlobs(obj[i], i, obj);
  12017. }
  12018. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  12019. for (var key in obj) {
  12020. _removeBlobs(obj[key], key, obj);
  12021. }
  12022. }
  12023. }
  12024. var pendingBlobs = 0;
  12025. var bloblessData = data;
  12026. _removeBlobs(bloblessData);
  12027. if (!pendingBlobs) {
  12028. callback(bloblessData);
  12029. }
  12030. };
  12031. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12032. },{"./is-buffer":72,"isarray":74}],71:[function(require,module,exports){
  12033. /**
  12034. * Module dependencies.
  12035. */
  12036. var debug = require('debug')('socket.io-parser');
  12037. var json = require('json3');
  12038. var isArray = require('isarray');
  12039. var Emitter = require('component-emitter');
  12040. var binary = require('./binary');
  12041. var isBuf = require('./is-buffer');
  12042. /**
  12043. * Protocol version.
  12044. *
  12045. * @api public
  12046. */
  12047. exports.protocol = 4;
  12048. /**
  12049. * Packet types.
  12050. *
  12051. * @api public
  12052. */
  12053. exports.types = [
  12054. 'CONNECT',
  12055. 'DISCONNECT',
  12056. 'EVENT',
  12057. 'BINARY_EVENT',
  12058. 'ACK',
  12059. 'BINARY_ACK',
  12060. 'ERROR'
  12061. ];
  12062. /**
  12063. * Packet type `connect`.
  12064. *
  12065. * @api public
  12066. */
  12067. exports.CONNECT = 0;
  12068. /**
  12069. * Packet type `disconnect`.
  12070. *
  12071. * @api public
  12072. */
  12073. exports.DISCONNECT = 1;
  12074. /**
  12075. * Packet type `event`.
  12076. *
  12077. * @api public
  12078. */
  12079. exports.EVENT = 2;
  12080. /**
  12081. * Packet type `ack`.
  12082. *
  12083. * @api public
  12084. */
  12085. exports.ACK = 3;
  12086. /**
  12087. * Packet type `error`.
  12088. *
  12089. * @api public
  12090. */
  12091. exports.ERROR = 4;
  12092. /**
  12093. * Packet type 'binary event'
  12094. *
  12095. * @api public
  12096. */
  12097. exports.BINARY_EVENT = 5;
  12098. /**
  12099. * Packet type `binary ack`. For acks with binary arguments.
  12100. *
  12101. * @api public
  12102. */
  12103. exports.BINARY_ACK = 6;
  12104. /**
  12105. * Encoder constructor.
  12106. *
  12107. * @api public
  12108. */
  12109. exports.Encoder = Encoder;
  12110. /**
  12111. * Decoder constructor.
  12112. *
  12113. * @api public
  12114. */
  12115. exports.Decoder = Decoder;
  12116. /**
  12117. * A socket.io Encoder instance
  12118. *
  12119. * @api public
  12120. */
  12121. function Encoder() {}
  12122. /**
  12123. * Encode a packet as a single string if non-binary, or as a
  12124. * buffer sequence, depending on packet type.
  12125. *
  12126. * @param {Object} obj - packet object
  12127. * @param {Function} callback - function to handle encodings (likely engine.write)
  12128. * @return Calls callback with Array of encodings
  12129. * @api public
  12130. */
  12131. Encoder.prototype.encode = function(obj, callback){
  12132. debug('encoding packet %j', obj);
  12133. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  12134. encodeAsBinary(obj, callback);
  12135. }
  12136. else {
  12137. var encoding = encodeAsString(obj);
  12138. callback([encoding]);
  12139. }
  12140. };
  12141. /**
  12142. * Encode packet as string.
  12143. *
  12144. * @param {Object} packet
  12145. * @return {String} encoded
  12146. * @api private
  12147. */
  12148. function encodeAsString(obj) {
  12149. var str = '';
  12150. var nsp = false;
  12151. // first is type
  12152. str += obj.type;
  12153. // attachments if we have them
  12154. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  12155. str += obj.attachments;
  12156. str += '-';
  12157. }
  12158. // if we have a namespace other than `/`
  12159. // we append it followed by a comma `,`
  12160. if (obj.nsp && '/' != obj.nsp) {
  12161. nsp = true;
  12162. str += obj.nsp;
  12163. }
  12164. // immediately followed by the id
  12165. if (null != obj.id) {
  12166. if (nsp) {
  12167. str += ',';
  12168. nsp = false;
  12169. }
  12170. str += obj.id;
  12171. }
  12172. // json data
  12173. if (null != obj.data) {
  12174. if (nsp) str += ',';
  12175. str += json.stringify(obj.data);
  12176. }
  12177. debug('encoded %j as %s', obj, str);
  12178. return str;
  12179. }
  12180. /**
  12181. * Encode packet as 'buffer sequence' by removing blobs, and
  12182. * deconstructing packet into object with placeholders and
  12183. * a list of buffers.
  12184. *
  12185. * @param {Object} packet
  12186. * @return {Buffer} encoded
  12187. * @api private
  12188. */
  12189. function encodeAsBinary(obj, callback) {
  12190. function writeEncoding(bloblessData) {
  12191. var deconstruction = binary.deconstructPacket(bloblessData);
  12192. var pack = encodeAsString(deconstruction.packet);
  12193. var buffers = deconstruction.buffers;
  12194. buffers.unshift(pack); // add packet info to beginning of data list
  12195. callback(buffers); // write all the buffers
  12196. }
  12197. binary.removeBlobs(obj, writeEncoding);
  12198. }
  12199. /**
  12200. * A socket.io Decoder instance
  12201. *
  12202. * @return {Object} decoder
  12203. * @api public
  12204. */
  12205. function Decoder() {
  12206. this.reconstructor = null;
  12207. }
  12208. /**
  12209. * Mix in `Emitter` with Decoder.
  12210. */
  12211. Emitter(Decoder.prototype);
  12212. /**
  12213. * Decodes an ecoded packet string into packet JSON.
  12214. *
  12215. * @param {String} obj - encoded packet
  12216. * @return {Object} packet
  12217. * @api public
  12218. */
  12219. Decoder.prototype.add = function(obj) {
  12220. var packet;
  12221. if ('string' == typeof obj) {
  12222. packet = decodeString(obj);
  12223. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  12224. this.reconstructor = new BinaryReconstructor(packet);
  12225. // no attachments, labeled binary but no binary data to follow
  12226. if (this.reconstructor.reconPack.attachments === 0) {
  12227. this.emit('decoded', packet);
  12228. }
  12229. } else { // non-binary full packet
  12230. this.emit('decoded', packet);
  12231. }
  12232. }
  12233. else if (isBuf(obj) || obj.base64) { // raw binary data
  12234. if (!this.reconstructor) {
  12235. throw new Error('got binary data when not reconstructing a packet');
  12236. } else {
  12237. packet = this.reconstructor.takeBinaryData(obj);
  12238. if (packet) { // received final buffer
  12239. this.reconstructor = null;
  12240. this.emit('decoded', packet);
  12241. }
  12242. }
  12243. }
  12244. else {
  12245. throw new Error('Unknown type: ' + obj);
  12246. }
  12247. };
  12248. /**
  12249. * Decode a packet String (JSON data)
  12250. *
  12251. * @param {String} str
  12252. * @return {Object} packet
  12253. * @api private
  12254. */
  12255. function decodeString(str) {
  12256. var p = {};
  12257. var i = 0;
  12258. // look up type
  12259. p.type = Number(str.charAt(0));
  12260. if (null == exports.types[p.type]) return error();
  12261. // look up attachments if type binary
  12262. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  12263. var buf = '';
  12264. while (str.charAt(++i) != '-') {
  12265. buf += str.charAt(i);
  12266. if (i == str.length) break;
  12267. }
  12268. if (buf != Number(buf) || str.charAt(i) != '-') {
  12269. throw new Error('Illegal attachments');
  12270. }
  12271. p.attachments = Number(buf);
  12272. }
  12273. // look up namespace (if any)
  12274. if ('/' == str.charAt(i + 1)) {
  12275. p.nsp = '';
  12276. while (++i) {
  12277. var c = str.charAt(i);
  12278. if (',' == c) break;
  12279. p.nsp += c;
  12280. if (i == str.length) break;
  12281. }
  12282. } else {
  12283. p.nsp = '/';
  12284. }
  12285. // look up id
  12286. var next = str.charAt(i + 1);
  12287. if ('' !== next && Number(next) == next) {
  12288. p.id = '';
  12289. while (++i) {
  12290. var c = str.charAt(i);
  12291. if (null == c || Number(c) != c) {
  12292. --i;
  12293. break;
  12294. }
  12295. p.id += str.charAt(i);
  12296. if (i == str.length) break;
  12297. }
  12298. p.id = Number(p.id);
  12299. }
  12300. // look up json data
  12301. if (str.charAt(++i)) {
  12302. try {
  12303. p.data = json.parse(str.substr(i));
  12304. } catch(e){
  12305. return error();
  12306. }
  12307. }
  12308. debug('decoded %s as %j', str, p);
  12309. return p;
  12310. }
  12311. /**
  12312. * Deallocates a parser's resources
  12313. *
  12314. * @api public
  12315. */
  12316. Decoder.prototype.destroy = function() {
  12317. if (this.reconstructor) {
  12318. this.reconstructor.finishedReconstruction();
  12319. }
  12320. };
  12321. /**
  12322. * A manager of a binary event's 'buffer sequence'. Should
  12323. * be constructed whenever a packet of type BINARY_EVENT is
  12324. * decoded.
  12325. *
  12326. * @param {Object} packet
  12327. * @return {BinaryReconstructor} initialized reconstructor
  12328. * @api private
  12329. */
  12330. function BinaryReconstructor(packet) {
  12331. this.reconPack = packet;
  12332. this.buffers = [];
  12333. }
  12334. /**
  12335. * Method to be called when binary data received from connection
  12336. * after a BINARY_EVENT packet.
  12337. *
  12338. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  12339. * @return {null | Object} returns null if more binary data is expected or
  12340. * a reconstructed packet object if all buffers have been received.
  12341. * @api private
  12342. */
  12343. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  12344. this.buffers.push(binData);
  12345. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  12346. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  12347. this.finishedReconstruction();
  12348. return packet;
  12349. }
  12350. return null;
  12351. };
  12352. /**
  12353. * Cleans up binary packet reconstruction variables.
  12354. *
  12355. * @api private
  12356. */
  12357. BinaryReconstructor.prototype.finishedReconstruction = function() {
  12358. this.reconPack = null;
  12359. this.buffers = [];
  12360. };
  12361. function error(data){
  12362. return {
  12363. type: exports.ERROR,
  12364. data: 'parser error'
  12365. };
  12366. }
  12367. },{"./binary":70,"./is-buffer":72,"component-emitter":8,"debug":73,"isarray":74,"json3":45}],72:[function(require,module,exports){
  12368. (function (global){
  12369. module.exports = isBuf;
  12370. /**
  12371. * Returns true if obj is a buffer or an arraybuffer.
  12372. *
  12373. * @api private
  12374. */
  12375. function isBuf(obj) {
  12376. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  12377. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  12378. }
  12379. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12380. },{}],73:[function(require,module,exports){
  12381. arguments[4][69][0].apply(exports,arguments)
  12382. },{"dup":69}],74:[function(require,module,exports){
  12383. arguments[4][42][0].apply(exports,arguments)
  12384. },{"dup":42}],75:[function(require,module,exports){
  12385. module.exports = toArray
  12386. function toArray(list, index) {
  12387. var array = []
  12388. index = index || 0
  12389. for (var i = index || 0; i < list.length; i++) {
  12390. array[i - index] = list[i]
  12391. }
  12392. return array
  12393. }
  12394. },{}],76:[function(require,module,exports){
  12395. // based on https://github.com/ESTOS/strophe.jingle/
  12396. // adds wildemitter support
  12397. var util = require('util');
  12398. var adapter = require('webrtc-adapter'); // jshint ignore:line
  12399. var WildEmitter = require('wildemitter');
  12400. function dumpSDP(description) {
  12401. return {
  12402. type: description.type,
  12403. sdp: description.sdp
  12404. };
  12405. }
  12406. function dumpStream(stream) {
  12407. var info = {
  12408. label: stream.id,
  12409. };
  12410. if (stream.getAudioTracks().length) {
  12411. info.audio = stream.getAudioTracks().map(function (track) {
  12412. return track.id;
  12413. });
  12414. }
  12415. if (stream.getVideoTracks().length) {
  12416. info.video = stream.getVideoTracks().map(function (track) {
  12417. return track.id;
  12418. });
  12419. }
  12420. return info;
  12421. }
  12422. function TraceablePeerConnection(config, constraints) {
  12423. var self = this;
  12424. WildEmitter.call(this);
  12425. this.peerconnection = new window.RTCPeerConnection(config, constraints);
  12426. this.trace = function (what, info) {
  12427. self.emit('PeerConnectionTrace', {
  12428. time: new Date(),
  12429. type: what,
  12430. value: info || ""
  12431. });
  12432. };
  12433. this.onicecandidate = null;
  12434. this.peerconnection.onicecandidate = function (event) {
  12435. self.trace('onicecandidate', event.candidate);
  12436. if (self.onicecandidate !== null) {
  12437. self.onicecandidate(event);
  12438. }
  12439. };
  12440. this.onaddstream = null;
  12441. this.peerconnection.onaddstream = function (event) {
  12442. self.trace('onaddstream', dumpStream(event.stream));
  12443. if (self.onaddstream !== null) {
  12444. self.onaddstream(event);
  12445. }
  12446. };
  12447. this.onremovestream = null;
  12448. this.peerconnection.onremovestream = function (event) {
  12449. self.trace('onremovestream', dumpStream(event.stream));
  12450. if (self.onremovestream !== null) {
  12451. self.onremovestream(event);
  12452. }
  12453. };
  12454. this.onsignalingstatechange = null;
  12455. this.peerconnection.onsignalingstatechange = function (event) {
  12456. self.trace('onsignalingstatechange', self.signalingState);
  12457. if (self.onsignalingstatechange !== null) {
  12458. self.onsignalingstatechange(event);
  12459. }
  12460. };
  12461. this.oniceconnectionstatechange = null;
  12462. this.peerconnection.oniceconnectionstatechange = function (event) {
  12463. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12464. if (self.oniceconnectionstatechange !== null) {
  12465. self.oniceconnectionstatechange(event);
  12466. }
  12467. };
  12468. this.onnegotiationneeded = null;
  12469. this.peerconnection.onnegotiationneeded = function (event) {
  12470. self.trace('onnegotiationneeded');
  12471. if (self.onnegotiationneeded !== null) {
  12472. self.onnegotiationneeded(event);
  12473. }
  12474. };
  12475. self.ondatachannel = null;
  12476. this.peerconnection.ondatachannel = function (event) {
  12477. self.trace('ondatachannel', event);
  12478. if (self.ondatachannel !== null) {
  12479. self.ondatachannel(event);
  12480. }
  12481. };
  12482. this.getLocalStreams = this.peerconnection.getLocalStreams.bind(this.peerconnection);
  12483. this.getRemoteStreams = this.peerconnection.getRemoteStreams.bind(this.peerconnection);
  12484. }
  12485. util.inherits(TraceablePeerConnection, WildEmitter);
  12486. ['signalingState', 'iceConnectionState', 'localDescription', 'remoteDescription'].forEach(function (prop) {
  12487. Object.defineProperty(TraceablePeerConnection.prototype, prop, {
  12488. get: function () {
  12489. return this.peerconnection[prop];
  12490. }
  12491. });
  12492. });
  12493. TraceablePeerConnection.prototype.addStream = function (stream) {
  12494. this.trace('addStream', dumpStream(stream));
  12495. this.peerconnection.addStream(stream);
  12496. };
  12497. TraceablePeerConnection.prototype.removeStream = function (stream) {
  12498. this.trace('removeStream', dumpStream(stream));
  12499. this.peerconnection.removeStream(stream);
  12500. };
  12501. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12502. this.trace('createDataChannel', label, opts);
  12503. return this.peerconnection.createDataChannel(label, opts);
  12504. };
  12505. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12506. var self = this;
  12507. this.trace('setLocalDescription', dumpSDP(description));
  12508. return this.peerconnection.setLocalDescription(
  12509. description
  12510. ).then(
  12511. function () {
  12512. self.trace('setLocalDescriptionOnSuccess');
  12513. if (successCallback) successCallback();
  12514. },
  12515. function (err) {
  12516. self.trace('setLocalDescriptionOnFailure', err);
  12517. if (failureCallback) failureCallback(err);
  12518. }
  12519. );
  12520. };
  12521. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12522. var self = this;
  12523. this.trace('setRemoteDescription', dumpSDP(description));
  12524. return this.peerconnection.setRemoteDescription(
  12525. description
  12526. ).then(
  12527. function () {
  12528. self.trace('setRemoteDescriptionOnSuccess');
  12529. if (successCallback) successCallback();
  12530. },
  12531. function (err) {
  12532. self.trace('setRemoteDescriptionOnFailure', err);
  12533. if (failureCallback) failureCallback(err);
  12534. }
  12535. );
  12536. };
  12537. TraceablePeerConnection.prototype.close = function () {
  12538. this.trace('stop');
  12539. if (this.peerconnection.signalingState != 'closed') {
  12540. this.peerconnection.close();
  12541. }
  12542. };
  12543. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12544. var self = this;
  12545. this.trace('createOffer', constraints);
  12546. return this.peerconnection.createOffer(
  12547. constraints
  12548. ).then(
  12549. function (offer) {
  12550. self.trace('createOfferOnSuccess', dumpSDP(offer));
  12551. if (successCallback) successCallback(offer);
  12552. },
  12553. function (err) {
  12554. self.trace('createOfferOnFailure', err);
  12555. if (failureCallback) failureCallback(err);
  12556. }
  12557. );
  12558. };
  12559. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12560. var self = this;
  12561. this.trace('createAnswer', constraints);
  12562. return this.peerconnection.createAnswer(
  12563. constraints
  12564. ).then(
  12565. function (answer) {
  12566. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  12567. if (successCallback) successCallback(answer);
  12568. },
  12569. function (err) {
  12570. self.trace('createAnswerOnFailure', err);
  12571. if (failureCallback) failureCallback(err);
  12572. }
  12573. );
  12574. };
  12575. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12576. var self = this;
  12577. this.trace('addIceCandidate', candidate);
  12578. return this.peerconnection.addIceCandidate(
  12579. candidate
  12580. ).then(
  12581. function () {
  12582. //self.trace('addIceCandidateOnSuccess');
  12583. if (successCallback) successCallback();
  12584. },
  12585. function (err) {
  12586. self.trace('addIceCandidateOnFailure', err);
  12587. if (failureCallback) failureCallback(err);
  12588. }
  12589. );
  12590. };
  12591. TraceablePeerConnection.prototype.getStats = function () {
  12592. this.peerconnection.getStats.apply(this.peerconnection, arguments);
  12593. };
  12594. module.exports = TraceablePeerConnection;
  12595. },{"util":89,"webrtc-adapter":77,"wildemitter":100}],77:[function(require,module,exports){
  12596. arguments[4][30][0].apply(exports,arguments)
  12597. },{"./chrome/chrome_shim":78,"./edge/edge_shim":80,"./firefox/firefox_shim":82,"./safari/safari_shim":84,"./utils":85,"dup":30}],78:[function(require,module,exports){
  12598. arguments[4][31][0].apply(exports,arguments)
  12599. },{"../utils.js":85,"./getusermedia":79,"dup":31}],79:[function(require,module,exports){
  12600. arguments[4][32][0].apply(exports,arguments)
  12601. },{"../utils.js":85,"dup":32}],80:[function(require,module,exports){
  12602. arguments[4][33][0].apply(exports,arguments)
  12603. },{"../utils":85,"./getusermedia":81,"dup":33,"sdp":62}],81:[function(require,module,exports){
  12604. arguments[4][34][0].apply(exports,arguments)
  12605. },{"dup":34}],82:[function(require,module,exports){
  12606. arguments[4][35][0].apply(exports,arguments)
  12607. },{"../utils":85,"./getusermedia":83,"dup":35}],83:[function(require,module,exports){
  12608. arguments[4][36][0].apply(exports,arguments)
  12609. },{"../utils":85,"dup":36}],84:[function(require,module,exports){
  12610. arguments[4][37][0].apply(exports,arguments)
  12611. },{"dup":37}],85:[function(require,module,exports){
  12612. arguments[4][38][0].apply(exports,arguments)
  12613. },{"dup":38}],86:[function(require,module,exports){
  12614. (function (global){
  12615. /*! https://mths.be/utf8js v2.0.0 by @mathias */
  12616. ;(function(root) {
  12617. // Detect free variables `exports`
  12618. var freeExports = typeof exports == 'object' && exports;
  12619. // Detect free variable `module`
  12620. var freeModule = typeof module == 'object' && module &&
  12621. module.exports == freeExports && module;
  12622. // Detect free variable `global`, from Node.js or Browserified code,
  12623. // and use it as `root`
  12624. var freeGlobal = typeof global == 'object' && global;
  12625. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  12626. root = freeGlobal;
  12627. }
  12628. /*--------------------------------------------------------------------------*/
  12629. var stringFromCharCode = String.fromCharCode;
  12630. // Taken from https://mths.be/punycode
  12631. function ucs2decode(string) {
  12632. var output = [];
  12633. var counter = 0;
  12634. var length = string.length;
  12635. var value;
  12636. var extra;
  12637. while (counter < length) {
  12638. value = string.charCodeAt(counter++);
  12639. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  12640. // high surrogate, and there is a next character
  12641. extra = string.charCodeAt(counter++);
  12642. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  12643. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  12644. } else {
  12645. // unmatched surrogate; only append this code unit, in case the next
  12646. // code unit is the high surrogate of a surrogate pair
  12647. output.push(value);
  12648. counter--;
  12649. }
  12650. } else {
  12651. output.push(value);
  12652. }
  12653. }
  12654. return output;
  12655. }
  12656. // Taken from https://mths.be/punycode
  12657. function ucs2encode(array) {
  12658. var length = array.length;
  12659. var index = -1;
  12660. var value;
  12661. var output = '';
  12662. while (++index < length) {
  12663. value = array[index];
  12664. if (value > 0xFFFF) {
  12665. value -= 0x10000;
  12666. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  12667. value = 0xDC00 | value & 0x3FF;
  12668. }
  12669. output += stringFromCharCode(value);
  12670. }
  12671. return output;
  12672. }
  12673. function checkScalarValue(codePoint) {
  12674. if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
  12675. throw Error(
  12676. 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
  12677. ' is not a scalar value'
  12678. );
  12679. }
  12680. }
  12681. /*--------------------------------------------------------------------------*/
  12682. function createByte(codePoint, shift) {
  12683. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  12684. }
  12685. function encodeCodePoint(codePoint) {
  12686. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  12687. return stringFromCharCode(codePoint);
  12688. }
  12689. var symbol = '';
  12690. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  12691. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  12692. }
  12693. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  12694. checkScalarValue(codePoint);
  12695. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  12696. symbol += createByte(codePoint, 6);
  12697. }
  12698. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  12699. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  12700. symbol += createByte(codePoint, 12);
  12701. symbol += createByte(codePoint, 6);
  12702. }
  12703. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  12704. return symbol;
  12705. }
  12706. function utf8encode(string) {
  12707. var codePoints = ucs2decode(string);
  12708. var length = codePoints.length;
  12709. var index = -1;
  12710. var codePoint;
  12711. var byteString = '';
  12712. while (++index < length) {
  12713. codePoint = codePoints[index];
  12714. byteString += encodeCodePoint(codePoint);
  12715. }
  12716. return byteString;
  12717. }
  12718. /*--------------------------------------------------------------------------*/
  12719. function readContinuationByte() {
  12720. if (byteIndex >= byteCount) {
  12721. throw Error('Invalid byte index');
  12722. }
  12723. var continuationByte = byteArray[byteIndex] & 0xFF;
  12724. byteIndex++;
  12725. if ((continuationByte & 0xC0) == 0x80) {
  12726. return continuationByte & 0x3F;
  12727. }
  12728. // If we end up here, it’s not a continuation byte
  12729. throw Error('Invalid continuation byte');
  12730. }
  12731. function decodeSymbol() {
  12732. var byte1;
  12733. var byte2;
  12734. var byte3;
  12735. var byte4;
  12736. var codePoint;
  12737. if (byteIndex > byteCount) {
  12738. throw Error('Invalid byte index');
  12739. }
  12740. if (byteIndex == byteCount) {
  12741. return false;
  12742. }
  12743. // Read first byte
  12744. byte1 = byteArray[byteIndex] & 0xFF;
  12745. byteIndex++;
  12746. // 1-byte sequence (no continuation bytes)
  12747. if ((byte1 & 0x80) == 0) {
  12748. return byte1;
  12749. }
  12750. // 2-byte sequence
  12751. if ((byte1 & 0xE0) == 0xC0) {
  12752. var byte2 = readContinuationByte();
  12753. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  12754. if (codePoint >= 0x80) {
  12755. return codePoint;
  12756. } else {
  12757. throw Error('Invalid continuation byte');
  12758. }
  12759. }
  12760. // 3-byte sequence (may include unpaired surrogates)
  12761. if ((byte1 & 0xF0) == 0xE0) {
  12762. byte2 = readContinuationByte();
  12763. byte3 = readContinuationByte();
  12764. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  12765. if (codePoint >= 0x0800) {
  12766. checkScalarValue(codePoint);
  12767. return codePoint;
  12768. } else {
  12769. throw Error('Invalid continuation byte');
  12770. }
  12771. }
  12772. // 4-byte sequence
  12773. if ((byte1 & 0xF8) == 0xF0) {
  12774. byte2 = readContinuationByte();
  12775. byte3 = readContinuationByte();
  12776. byte4 = readContinuationByte();
  12777. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  12778. (byte3 << 0x06) | byte4;
  12779. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  12780. return codePoint;
  12781. }
  12782. }
  12783. throw Error('Invalid UTF-8 detected');
  12784. }
  12785. var byteArray;
  12786. var byteCount;
  12787. var byteIndex;
  12788. function utf8decode(byteString) {
  12789. byteArray = ucs2decode(byteString);
  12790. byteCount = byteArray.length;
  12791. byteIndex = 0;
  12792. var codePoints = [];
  12793. var tmp;
  12794. while ((tmp = decodeSymbol()) !== false) {
  12795. codePoints.push(tmp);
  12796. }
  12797. return ucs2encode(codePoints);
  12798. }
  12799. /*--------------------------------------------------------------------------*/
  12800. var utf8 = {
  12801. 'version': '2.0.0',
  12802. 'encode': utf8encode,
  12803. 'decode': utf8decode
  12804. };
  12805. // Some AMD build optimizers, like r.js, check for specific condition patterns
  12806. // like the following:
  12807. if (
  12808. typeof define == 'function' &&
  12809. typeof define.amd == 'object' &&
  12810. define.amd
  12811. ) {
  12812. define(function() {
  12813. return utf8;
  12814. });
  12815. } else if (freeExports && !freeExports.nodeType) {
  12816. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  12817. freeModule.exports = utf8;
  12818. } else { // in Narwhal or RingoJS v0.7.0-
  12819. var object = {};
  12820. var hasOwnProperty = object.hasOwnProperty;
  12821. for (var key in utf8) {
  12822. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  12823. }
  12824. }
  12825. } else { // in Rhino or a web browser
  12826. root.utf8 = utf8;
  12827. }
  12828. }(this));
  12829. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  12830. },{}],87:[function(require,module,exports){
  12831. if (typeof Object.create === 'function') {
  12832. // implementation from standard node.js 'util' module
  12833. module.exports = function inherits(ctor, superCtor) {
  12834. ctor.super_ = superCtor
  12835. ctor.prototype = Object.create(superCtor.prototype, {
  12836. constructor: {
  12837. value: ctor,
  12838. enumerable: false,
  12839. writable: true,
  12840. configurable: true
  12841. }
  12842. });
  12843. };
  12844. } else {
  12845. // old school shim for old browsers
  12846. module.exports = function inherits(ctor, superCtor) {
  12847. ctor.super_ = superCtor
  12848. var TempCtor = function () {}
  12849. TempCtor.prototype = superCtor.prototype
  12850. ctor.prototype = new TempCtor()
  12851. ctor.prototype.constructor = ctor
  12852. }
  12853. }
  12854. },{}],88:[function(require,module,exports){
  12855. module.exports = function isBuffer(arg) {
  12856. return arg && typeof arg === 'object'
  12857. && typeof arg.copy === 'function'
  12858. && typeof arg.fill === 'function'
  12859. && typeof arg.readUInt8 === 'function';
  12860. }
  12861. },{}],89:[function(require,module,exports){
  12862. (function (process,global){
  12863. // Copyright Joyent, Inc. and other Node contributors.
  12864. //
  12865. // Permission is hereby granted, free of charge, to any person obtaining a
  12866. // copy of this software and associated documentation files (the
  12867. // "Software"), to deal in the Software without restriction, including
  12868. // without limitation the rights to use, copy, modify, merge, publish,
  12869. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12870. // persons to whom the Software is furnished to do so, subject to the
  12871. // following conditions:
  12872. //
  12873. // The above copyright notice and this permission notice shall be included
  12874. // in all copies or substantial portions of the Software.
  12875. //
  12876. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  12877. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  12878. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  12879. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  12880. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  12881. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  12882. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  12883. var formatRegExp = /%[sdj%]/g;
  12884. exports.format = function(f) {
  12885. if (!isString(f)) {
  12886. var objects = [];
  12887. for (var i = 0; i < arguments.length; i++) {
  12888. objects.push(inspect(arguments[i]));
  12889. }
  12890. return objects.join(' ');
  12891. }
  12892. var i = 1;
  12893. var args = arguments;
  12894. var len = args.length;
  12895. var str = String(f).replace(formatRegExp, function(x) {
  12896. if (x === '%%') return '%';
  12897. if (i >= len) return x;
  12898. switch (x) {
  12899. case '%s': return String(args[i++]);
  12900. case '%d': return Number(args[i++]);
  12901. case '%j':
  12902. try {
  12903. return JSON.stringify(args[i++]);
  12904. } catch (_) {
  12905. return '[Circular]';
  12906. }
  12907. default:
  12908. return x;
  12909. }
  12910. });
  12911. for (var x = args[i]; i < len; x = args[++i]) {
  12912. if (isNull(x) || !isObject(x)) {
  12913. str += ' ' + x;
  12914. } else {
  12915. str += ' ' + inspect(x);
  12916. }
  12917. }
  12918. return str;
  12919. };
  12920. // Mark that a method should not be used.
  12921. // Returns a modified function which warns once by default.
  12922. // If --no-deprecation is set, then it is a no-op.
  12923. exports.deprecate = function(fn, msg) {
  12924. // Allow for deprecating things in the process of starting up.
  12925. if (isUndefined(global.process)) {
  12926. return function() {
  12927. return exports.deprecate(fn, msg).apply(this, arguments);
  12928. };
  12929. }
  12930. if (process.noDeprecation === true) {
  12931. return fn;
  12932. }
  12933. var warned = false;
  12934. function deprecated() {
  12935. if (!warned) {
  12936. if (process.throwDeprecation) {
  12937. throw new Error(msg);
  12938. } else if (process.traceDeprecation) {
  12939. console.trace(msg);
  12940. } else {
  12941. console.error(msg);
  12942. }
  12943. warned = true;
  12944. }
  12945. return fn.apply(this, arguments);
  12946. }
  12947. return deprecated;
  12948. };
  12949. var debugs = {};
  12950. var debugEnviron;
  12951. exports.debuglog = function(set) {
  12952. if (isUndefined(debugEnviron))
  12953. debugEnviron = process.env.NODE_DEBUG || '';
  12954. set = set.toUpperCase();
  12955. if (!debugs[set]) {
  12956. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  12957. var pid = process.pid;
  12958. debugs[set] = function() {
  12959. var msg = exports.format.apply(exports, arguments);
  12960. console.error('%s %d: %s', set, pid, msg);
  12961. };
  12962. } else {
  12963. debugs[set] = function() {};
  12964. }
  12965. }
  12966. return debugs[set];
  12967. };
  12968. /**
  12969. * Echos the value of a value. Trys to print the value out
  12970. * in the best way possible given the different types.
  12971. *
  12972. * @param {Object} obj The object to print out.
  12973. * @param {Object} opts Optional options object that alters the output.
  12974. */
  12975. /* legacy: obj, showHidden, depth, colors*/
  12976. function inspect(obj, opts) {
  12977. // default options
  12978. var ctx = {
  12979. seen: [],
  12980. stylize: stylizeNoColor
  12981. };
  12982. // legacy...
  12983. if (arguments.length >= 3) ctx.depth = arguments[2];
  12984. if (arguments.length >= 4) ctx.colors = arguments[3];
  12985. if (isBoolean(opts)) {
  12986. // legacy...
  12987. ctx.showHidden = opts;
  12988. } else if (opts) {
  12989. // got an "options" object
  12990. exports._extend(ctx, opts);
  12991. }
  12992. // set default options
  12993. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  12994. if (isUndefined(ctx.depth)) ctx.depth = 2;
  12995. if (isUndefined(ctx.colors)) ctx.colors = false;
  12996. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  12997. if (ctx.colors) ctx.stylize = stylizeWithColor;
  12998. return formatValue(ctx, obj, ctx.depth);
  12999. }
  13000. exports.inspect = inspect;
  13001. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  13002. inspect.colors = {
  13003. 'bold' : [1, 22],
  13004. 'italic' : [3, 23],
  13005. 'underline' : [4, 24],
  13006. 'inverse' : [7, 27],
  13007. 'white' : [37, 39],
  13008. 'grey' : [90, 39],
  13009. 'black' : [30, 39],
  13010. 'blue' : [34, 39],
  13011. 'cyan' : [36, 39],
  13012. 'green' : [32, 39],
  13013. 'magenta' : [35, 39],
  13014. 'red' : [31, 39],
  13015. 'yellow' : [33, 39]
  13016. };
  13017. // Don't use 'blue' not visible on cmd.exe
  13018. inspect.styles = {
  13019. 'special': 'cyan',
  13020. 'number': 'yellow',
  13021. 'boolean': 'yellow',
  13022. 'undefined': 'grey',
  13023. 'null': 'bold',
  13024. 'string': 'green',
  13025. 'date': 'magenta',
  13026. // "name": intentionally not styling
  13027. 'regexp': 'red'
  13028. };
  13029. function stylizeWithColor(str, styleType) {
  13030. var style = inspect.styles[styleType];
  13031. if (style) {
  13032. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  13033. '\u001b[' + inspect.colors[style][1] + 'm';
  13034. } else {
  13035. return str;
  13036. }
  13037. }
  13038. function stylizeNoColor(str, styleType) {
  13039. return str;
  13040. }
  13041. function arrayToHash(array) {
  13042. var hash = {};
  13043. array.forEach(function(val, idx) {
  13044. hash[val] = true;
  13045. });
  13046. return hash;
  13047. }
  13048. function formatValue(ctx, value, recurseTimes) {
  13049. // Provide a hook for user-specified inspect functions.
  13050. // Check that value is an object with an inspect function on it
  13051. if (ctx.customInspect &&
  13052. value &&
  13053. isFunction(value.inspect) &&
  13054. // Filter out the util module, it's inspect function is special
  13055. value.inspect !== exports.inspect &&
  13056. // Also filter out any prototype objects using the circular check.
  13057. !(value.constructor && value.constructor.prototype === value)) {
  13058. var ret = value.inspect(recurseTimes, ctx);
  13059. if (!isString(ret)) {
  13060. ret = formatValue(ctx, ret, recurseTimes);
  13061. }
  13062. return ret;
  13063. }
  13064. // Primitive types cannot have properties
  13065. var primitive = formatPrimitive(ctx, value);
  13066. if (primitive) {
  13067. return primitive;
  13068. }
  13069. // Look up the keys of the object.
  13070. var keys = Object.keys(value);
  13071. var visibleKeys = arrayToHash(keys);
  13072. if (ctx.showHidden) {
  13073. keys = Object.getOwnPropertyNames(value);
  13074. }
  13075. // IE doesn't make error fields non-enumerable
  13076. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  13077. if (isError(value)
  13078. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  13079. return formatError(value);
  13080. }
  13081. // Some type of object without properties can be shortcutted.
  13082. if (keys.length === 0) {
  13083. if (isFunction(value)) {
  13084. var name = value.name ? ': ' + value.name : '';
  13085. return ctx.stylize('[Function' + name + ']', 'special');
  13086. }
  13087. if (isRegExp(value)) {
  13088. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  13089. }
  13090. if (isDate(value)) {
  13091. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  13092. }
  13093. if (isError(value)) {
  13094. return formatError(value);
  13095. }
  13096. }
  13097. var base = '', array = false, braces = ['{', '}'];
  13098. // Make Array say that they are Array
  13099. if (isArray(value)) {
  13100. array = true;
  13101. braces = ['[', ']'];
  13102. }
  13103. // Make functions say that they are functions
  13104. if (isFunction(value)) {
  13105. var n = value.name ? ': ' + value.name : '';
  13106. base = ' [Function' + n + ']';
  13107. }
  13108. // Make RegExps say that they are RegExps
  13109. if (isRegExp(value)) {
  13110. base = ' ' + RegExp.prototype.toString.call(value);
  13111. }
  13112. // Make dates with properties first say the date
  13113. if (isDate(value)) {
  13114. base = ' ' + Date.prototype.toUTCString.call(value);
  13115. }
  13116. // Make error with message first say the error
  13117. if (isError(value)) {
  13118. base = ' ' + formatError(value);
  13119. }
  13120. if (keys.length === 0 && (!array || value.length == 0)) {
  13121. return braces[0] + base + braces[1];
  13122. }
  13123. if (recurseTimes < 0) {
  13124. if (isRegExp(value)) {
  13125. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  13126. } else {
  13127. return ctx.stylize('[Object]', 'special');
  13128. }
  13129. }
  13130. ctx.seen.push(value);
  13131. var output;
  13132. if (array) {
  13133. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  13134. } else {
  13135. output = keys.map(function(key) {
  13136. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  13137. });
  13138. }
  13139. ctx.seen.pop();
  13140. return reduceToSingleString(output, base, braces);
  13141. }
  13142. function formatPrimitive(ctx, value) {
  13143. if (isUndefined(value))
  13144. return ctx.stylize('undefined', 'undefined');
  13145. if (isString(value)) {
  13146. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  13147. .replace(/'/g, "\\'")
  13148. .replace(/\\"/g, '"') + '\'';
  13149. return ctx.stylize(simple, 'string');
  13150. }
  13151. if (isNumber(value))
  13152. return ctx.stylize('' + value, 'number');
  13153. if (isBoolean(value))
  13154. return ctx.stylize('' + value, 'boolean');
  13155. // For some reason typeof null is "object", so special case here.
  13156. if (isNull(value))
  13157. return ctx.stylize('null', 'null');
  13158. }
  13159. function formatError(value) {
  13160. return '[' + Error.prototype.toString.call(value) + ']';
  13161. }
  13162. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  13163. var output = [];
  13164. for (var i = 0, l = value.length; i < l; ++i) {
  13165. if (hasOwnProperty(value, String(i))) {
  13166. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  13167. String(i), true));
  13168. } else {
  13169. output.push('');
  13170. }
  13171. }
  13172. keys.forEach(function(key) {
  13173. if (!key.match(/^\d+$/)) {
  13174. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  13175. key, true));
  13176. }
  13177. });
  13178. return output;
  13179. }
  13180. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  13181. var name, str, desc;
  13182. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  13183. if (desc.get) {
  13184. if (desc.set) {
  13185. str = ctx.stylize('[Getter/Setter]', 'special');
  13186. } else {
  13187. str = ctx.stylize('[Getter]', 'special');
  13188. }
  13189. } else {
  13190. if (desc.set) {
  13191. str = ctx.stylize('[Setter]', 'special');
  13192. }
  13193. }
  13194. if (!hasOwnProperty(visibleKeys, key)) {
  13195. name = '[' + key + ']';
  13196. }
  13197. if (!str) {
  13198. if (ctx.seen.indexOf(desc.value) < 0) {
  13199. if (isNull(recurseTimes)) {
  13200. str = formatValue(ctx, desc.value, null);
  13201. } else {
  13202. str = formatValue(ctx, desc.value, recurseTimes - 1);
  13203. }
  13204. if (str.indexOf('\n') > -1) {
  13205. if (array) {
  13206. str = str.split('\n').map(function(line) {
  13207. return ' ' + line;
  13208. }).join('\n').substr(2);
  13209. } else {
  13210. str = '\n' + str.split('\n').map(function(line) {
  13211. return ' ' + line;
  13212. }).join('\n');
  13213. }
  13214. }
  13215. } else {
  13216. str = ctx.stylize('[Circular]', 'special');
  13217. }
  13218. }
  13219. if (isUndefined(name)) {
  13220. if (array && key.match(/^\d+$/)) {
  13221. return str;
  13222. }
  13223. name = JSON.stringify('' + key);
  13224. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  13225. name = name.substr(1, name.length - 2);
  13226. name = ctx.stylize(name, 'name');
  13227. } else {
  13228. name = name.replace(/'/g, "\\'")
  13229. .replace(/\\"/g, '"')
  13230. .replace(/(^"|"$)/g, "'");
  13231. name = ctx.stylize(name, 'string');
  13232. }
  13233. }
  13234. return name + ': ' + str;
  13235. }
  13236. function reduceToSingleString(output, base, braces) {
  13237. var numLinesEst = 0;
  13238. var length = output.reduce(function(prev, cur) {
  13239. numLinesEst++;
  13240. if (cur.indexOf('\n') >= 0) numLinesEst++;
  13241. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  13242. }, 0);
  13243. if (length > 60) {
  13244. return braces[0] +
  13245. (base === '' ? '' : base + '\n ') +
  13246. ' ' +
  13247. output.join(',\n ') +
  13248. ' ' +
  13249. braces[1];
  13250. }
  13251. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  13252. }
  13253. // NOTE: These type checking functions intentionally don't use `instanceof`
  13254. // because it is fragile and can be easily faked with `Object.create()`.
  13255. function isArray(ar) {
  13256. return Array.isArray(ar);
  13257. }
  13258. exports.isArray = isArray;
  13259. function isBoolean(arg) {
  13260. return typeof arg === 'boolean';
  13261. }
  13262. exports.isBoolean = isBoolean;
  13263. function isNull(arg) {
  13264. return arg === null;
  13265. }
  13266. exports.isNull = isNull;
  13267. function isNullOrUndefined(arg) {
  13268. return arg == null;
  13269. }
  13270. exports.isNullOrUndefined = isNullOrUndefined;
  13271. function isNumber(arg) {
  13272. return typeof arg === 'number';
  13273. }
  13274. exports.isNumber = isNumber;
  13275. function isString(arg) {
  13276. return typeof arg === 'string';
  13277. }
  13278. exports.isString = isString;
  13279. function isSymbol(arg) {
  13280. return typeof arg === 'symbol';
  13281. }
  13282. exports.isSymbol = isSymbol;
  13283. function isUndefined(arg) {
  13284. return arg === void 0;
  13285. }
  13286. exports.isUndefined = isUndefined;
  13287. function isRegExp(re) {
  13288. return isObject(re) && objectToString(re) === '[object RegExp]';
  13289. }
  13290. exports.isRegExp = isRegExp;
  13291. function isObject(arg) {
  13292. return typeof arg === 'object' && arg !== null;
  13293. }
  13294. exports.isObject = isObject;
  13295. function isDate(d) {
  13296. return isObject(d) && objectToString(d) === '[object Date]';
  13297. }
  13298. exports.isDate = isDate;
  13299. function isError(e) {
  13300. return isObject(e) &&
  13301. (objectToString(e) === '[object Error]' || e instanceof Error);
  13302. }
  13303. exports.isError = isError;
  13304. function isFunction(arg) {
  13305. return typeof arg === 'function';
  13306. }
  13307. exports.isFunction = isFunction;
  13308. function isPrimitive(arg) {
  13309. return arg === null ||
  13310. typeof arg === 'boolean' ||
  13311. typeof arg === 'number' ||
  13312. typeof arg === 'string' ||
  13313. typeof arg === 'symbol' || // ES6 symbol
  13314. typeof arg === 'undefined';
  13315. }
  13316. exports.isPrimitive = isPrimitive;
  13317. exports.isBuffer = require('./support/isBuffer');
  13318. function objectToString(o) {
  13319. return Object.prototype.toString.call(o);
  13320. }
  13321. function pad(n) {
  13322. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  13323. }
  13324. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  13325. 'Oct', 'Nov', 'Dec'];
  13326. // 26 Feb 16:19:34
  13327. function timestamp() {
  13328. var d = new Date();
  13329. var time = [pad(d.getHours()),
  13330. pad(d.getMinutes()),
  13331. pad(d.getSeconds())].join(':');
  13332. return [d.getDate(), months[d.getMonth()], time].join(' ');
  13333. }
  13334. // log is just a thin wrapper to console.log that prepends a timestamp
  13335. exports.log = function() {
  13336. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  13337. };
  13338. /**
  13339. * Inherit the prototype methods from one constructor into another.
  13340. *
  13341. * The Function.prototype.inherits from lang.js rewritten as a standalone
  13342. * function (not on Function.prototype). NOTE: If this file is to be loaded
  13343. * during bootstrapping this function needs to be rewritten using some native
  13344. * functions as prototype setup using normal JavaScript does not work as
  13345. * expected during bootstrapping (see mirror.js in r114903).
  13346. *
  13347. * @param {function} ctor Constructor function which needs to inherit the
  13348. * prototype.
  13349. * @param {function} superCtor Constructor function to inherit prototype from.
  13350. */
  13351. exports.inherits = require('inherits');
  13352. exports._extend = function(origin, add) {
  13353. // Don't do anything if add isn't an object
  13354. if (!add || !isObject(add)) return origin;
  13355. var keys = Object.keys(add);
  13356. var i = keys.length;
  13357. while (i--) {
  13358. origin[keys[i]] = add[keys[i]];
  13359. }
  13360. return origin;
  13361. };
  13362. function hasOwnProperty(obj, prop) {
  13363. return Object.prototype.hasOwnProperty.call(obj, prop);
  13364. }
  13365. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13366. },{"./support/isBuffer":88,"_process":55,"inherits":87}],90:[function(require,module,exports){
  13367. arguments[4][30][0].apply(exports,arguments)
  13368. },{"./chrome/chrome_shim":91,"./edge/edge_shim":93,"./firefox/firefox_shim":95,"./safari/safari_shim":97,"./utils":98,"dup":30}],91:[function(require,module,exports){
  13369. /*
  13370. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  13371. *
  13372. * Use of this source code is governed by a BSD-style license
  13373. * that can be found in the LICENSE file in the root of the source
  13374. * tree.
  13375. */
  13376. /* eslint-env node */
  13377. 'use strict';
  13378. var logging = require('../utils.js').log;
  13379. var browserDetails = require('../utils.js').browserDetails;
  13380. var chromeShim = {
  13381. shimMediaStream: function() {
  13382. window.MediaStream = window.MediaStream || window.webkitMediaStream;
  13383. },
  13384. shimOnTrack: function() {
  13385. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  13386. window.RTCPeerConnection.prototype)) {
  13387. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  13388. get: function() {
  13389. return this._ontrack;
  13390. },
  13391. set: function(f) {
  13392. var self = this;
  13393. if (this._ontrack) {
  13394. this.removeEventListener('track', this._ontrack);
  13395. this.removeEventListener('addstream', this._ontrackpoly);
  13396. }
  13397. this.addEventListener('track', this._ontrack = f);
  13398. this.addEventListener('addstream', this._ontrackpoly = function(e) {
  13399. // onaddstream does not fire when a track is added to an existing
  13400. // stream. But stream.onaddtrack is implemented so we use that.
  13401. e.stream.addEventListener('addtrack', function(te) {
  13402. var event = new Event('track');
  13403. event.track = te.track;
  13404. event.receiver = {track: te.track};
  13405. event.streams = [e.stream];
  13406. self.dispatchEvent(event);
  13407. });
  13408. e.stream.getTracks().forEach(function(track) {
  13409. var event = new Event('track');
  13410. event.track = track;
  13411. event.receiver = {track: track};
  13412. event.streams = [e.stream];
  13413. this.dispatchEvent(event);
  13414. }.bind(this));
  13415. }.bind(this));
  13416. }
  13417. });
  13418. }
  13419. },
  13420. shimSourceObject: function() {
  13421. if (typeof window === 'object') {
  13422. if (window.HTMLMediaElement &&
  13423. !('srcObject' in window.HTMLMediaElement.prototype)) {
  13424. // Shim the srcObject property, once, when HTMLMediaElement is found.
  13425. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
  13426. get: function() {
  13427. return this._srcObject;
  13428. },
  13429. set: function(stream) {
  13430. var self = this;
  13431. // Use _srcObject as a private property for this shim
  13432. this._srcObject = stream;
  13433. if (this.src) {
  13434. URL.revokeObjectURL(this.src);
  13435. }
  13436. if (!stream) {
  13437. this.src = '';
  13438. return;
  13439. }
  13440. this.src = URL.createObjectURL(stream);
  13441. // We need to recreate the blob url when a track is added or
  13442. // removed. Doing it manually since we want to avoid a recursion.
  13443. stream.addEventListener('addtrack', function() {
  13444. if (self.src) {
  13445. URL.revokeObjectURL(self.src);
  13446. }
  13447. self.src = URL.createObjectURL(stream);
  13448. });
  13449. stream.addEventListener('removetrack', function() {
  13450. if (self.src) {
  13451. URL.revokeObjectURL(self.src);
  13452. }
  13453. self.src = URL.createObjectURL(stream);
  13454. });
  13455. }
  13456. });
  13457. }
  13458. }
  13459. },
  13460. shimPeerConnection: function() {
  13461. // The RTCPeerConnection object.
  13462. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  13463. // Translate iceTransportPolicy to iceTransports,
  13464. // see https://code.google.com/p/webrtc/issues/detail?id=4869
  13465. logging('PeerConnection');
  13466. if (pcConfig && pcConfig.iceTransportPolicy) {
  13467. pcConfig.iceTransports = pcConfig.iceTransportPolicy;
  13468. }
  13469. var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints);
  13470. var origGetStats = pc.getStats.bind(pc);
  13471. pc.getStats = function(selector, successCallback, errorCallback) {
  13472. var self = this;
  13473. var args = arguments;
  13474. // If selector is a function then we are in the old style stats so just
  13475. // pass back the original getStats format to avoid breaking old users.
  13476. if (arguments.length > 0 && typeof selector === 'function') {
  13477. return origGetStats(selector, successCallback);
  13478. }
  13479. var fixChromeStats_ = function(response) {
  13480. var standardReport = {};
  13481. var reports = response.result();
  13482. reports.forEach(function(report) {
  13483. var standardStats = {
  13484. id: report.id,
  13485. timestamp: report.timestamp,
  13486. type: report.type
  13487. };
  13488. report.names().forEach(function(name) {
  13489. standardStats[name] = report.stat(name);
  13490. });
  13491. standardReport[standardStats.id] = standardStats;
  13492. });
  13493. return standardReport;
  13494. };
  13495. // shim getStats with maplike support
  13496. var makeMapStats = function(stats, legacyStats) {
  13497. var map = new Map(Object.keys(stats).map(function(key) {
  13498. return[key, stats[key]];
  13499. }));
  13500. legacyStats = legacyStats || stats;
  13501. Object.keys(legacyStats).forEach(function(key) {
  13502. map[key] = legacyStats[key];
  13503. });
  13504. return map;
  13505. };
  13506. if (arguments.length >= 2) {
  13507. var successCallbackWrapper_ = function(response) {
  13508. args[1](makeMapStats(fixChromeStats_(response)));
  13509. };
  13510. return origGetStats.apply(this, [successCallbackWrapper_,
  13511. arguments[0]]);
  13512. }
  13513. // promise-support
  13514. return new Promise(function(resolve, reject) {
  13515. if (args.length === 1 && typeof selector === 'object') {
  13516. origGetStats.apply(self, [
  13517. function(response) {
  13518. resolve(makeMapStats(fixChromeStats_(response)));
  13519. }, reject]);
  13520. } else {
  13521. // Preserve legacy chrome stats only on legacy access of stats obj
  13522. origGetStats.apply(self, [
  13523. function(response) {
  13524. resolve(makeMapStats(fixChromeStats_(response),
  13525. response.result()));
  13526. }, reject]);
  13527. }
  13528. }).then(successCallback, errorCallback);
  13529. };
  13530. return pc;
  13531. };
  13532. window.RTCPeerConnection.prototype = webkitRTCPeerConnection.prototype;
  13533. // wrap static methods. Currently just generateCertificate.
  13534. if (webkitRTCPeerConnection.generateCertificate) {
  13535. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  13536. get: function() {
  13537. return webkitRTCPeerConnection.generateCertificate;
  13538. }
  13539. });
  13540. }
  13541. ['createOffer', 'createAnswer'].forEach(function(method) {
  13542. var nativeMethod = webkitRTCPeerConnection.prototype[method];
  13543. webkitRTCPeerConnection.prototype[method] = function() {
  13544. var self = this;
  13545. if (arguments.length < 1 || (arguments.length === 1 &&
  13546. typeof arguments[0] === 'object')) {
  13547. var opts = arguments.length === 1 ? arguments[0] : undefined;
  13548. return new Promise(function(resolve, reject) {
  13549. nativeMethod.apply(self, [resolve, reject, opts]);
  13550. });
  13551. }
  13552. return nativeMethod.apply(this, arguments);
  13553. };
  13554. });
  13555. // add promise support -- natively available in Chrome 51
  13556. if (browserDetails.version < 51) {
  13557. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  13558. .forEach(function(method) {
  13559. var nativeMethod = webkitRTCPeerConnection.prototype[method];
  13560. webkitRTCPeerConnection.prototype[method] = function() {
  13561. var args = arguments;
  13562. var self = this;
  13563. var promise = new Promise(function(resolve, reject) {
  13564. nativeMethod.apply(self, [args[0], resolve, reject]);
  13565. });
  13566. if (args.length < 2) {
  13567. return promise;
  13568. }
  13569. return promise.then(function() {
  13570. args[1].apply(null, []);
  13571. },
  13572. function(err) {
  13573. if (args.length >= 3) {
  13574. args[2].apply(null, [err]);
  13575. }
  13576. });
  13577. };
  13578. });
  13579. }
  13580. // shim implicit creation of RTCSessionDescription/RTCIceCandidate
  13581. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  13582. .forEach(function(method) {
  13583. var nativeMethod = webkitRTCPeerConnection.prototype[method];
  13584. webkitRTCPeerConnection.prototype[method] = function() {
  13585. arguments[0] = new ((method === 'addIceCandidate') ?
  13586. RTCIceCandidate : RTCSessionDescription)(arguments[0]);
  13587. return nativeMethod.apply(this, arguments);
  13588. };
  13589. });
  13590. // support for addIceCandidate(null or undefined)
  13591. var nativeAddIceCandidate =
  13592. RTCPeerConnection.prototype.addIceCandidate;
  13593. RTCPeerConnection.prototype.addIceCandidate = function() {
  13594. if (!arguments[0]) {
  13595. if (arguments[1]) {
  13596. arguments[1].apply(null);
  13597. }
  13598. return Promise.resolve();
  13599. }
  13600. return nativeAddIceCandidate.apply(this, arguments);
  13601. };
  13602. }
  13603. };
  13604. // Expose public methods.
  13605. module.exports = {
  13606. shimMediaStream: chromeShim.shimMediaStream,
  13607. shimOnTrack: chromeShim.shimOnTrack,
  13608. shimSourceObject: chromeShim.shimSourceObject,
  13609. shimPeerConnection: chromeShim.shimPeerConnection,
  13610. shimGetUserMedia: require('./getusermedia')
  13611. };
  13612. },{"../utils.js":98,"./getusermedia":92}],92:[function(require,module,exports){
  13613. /*
  13614. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  13615. *
  13616. * Use of this source code is governed by a BSD-style license
  13617. * that can be found in the LICENSE file in the root of the source
  13618. * tree.
  13619. */
  13620. /* eslint-env node */
  13621. 'use strict';
  13622. var logging = require('../utils.js').log;
  13623. // Expose public methods.
  13624. module.exports = function() {
  13625. var constraintsToChrome_ = function(c) {
  13626. if (typeof c !== 'object' || c.mandatory || c.optional) {
  13627. return c;
  13628. }
  13629. var cc = {};
  13630. Object.keys(c).forEach(function(key) {
  13631. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  13632. return;
  13633. }
  13634. var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
  13635. if (r.exact !== undefined && typeof r.exact === 'number') {
  13636. r.min = r.max = r.exact;
  13637. }
  13638. var oldname_ = function(prefix, name) {
  13639. if (prefix) {
  13640. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  13641. }
  13642. return (name === 'deviceId') ? 'sourceId' : name;
  13643. };
  13644. if (r.ideal !== undefined) {
  13645. cc.optional = cc.optional || [];
  13646. var oc = {};
  13647. if (typeof r.ideal === 'number') {
  13648. oc[oldname_('min', key)] = r.ideal;
  13649. cc.optional.push(oc);
  13650. oc = {};
  13651. oc[oldname_('max', key)] = r.ideal;
  13652. cc.optional.push(oc);
  13653. } else {
  13654. oc[oldname_('', key)] = r.ideal;
  13655. cc.optional.push(oc);
  13656. }
  13657. }
  13658. if (r.exact !== undefined && typeof r.exact !== 'number') {
  13659. cc.mandatory = cc.mandatory || {};
  13660. cc.mandatory[oldname_('', key)] = r.exact;
  13661. } else {
  13662. ['min', 'max'].forEach(function(mix) {
  13663. if (r[mix] !== undefined) {
  13664. cc.mandatory = cc.mandatory || {};
  13665. cc.mandatory[oldname_(mix, key)] = r[mix];
  13666. }
  13667. });
  13668. }
  13669. });
  13670. if (c.advanced) {
  13671. cc.optional = (cc.optional || []).concat(c.advanced);
  13672. }
  13673. return cc;
  13674. };
  13675. var shimConstraints_ = function(constraints, func) {
  13676. constraints = JSON.parse(JSON.stringify(constraints));
  13677. if (constraints && constraints.audio) {
  13678. constraints.audio = constraintsToChrome_(constraints.audio);
  13679. }
  13680. if (constraints && typeof constraints.video === 'object') {
  13681. // Shim facingMode for mobile, where it defaults to "user".
  13682. var face = constraints.video.facingMode;
  13683. face = face && ((typeof face === 'object') ? face : {ideal: face});
  13684. if ((face && (face.exact === 'user' || face.exact === 'environment' ||
  13685. face.ideal === 'user' || face.ideal === 'environment')) &&
  13686. !(navigator.mediaDevices.getSupportedConstraints &&
  13687. navigator.mediaDevices.getSupportedConstraints().facingMode)) {
  13688. delete constraints.video.facingMode;
  13689. if (face.exact === 'environment' || face.ideal === 'environment') {
  13690. // Look for "back" in label, or use last cam (typically back cam).
  13691. return navigator.mediaDevices.enumerateDevices()
  13692. .then(function(devices) {
  13693. devices = devices.filter(function(d) {
  13694. return d.kind === 'videoinput';
  13695. });
  13696. var back = devices.find(function(d) {
  13697. return d.label.toLowerCase().indexOf('back') !== -1;
  13698. }) || (devices.length && devices[devices.length - 1]);
  13699. if (back) {
  13700. constraints.video.deviceId = face.exact ? {exact: back.deviceId} :
  13701. {ideal: back.deviceId};
  13702. }
  13703. constraints.video = constraintsToChrome_(constraints.video);
  13704. logging('chrome: ' + JSON.stringify(constraints));
  13705. return func(constraints);
  13706. });
  13707. }
  13708. }
  13709. constraints.video = constraintsToChrome_(constraints.video);
  13710. }
  13711. logging('chrome: ' + JSON.stringify(constraints));
  13712. return func(constraints);
  13713. };
  13714. var shimError_ = function(e) {
  13715. return {
  13716. name: {
  13717. PermissionDeniedError: 'NotAllowedError',
  13718. ConstraintNotSatisfiedError: 'OverconstrainedError'
  13719. }[e.name] || e.name,
  13720. message: e.message,
  13721. constraint: e.constraintName,
  13722. toString: function() {
  13723. return this.name + (this.message && ': ') + this.message;
  13724. }
  13725. };
  13726. };
  13727. var getUserMedia_ = function(constraints, onSuccess, onError) {
  13728. shimConstraints_(constraints, function(c) {
  13729. navigator.webkitGetUserMedia(c, onSuccess, function(e) {
  13730. onError(shimError_(e));
  13731. });
  13732. });
  13733. };
  13734. navigator.getUserMedia = getUserMedia_;
  13735. // Returns the result of getUserMedia as a Promise.
  13736. var getUserMediaPromise_ = function(constraints) {
  13737. return new Promise(function(resolve, reject) {
  13738. navigator.getUserMedia(constraints, resolve, reject);
  13739. });
  13740. };
  13741. if (!navigator.mediaDevices) {
  13742. navigator.mediaDevices = {
  13743. getUserMedia: getUserMediaPromise_,
  13744. enumerateDevices: function() {
  13745. return new Promise(function(resolve) {
  13746. var kinds = {audio: 'audioinput', video: 'videoinput'};
  13747. return MediaStreamTrack.getSources(function(devices) {
  13748. resolve(devices.map(function(device) {
  13749. return {label: device.label,
  13750. kind: kinds[device.kind],
  13751. deviceId: device.id,
  13752. groupId: ''};
  13753. }));
  13754. });
  13755. });
  13756. }
  13757. };
  13758. }
  13759. // A shim for getUserMedia method on the mediaDevices object.
  13760. // TODO(KaptenJansson) remove once implemented in Chrome stable.
  13761. if (!navigator.mediaDevices.getUserMedia) {
  13762. navigator.mediaDevices.getUserMedia = function(constraints) {
  13763. return getUserMediaPromise_(constraints);
  13764. };
  13765. } else {
  13766. // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
  13767. // function which returns a Promise, it does not accept spec-style
  13768. // constraints.
  13769. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  13770. bind(navigator.mediaDevices);
  13771. navigator.mediaDevices.getUserMedia = function(cs) {
  13772. return shimConstraints_(cs, function(c) {
  13773. return origGetUserMedia(c).then(function(stream) {
  13774. if (c.audio && !stream.getAudioTracks().length ||
  13775. c.video && !stream.getVideoTracks().length) {
  13776. stream.getTracks().forEach(function(track) {
  13777. track.stop();
  13778. });
  13779. throw new DOMException('', 'NotFoundError');
  13780. }
  13781. return stream;
  13782. }, function(e) {
  13783. return Promise.reject(shimError_(e));
  13784. });
  13785. });
  13786. };
  13787. }
  13788. // Dummy devicechange event methods.
  13789. // TODO(KaptenJansson) remove once implemented in Chrome stable.
  13790. if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
  13791. navigator.mediaDevices.addEventListener = function() {
  13792. logging('Dummy mediaDevices.addEventListener called.');
  13793. };
  13794. }
  13795. if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
  13796. navigator.mediaDevices.removeEventListener = function() {
  13797. logging('Dummy mediaDevices.removeEventListener called.');
  13798. };
  13799. }
  13800. };
  13801. },{"../utils.js":98}],93:[function(require,module,exports){
  13802. /*
  13803. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  13804. *
  13805. * Use of this source code is governed by a BSD-style license
  13806. * that can be found in the LICENSE file in the root of the source
  13807. * tree.
  13808. */
  13809. /* eslint-env node */
  13810. 'use strict';
  13811. var SDPUtils = require('sdp');
  13812. var browserDetails = require('../utils').browserDetails;
  13813. var edgeShim = {
  13814. shimPeerConnection: function() {
  13815. if (window.RTCIceGatherer) {
  13816. // ORTC defines an RTCIceCandidate object but no constructor.
  13817. // Not implemented in Edge.
  13818. if (!window.RTCIceCandidate) {
  13819. window.RTCIceCandidate = function(args) {
  13820. return args;
  13821. };
  13822. }
  13823. // ORTC does not have a session description object but
  13824. // other browsers (i.e. Chrome) that will support both PC and ORTC
  13825. // in the future might have this defined already.
  13826. if (!window.RTCSessionDescription) {
  13827. window.RTCSessionDescription = function(args) {
  13828. return args;
  13829. };
  13830. }
  13831. // this adds an additional event listener to MediaStrackTrack that signals
  13832. // when a tracks enabled property was changed.
  13833. var origMSTEnabled = Object.getOwnPropertyDescriptor(
  13834. MediaStreamTrack.prototype, 'enabled');
  13835. Object.defineProperty(MediaStreamTrack.prototype, 'enabled', {
  13836. set: function(value) {
  13837. origMSTEnabled.set.call(this, value);
  13838. var ev = new Event('enabled');
  13839. ev.enabled = value;
  13840. this.dispatchEvent(ev);
  13841. }
  13842. });
  13843. }
  13844. window.RTCPeerConnection = function(config) {
  13845. var self = this;
  13846. var _eventTarget = document.createDocumentFragment();
  13847. ['addEventListener', 'removeEventListener', 'dispatchEvent']
  13848. .forEach(function(method) {
  13849. self[method] = _eventTarget[method].bind(_eventTarget);
  13850. });
  13851. this.onicecandidate = null;
  13852. this.onaddstream = null;
  13853. this.ontrack = null;
  13854. this.onremovestream = null;
  13855. this.onsignalingstatechange = null;
  13856. this.oniceconnectionstatechange = null;
  13857. this.onnegotiationneeded = null;
  13858. this.ondatachannel = null;
  13859. this.localStreams = [];
  13860. this.remoteStreams = [];
  13861. this.getLocalStreams = function() {
  13862. return self.localStreams;
  13863. };
  13864. this.getRemoteStreams = function() {
  13865. return self.remoteStreams;
  13866. };
  13867. this.localDescription = new RTCSessionDescription({
  13868. type: '',
  13869. sdp: ''
  13870. });
  13871. this.remoteDescription = new RTCSessionDescription({
  13872. type: '',
  13873. sdp: ''
  13874. });
  13875. this.signalingState = 'stable';
  13876. this.iceConnectionState = 'new';
  13877. this.iceGatheringState = 'new';
  13878. this.iceOptions = {
  13879. gatherPolicy: 'all',
  13880. iceServers: []
  13881. };
  13882. if (config && config.iceTransportPolicy) {
  13883. switch (config.iceTransportPolicy) {
  13884. case 'all':
  13885. case 'relay':
  13886. this.iceOptions.gatherPolicy = config.iceTransportPolicy;
  13887. break;
  13888. case 'none':
  13889. // FIXME: remove once implementation and spec have added this.
  13890. throw new TypeError('iceTransportPolicy "none" not supported');
  13891. default:
  13892. // don't set iceTransportPolicy.
  13893. break;
  13894. }
  13895. }
  13896. this.usingBundle = config && config.bundlePolicy === 'max-bundle';
  13897. if (config && config.iceServers) {
  13898. // Edge does not like
  13899. // 1) stun:
  13900. // 2) turn: that does not have all of turn:host:port?transport=udp
  13901. // 3) turn: with ipv6 addresses
  13902. var iceServers = JSON.parse(JSON.stringify(config.iceServers));
  13903. this.iceOptions.iceServers = iceServers.filter(function(server) {
  13904. if (server && server.urls) {
  13905. var urls = server.urls;
  13906. if (typeof urls === 'string') {
  13907. urls = [urls];
  13908. }
  13909. urls = urls.filter(function(url) {
  13910. return (url.indexOf('turn:') === 0 &&
  13911. url.indexOf('transport=udp') !== -1 &&
  13912. url.indexOf('turn:[') === -1) ||
  13913. (url.indexOf('stun:') === 0 &&
  13914. browserDetails.version >= 14393);
  13915. })[0];
  13916. return !!urls;
  13917. }
  13918. return false;
  13919. });
  13920. }
  13921. this._config = config;
  13922. // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
  13923. // everything that is needed to describe a SDP m-line.
  13924. this.transceivers = [];
  13925. // since the iceGatherer is currently created in createOffer but we
  13926. // must not emit candidates until after setLocalDescription we buffer
  13927. // them in this array.
  13928. this._localIceCandidatesBuffer = [];
  13929. };
  13930. window.RTCPeerConnection.prototype._emitBufferedCandidates = function() {
  13931. var self = this;
  13932. var sections = SDPUtils.splitSections(self.localDescription.sdp);
  13933. // FIXME: need to apply ice candidates in a way which is async but
  13934. // in-order
  13935. this._localIceCandidatesBuffer.forEach(function(event) {
  13936. var end = !event.candidate || Object.keys(event.candidate).length === 0;
  13937. if (end) {
  13938. for (var j = 1; j < sections.length; j++) {
  13939. if (sections[j].indexOf('\r\na=end-of-candidates\r\n') === -1) {
  13940. sections[j] += 'a=end-of-candidates\r\n';
  13941. }
  13942. }
  13943. } else if (event.candidate.candidate.indexOf('typ endOfCandidates')
  13944. === -1) {
  13945. sections[event.candidate.sdpMLineIndex + 1] +=
  13946. 'a=' + event.candidate.candidate + '\r\n';
  13947. }
  13948. self.localDescription.sdp = sections.join('');
  13949. self.dispatchEvent(event);
  13950. if (self.onicecandidate !== null) {
  13951. self.onicecandidate(event);
  13952. }
  13953. if (!event.candidate && self.iceGatheringState !== 'complete') {
  13954. var complete = self.transceivers.every(function(transceiver) {
  13955. return transceiver.iceGatherer &&
  13956. transceiver.iceGatherer.state === 'completed';
  13957. });
  13958. if (complete) {
  13959. self.iceGatheringState = 'complete';
  13960. }
  13961. }
  13962. });
  13963. this._localIceCandidatesBuffer = [];
  13964. };
  13965. window.RTCPeerConnection.prototype.getConfiguration = function() {
  13966. return this._config;
  13967. };
  13968. window.RTCPeerConnection.prototype.addStream = function(stream) {
  13969. // Clone is necessary for local demos mostly, attaching directly
  13970. // to two different senders does not work (build 10547).
  13971. var clonedStream = stream.clone();
  13972. stream.getTracks().forEach(function(track, idx) {
  13973. var clonedTrack = clonedStream.getTracks()[idx];
  13974. track.addEventListener('enabled', function(event) {
  13975. clonedTrack.enabled = event.enabled;
  13976. });
  13977. });
  13978. this.localStreams.push(clonedStream);
  13979. this._maybeFireNegotiationNeeded();
  13980. };
  13981. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  13982. var idx = this.localStreams.indexOf(stream);
  13983. if (idx > -1) {
  13984. this.localStreams.splice(idx, 1);
  13985. this._maybeFireNegotiationNeeded();
  13986. }
  13987. };
  13988. window.RTCPeerConnection.prototype.getSenders = function() {
  13989. return this.transceivers.filter(function(transceiver) {
  13990. return !!transceiver.rtpSender;
  13991. })
  13992. .map(function(transceiver) {
  13993. return transceiver.rtpSender;
  13994. });
  13995. };
  13996. window.RTCPeerConnection.prototype.getReceivers = function() {
  13997. return this.transceivers.filter(function(transceiver) {
  13998. return !!transceiver.rtpReceiver;
  13999. })
  14000. .map(function(transceiver) {
  14001. return transceiver.rtpReceiver;
  14002. });
  14003. };
  14004. // Determines the intersection of local and remote capabilities.
  14005. window.RTCPeerConnection.prototype._getCommonCapabilities =
  14006. function(localCapabilities, remoteCapabilities) {
  14007. var commonCapabilities = {
  14008. codecs: [],
  14009. headerExtensions: [],
  14010. fecMechanisms: []
  14011. };
  14012. localCapabilities.codecs.forEach(function(lCodec) {
  14013. for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
  14014. var rCodec = remoteCapabilities.codecs[i];
  14015. if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
  14016. lCodec.clockRate === rCodec.clockRate) {
  14017. // number of channels is the highest common number of channels
  14018. rCodec.numChannels = Math.min(lCodec.numChannels,
  14019. rCodec.numChannels);
  14020. // push rCodec so we reply with offerer payload type
  14021. commonCapabilities.codecs.push(rCodec);
  14022. // determine common feedback mechanisms
  14023. rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
  14024. for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
  14025. if (lCodec.rtcpFeedback[j].type === fb.type &&
  14026. lCodec.rtcpFeedback[j].parameter === fb.parameter) {
  14027. return true;
  14028. }
  14029. }
  14030. return false;
  14031. });
  14032. // FIXME: also need to determine .parameters
  14033. // see https://github.com/openpeer/ortc/issues/569
  14034. break;
  14035. }
  14036. }
  14037. });
  14038. localCapabilities.headerExtensions
  14039. .forEach(function(lHeaderExtension) {
  14040. for (var i = 0; i < remoteCapabilities.headerExtensions.length;
  14041. i++) {
  14042. var rHeaderExtension = remoteCapabilities.headerExtensions[i];
  14043. if (lHeaderExtension.uri === rHeaderExtension.uri) {
  14044. commonCapabilities.headerExtensions.push(rHeaderExtension);
  14045. break;
  14046. }
  14047. }
  14048. });
  14049. // FIXME: fecMechanisms
  14050. return commonCapabilities;
  14051. };
  14052. // Create ICE gatherer, ICE transport and DTLS transport.
  14053. window.RTCPeerConnection.prototype._createIceAndDtlsTransports =
  14054. function(mid, sdpMLineIndex) {
  14055. var self = this;
  14056. var iceGatherer = new RTCIceGatherer(self.iceOptions);
  14057. var iceTransport = new RTCIceTransport(iceGatherer);
  14058. iceGatherer.onlocalcandidate = function(evt) {
  14059. var event = new Event('icecandidate');
  14060. event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
  14061. var cand = evt.candidate;
  14062. var end = !cand || Object.keys(cand).length === 0;
  14063. // Edge emits an empty object for RTCIceCandidateComplete‥
  14064. if (end) {
  14065. // polyfill since RTCIceGatherer.state is not implemented in
  14066. // Edge 10547 yet.
  14067. if (iceGatherer.state === undefined) {
  14068. iceGatherer.state = 'completed';
  14069. }
  14070. // Emit a candidate with type endOfCandidates to make the samples
  14071. // work. Edge requires addIceCandidate with this empty candidate
  14072. // to start checking. The real solution is to signal
  14073. // end-of-candidates to the other side when getting the null
  14074. // candidate but some apps (like the samples) don't do that.
  14075. event.candidate.candidate =
  14076. 'candidate:1 1 udp 1 0.0.0.0 9 typ endOfCandidates';
  14077. } else {
  14078. // RTCIceCandidate doesn't have a component, needs to be added
  14079. cand.component = iceTransport.component === 'RTCP' ? 2 : 1;
  14080. event.candidate.candidate = SDPUtils.writeCandidate(cand);
  14081. }
  14082. // update local description.
  14083. var sections = SDPUtils.splitSections(self.localDescription.sdp);
  14084. if (event.candidate.candidate.indexOf('typ endOfCandidates')
  14085. === -1) {
  14086. sections[event.candidate.sdpMLineIndex + 1] +=
  14087. 'a=' + event.candidate.candidate + '\r\n';
  14088. } else {
  14089. sections[event.candidate.sdpMLineIndex + 1] +=
  14090. 'a=end-of-candidates\r\n';
  14091. }
  14092. self.localDescription.sdp = sections.join('');
  14093. var complete = self.transceivers.every(function(transceiver) {
  14094. return transceiver.iceGatherer &&
  14095. transceiver.iceGatherer.state === 'completed';
  14096. });
  14097. // Emit candidate if localDescription is set.
  14098. // Also emits null candidate when all gatherers are complete.
  14099. switch (self.iceGatheringState) {
  14100. case 'new':
  14101. self._localIceCandidatesBuffer.push(event);
  14102. if (end && complete) {
  14103. self._localIceCandidatesBuffer.push(
  14104. new Event('icecandidate'));
  14105. }
  14106. break;
  14107. case 'gathering':
  14108. self._emitBufferedCandidates();
  14109. self.dispatchEvent(event);
  14110. if (self.onicecandidate !== null) {
  14111. self.onicecandidate(event);
  14112. }
  14113. if (complete) {
  14114. self.dispatchEvent(new Event('icecandidate'));
  14115. if (self.onicecandidate !== null) {
  14116. self.onicecandidate(new Event('icecandidate'));
  14117. }
  14118. self.iceGatheringState = 'complete';
  14119. }
  14120. break;
  14121. case 'complete':
  14122. // should not happen... currently!
  14123. break;
  14124. default: // no-op.
  14125. break;
  14126. }
  14127. };
  14128. iceTransport.onicestatechange = function() {
  14129. self._updateConnectionState();
  14130. };
  14131. var dtlsTransport = new RTCDtlsTransport(iceTransport);
  14132. dtlsTransport.ondtlsstatechange = function() {
  14133. self._updateConnectionState();
  14134. };
  14135. dtlsTransport.onerror = function() {
  14136. // onerror does not set state to failed by itself.
  14137. dtlsTransport.state = 'failed';
  14138. self._updateConnectionState();
  14139. };
  14140. return {
  14141. iceGatherer: iceGatherer,
  14142. iceTransport: iceTransport,
  14143. dtlsTransport: dtlsTransport
  14144. };
  14145. };
  14146. // Start the RTP Sender and Receiver for a transceiver.
  14147. window.RTCPeerConnection.prototype._transceive = function(transceiver,
  14148. send, recv) {
  14149. var params = this._getCommonCapabilities(transceiver.localCapabilities,
  14150. transceiver.remoteCapabilities);
  14151. if (send && transceiver.rtpSender) {
  14152. params.encodings = transceiver.sendEncodingParameters;
  14153. params.rtcp = {
  14154. cname: SDPUtils.localCName
  14155. };
  14156. if (transceiver.recvEncodingParameters.length) {
  14157. params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
  14158. }
  14159. transceiver.rtpSender.send(params);
  14160. }
  14161. if (recv && transceiver.rtpReceiver) {
  14162. // remove RTX field in Edge 14942
  14163. if (transceiver.kind === 'video'
  14164. && transceiver.recvEncodingParameters) {
  14165. transceiver.recvEncodingParameters.forEach(function(p) {
  14166. delete p.rtx;
  14167. });
  14168. }
  14169. params.encodings = transceiver.recvEncodingParameters;
  14170. params.rtcp = {
  14171. cname: transceiver.cname
  14172. };
  14173. if (transceiver.sendEncodingParameters.length) {
  14174. params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
  14175. }
  14176. transceiver.rtpReceiver.receive(params);
  14177. }
  14178. };
  14179. window.RTCPeerConnection.prototype.setLocalDescription =
  14180. function(description) {
  14181. var self = this;
  14182. var sections;
  14183. var sessionpart;
  14184. if (description.type === 'offer') {
  14185. // FIXME: What was the purpose of this empty if statement?
  14186. // if (!this._pendingOffer) {
  14187. // } else {
  14188. if (this._pendingOffer) {
  14189. // VERY limited support for SDP munging. Limited to:
  14190. // * changing the order of codecs
  14191. sections = SDPUtils.splitSections(description.sdp);
  14192. sessionpart = sections.shift();
  14193. sections.forEach(function(mediaSection, sdpMLineIndex) {
  14194. var caps = SDPUtils.parseRtpParameters(mediaSection);
  14195. self._pendingOffer[sdpMLineIndex].localCapabilities = caps;
  14196. });
  14197. this.transceivers = this._pendingOffer;
  14198. delete this._pendingOffer;
  14199. }
  14200. } else if (description.type === 'answer') {
  14201. sections = SDPUtils.splitSections(self.remoteDescription.sdp);
  14202. sessionpart = sections.shift();
  14203. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  14204. 'a=ice-lite').length > 0;
  14205. sections.forEach(function(mediaSection, sdpMLineIndex) {
  14206. var transceiver = self.transceivers[sdpMLineIndex];
  14207. var iceGatherer = transceiver.iceGatherer;
  14208. var iceTransport = transceiver.iceTransport;
  14209. var dtlsTransport = transceiver.dtlsTransport;
  14210. var localCapabilities = transceiver.localCapabilities;
  14211. var remoteCapabilities = transceiver.remoteCapabilities;
  14212. var rejected = mediaSection.split('\n', 1)[0]
  14213. .split(' ', 2)[1] === '0';
  14214. if (!rejected && !transceiver.isDatachannel) {
  14215. var remoteIceParameters = SDPUtils.getIceParameters(
  14216. mediaSection, sessionpart);
  14217. if (isIceLite) {
  14218. var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
  14219. .map(function(cand) {
  14220. return SDPUtils.parseCandidate(cand);
  14221. })
  14222. .filter(function(cand) {
  14223. return cand.component === '1';
  14224. });
  14225. // ice-lite only includes host candidates in the SDP so we can
  14226. // use setRemoteCandidates (which implies an
  14227. // RTCIceCandidateComplete)
  14228. if (cands.length) {
  14229. iceTransport.setRemoteCandidates(cands);
  14230. }
  14231. }
  14232. var remoteDtlsParameters = SDPUtils.getDtlsParameters(
  14233. mediaSection, sessionpart);
  14234. if (isIceLite) {
  14235. remoteDtlsParameters.role = 'server';
  14236. }
  14237. if (!self.usingBundle || sdpMLineIndex === 0) {
  14238. iceTransport.start(iceGatherer, remoteIceParameters,
  14239. isIceLite ? 'controlling' : 'controlled');
  14240. dtlsTransport.start(remoteDtlsParameters);
  14241. }
  14242. // Calculate intersection of capabilities.
  14243. var params = self._getCommonCapabilities(localCapabilities,
  14244. remoteCapabilities);
  14245. // Start the RTCRtpSender. The RTCRtpReceiver for this
  14246. // transceiver has already been started in setRemoteDescription.
  14247. self._transceive(transceiver,
  14248. params.codecs.length > 0,
  14249. false);
  14250. }
  14251. });
  14252. }
  14253. this.localDescription = {
  14254. type: description.type,
  14255. sdp: description.sdp
  14256. };
  14257. switch (description.type) {
  14258. case 'offer':
  14259. this._updateSignalingState('have-local-offer');
  14260. break;
  14261. case 'answer':
  14262. this._updateSignalingState('stable');
  14263. break;
  14264. default:
  14265. throw new TypeError('unsupported type "' + description.type +
  14266. '"');
  14267. }
  14268. // If a success callback was provided, emit ICE candidates after it
  14269. // has been executed. Otherwise, emit callback after the Promise is
  14270. // resolved.
  14271. var hasCallback = arguments.length > 1 &&
  14272. typeof arguments[1] === 'function';
  14273. if (hasCallback) {
  14274. var cb = arguments[1];
  14275. window.setTimeout(function() {
  14276. cb();
  14277. if (self.iceGatheringState === 'new') {
  14278. self.iceGatheringState = 'gathering';
  14279. }
  14280. self._emitBufferedCandidates();
  14281. }, 0);
  14282. }
  14283. var p = Promise.resolve();
  14284. p.then(function() {
  14285. if (!hasCallback) {
  14286. if (self.iceGatheringState === 'new') {
  14287. self.iceGatheringState = 'gathering';
  14288. }
  14289. // Usually candidates will be emitted earlier.
  14290. window.setTimeout(self._emitBufferedCandidates.bind(self), 500);
  14291. }
  14292. });
  14293. return p;
  14294. };
  14295. window.RTCPeerConnection.prototype.setRemoteDescription =
  14296. function(description) {
  14297. var self = this;
  14298. var stream = new MediaStream();
  14299. var receiverList = [];
  14300. var sections = SDPUtils.splitSections(description.sdp);
  14301. var sessionpart = sections.shift();
  14302. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  14303. 'a=ice-lite').length > 0;
  14304. this.usingBundle = SDPUtils.matchPrefix(sessionpart,
  14305. 'a=group:BUNDLE ').length > 0;
  14306. sections.forEach(function(mediaSection, sdpMLineIndex) {
  14307. var lines = SDPUtils.splitLines(mediaSection);
  14308. var mline = lines[0].substr(2).split(' ');
  14309. var kind = mline[0];
  14310. var rejected = mline[1] === '0';
  14311. var direction = SDPUtils.getDirection(mediaSection, sessionpart);
  14312. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:');
  14313. if (mid.length) {
  14314. mid = mid[0].substr(6);
  14315. } else {
  14316. mid = SDPUtils.generateIdentifier();
  14317. }
  14318. // Reject datachannels which are not implemented yet.
  14319. if (kind === 'application' && mline[2] === 'DTLS/SCTP') {
  14320. self.transceivers[sdpMLineIndex] = {
  14321. mid: mid,
  14322. isDatachannel: true
  14323. };
  14324. return;
  14325. }
  14326. var transceiver;
  14327. var iceGatherer;
  14328. var iceTransport;
  14329. var dtlsTransport;
  14330. var rtpSender;
  14331. var rtpReceiver;
  14332. var sendEncodingParameters;
  14333. var recvEncodingParameters;
  14334. var localCapabilities;
  14335. var track;
  14336. // FIXME: ensure the mediaSection has rtcp-mux set.
  14337. var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection);
  14338. var remoteIceParameters;
  14339. var remoteDtlsParameters;
  14340. if (!rejected) {
  14341. remoteIceParameters = SDPUtils.getIceParameters(mediaSection,
  14342. sessionpart);
  14343. remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection,
  14344. sessionpart);
  14345. remoteDtlsParameters.role = 'client';
  14346. }
  14347. recvEncodingParameters =
  14348. SDPUtils.parseRtpEncodingParameters(mediaSection);
  14349. var cname;
  14350. // Gets the first SSRC. Note that with RTX there might be multiple
  14351. // SSRCs.
  14352. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  14353. .map(function(line) {
  14354. return SDPUtils.parseSsrcMedia(line);
  14355. })
  14356. .filter(function(obj) {
  14357. return obj.attribute === 'cname';
  14358. })[0];
  14359. if (remoteSsrc) {
  14360. cname = remoteSsrc.value;
  14361. }
  14362. var isComplete = SDPUtils.matchPrefix(mediaSection,
  14363. 'a=end-of-candidates', sessionpart).length > 0;
  14364. var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
  14365. .map(function(cand) {
  14366. return SDPUtils.parseCandidate(cand);
  14367. })
  14368. .filter(function(cand) {
  14369. return cand.component === '1';
  14370. });
  14371. if (description.type === 'offer' && !rejected) {
  14372. var transports = self.usingBundle && sdpMLineIndex > 0 ? {
  14373. iceGatherer: self.transceivers[0].iceGatherer,
  14374. iceTransport: self.transceivers[0].iceTransport,
  14375. dtlsTransport: self.transceivers[0].dtlsTransport
  14376. } : self._createIceAndDtlsTransports(mid, sdpMLineIndex);
  14377. if (isComplete) {
  14378. transports.iceTransport.setRemoteCandidates(cands);
  14379. }
  14380. localCapabilities = RTCRtpReceiver.getCapabilities(kind);
  14381. // filter RTX until additional stuff needed for RTX is implemented
  14382. // in adapter.js
  14383. localCapabilities.codecs = localCapabilities.codecs.filter(
  14384. function(codec) {
  14385. return codec.name !== 'rtx';
  14386. });
  14387. sendEncodingParameters = [{
  14388. ssrc: (2 * sdpMLineIndex + 2) * 1001
  14389. }];
  14390. rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind);
  14391. track = rtpReceiver.track;
  14392. receiverList.push([track, rtpReceiver]);
  14393. // FIXME: not correct when there are multiple streams but that is
  14394. // not currently supported in this shim.
  14395. stream.addTrack(track);
  14396. // FIXME: look at direction.
  14397. if (self.localStreams.length > 0 &&
  14398. self.localStreams[0].getTracks().length >= sdpMLineIndex) {
  14399. var localTrack;
  14400. if (kind === 'audio') {
  14401. localTrack = self.localStreams[0].getAudioTracks()[0];
  14402. } else if (kind === 'video') {
  14403. localTrack = self.localStreams[0].getVideoTracks()[0];
  14404. }
  14405. if (localTrack) {
  14406. rtpSender = new RTCRtpSender(localTrack,
  14407. transports.dtlsTransport);
  14408. }
  14409. }
  14410. self.transceivers[sdpMLineIndex] = {
  14411. iceGatherer: transports.iceGatherer,
  14412. iceTransport: transports.iceTransport,
  14413. dtlsTransport: transports.dtlsTransport,
  14414. localCapabilities: localCapabilities,
  14415. remoteCapabilities: remoteCapabilities,
  14416. rtpSender: rtpSender,
  14417. rtpReceiver: rtpReceiver,
  14418. kind: kind,
  14419. mid: mid,
  14420. cname: cname,
  14421. sendEncodingParameters: sendEncodingParameters,
  14422. recvEncodingParameters: recvEncodingParameters
  14423. };
  14424. // Start the RTCRtpReceiver now. The RTPSender is started in
  14425. // setLocalDescription.
  14426. self._transceive(self.transceivers[sdpMLineIndex],
  14427. false,
  14428. direction === 'sendrecv' || direction === 'sendonly');
  14429. } else if (description.type === 'answer' && !rejected) {
  14430. transceiver = self.transceivers[sdpMLineIndex];
  14431. iceGatherer = transceiver.iceGatherer;
  14432. iceTransport = transceiver.iceTransport;
  14433. dtlsTransport = transceiver.dtlsTransport;
  14434. rtpSender = transceiver.rtpSender;
  14435. rtpReceiver = transceiver.rtpReceiver;
  14436. sendEncodingParameters = transceiver.sendEncodingParameters;
  14437. localCapabilities = transceiver.localCapabilities;
  14438. self.transceivers[sdpMLineIndex].recvEncodingParameters =
  14439. recvEncodingParameters;
  14440. self.transceivers[sdpMLineIndex].remoteCapabilities =
  14441. remoteCapabilities;
  14442. self.transceivers[sdpMLineIndex].cname = cname;
  14443. if ((isIceLite || isComplete) && cands.length) {
  14444. iceTransport.setRemoteCandidates(cands);
  14445. }
  14446. if (!self.usingBundle || sdpMLineIndex === 0) {
  14447. iceTransport.start(iceGatherer, remoteIceParameters,
  14448. 'controlling');
  14449. dtlsTransport.start(remoteDtlsParameters);
  14450. }
  14451. self._transceive(transceiver,
  14452. direction === 'sendrecv' || direction === 'recvonly',
  14453. direction === 'sendrecv' || direction === 'sendonly');
  14454. if (rtpReceiver &&
  14455. (direction === 'sendrecv' || direction === 'sendonly')) {
  14456. track = rtpReceiver.track;
  14457. receiverList.push([track, rtpReceiver]);
  14458. stream.addTrack(track);
  14459. } else {
  14460. // FIXME: actually the receiver should be created later.
  14461. delete transceiver.rtpReceiver;
  14462. }
  14463. }
  14464. });
  14465. this.remoteDescription = {
  14466. type: description.type,
  14467. sdp: description.sdp
  14468. };
  14469. switch (description.type) {
  14470. case 'offer':
  14471. this._updateSignalingState('have-remote-offer');
  14472. break;
  14473. case 'answer':
  14474. this._updateSignalingState('stable');
  14475. break;
  14476. default:
  14477. throw new TypeError('unsupported type "' + description.type +
  14478. '"');
  14479. }
  14480. if (stream.getTracks().length) {
  14481. self.remoteStreams.push(stream);
  14482. window.setTimeout(function() {
  14483. var event = new Event('addstream');
  14484. event.stream = stream;
  14485. self.dispatchEvent(event);
  14486. if (self.onaddstream !== null) {
  14487. window.setTimeout(function() {
  14488. self.onaddstream(event);
  14489. }, 0);
  14490. }
  14491. receiverList.forEach(function(item) {
  14492. var track = item[0];
  14493. var receiver = item[1];
  14494. var trackEvent = new Event('track');
  14495. trackEvent.track = track;
  14496. trackEvent.receiver = receiver;
  14497. trackEvent.streams = [stream];
  14498. self.dispatchEvent(event);
  14499. if (self.ontrack !== null) {
  14500. window.setTimeout(function() {
  14501. self.ontrack(trackEvent);
  14502. }, 0);
  14503. }
  14504. });
  14505. }, 0);
  14506. }
  14507. if (arguments.length > 1 && typeof arguments[1] === 'function') {
  14508. window.setTimeout(arguments[1], 0);
  14509. }
  14510. return Promise.resolve();
  14511. };
  14512. window.RTCPeerConnection.prototype.close = function() {
  14513. this.transceivers.forEach(function(transceiver) {
  14514. /* not yet
  14515. if (transceiver.iceGatherer) {
  14516. transceiver.iceGatherer.close();
  14517. }
  14518. */
  14519. if (transceiver.iceTransport) {
  14520. transceiver.iceTransport.stop();
  14521. }
  14522. if (transceiver.dtlsTransport) {
  14523. transceiver.dtlsTransport.stop();
  14524. }
  14525. if (transceiver.rtpSender) {
  14526. transceiver.rtpSender.stop();
  14527. }
  14528. if (transceiver.rtpReceiver) {
  14529. transceiver.rtpReceiver.stop();
  14530. }
  14531. });
  14532. // FIXME: clean up tracks, local streams, remote streams, etc
  14533. this._updateSignalingState('closed');
  14534. };
  14535. // Update the signaling state.
  14536. window.RTCPeerConnection.prototype._updateSignalingState =
  14537. function(newState) {
  14538. this.signalingState = newState;
  14539. var event = new Event('signalingstatechange');
  14540. this.dispatchEvent(event);
  14541. if (this.onsignalingstatechange !== null) {
  14542. this.onsignalingstatechange(event);
  14543. }
  14544. };
  14545. // Determine whether to fire the negotiationneeded event.
  14546. window.RTCPeerConnection.prototype._maybeFireNegotiationNeeded =
  14547. function() {
  14548. // Fire away (for now).
  14549. var event = new Event('negotiationneeded');
  14550. this.dispatchEvent(event);
  14551. if (this.onnegotiationneeded !== null) {
  14552. this.onnegotiationneeded(event);
  14553. }
  14554. };
  14555. // Update the connection state.
  14556. window.RTCPeerConnection.prototype._updateConnectionState = function() {
  14557. var self = this;
  14558. var newState;
  14559. var states = {
  14560. 'new': 0,
  14561. closed: 0,
  14562. connecting: 0,
  14563. checking: 0,
  14564. connected: 0,
  14565. completed: 0,
  14566. failed: 0
  14567. };
  14568. this.transceivers.forEach(function(transceiver) {
  14569. states[transceiver.iceTransport.state]++;
  14570. states[transceiver.dtlsTransport.state]++;
  14571. });
  14572. // ICETransport.completed and connected are the same for this purpose.
  14573. states.connected += states.completed;
  14574. newState = 'new';
  14575. if (states.failed > 0) {
  14576. newState = 'failed';
  14577. } else if (states.connecting > 0 || states.checking > 0) {
  14578. newState = 'connecting';
  14579. } else if (states.disconnected > 0) {
  14580. newState = 'disconnected';
  14581. } else if (states.new > 0) {
  14582. newState = 'new';
  14583. } else if (states.connected > 0 || states.completed > 0) {
  14584. newState = 'connected';
  14585. }
  14586. if (newState !== self.iceConnectionState) {
  14587. self.iceConnectionState = newState;
  14588. var event = new Event('iceconnectionstatechange');
  14589. this.dispatchEvent(event);
  14590. if (this.oniceconnectionstatechange !== null) {
  14591. this.oniceconnectionstatechange(event);
  14592. }
  14593. }
  14594. };
  14595. window.RTCPeerConnection.prototype.createOffer = function() {
  14596. var self = this;
  14597. if (this._pendingOffer) {
  14598. throw new Error('createOffer called while there is a pending offer.');
  14599. }
  14600. var offerOptions;
  14601. if (arguments.length === 1 && typeof arguments[0] !== 'function') {
  14602. offerOptions = arguments[0];
  14603. } else if (arguments.length === 3) {
  14604. offerOptions = arguments[2];
  14605. }
  14606. var tracks = [];
  14607. var numAudioTracks = 0;
  14608. var numVideoTracks = 0;
  14609. // Default to sendrecv.
  14610. if (this.localStreams.length) {
  14611. numAudioTracks = this.localStreams[0].getAudioTracks().length;
  14612. numVideoTracks = this.localStreams[0].getVideoTracks().length;
  14613. }
  14614. // Determine number of audio and video tracks we need to send/recv.
  14615. if (offerOptions) {
  14616. // Reject Chrome legacy constraints.
  14617. if (offerOptions.mandatory || offerOptions.optional) {
  14618. throw new TypeError(
  14619. 'Legacy mandatory/optional constraints not supported.');
  14620. }
  14621. if (offerOptions.offerToReceiveAudio !== undefined) {
  14622. numAudioTracks = offerOptions.offerToReceiveAudio;
  14623. }
  14624. if (offerOptions.offerToReceiveVideo !== undefined) {
  14625. numVideoTracks = offerOptions.offerToReceiveVideo;
  14626. }
  14627. }
  14628. if (this.localStreams.length) {
  14629. // Push local streams.
  14630. this.localStreams[0].getTracks().forEach(function(track) {
  14631. tracks.push({
  14632. kind: track.kind,
  14633. track: track,
  14634. wantReceive: track.kind === 'audio' ?
  14635. numAudioTracks > 0 : numVideoTracks > 0
  14636. });
  14637. if (track.kind === 'audio') {
  14638. numAudioTracks--;
  14639. } else if (track.kind === 'video') {
  14640. numVideoTracks--;
  14641. }
  14642. });
  14643. }
  14644. // Create M-lines for recvonly streams.
  14645. while (numAudioTracks > 0 || numVideoTracks > 0) {
  14646. if (numAudioTracks > 0) {
  14647. tracks.push({
  14648. kind: 'audio',
  14649. wantReceive: true
  14650. });
  14651. numAudioTracks--;
  14652. }
  14653. if (numVideoTracks > 0) {
  14654. tracks.push({
  14655. kind: 'video',
  14656. wantReceive: true
  14657. });
  14658. numVideoTracks--;
  14659. }
  14660. }
  14661. var sdp = SDPUtils.writeSessionBoilerplate();
  14662. var transceivers = [];
  14663. tracks.forEach(function(mline, sdpMLineIndex) {
  14664. // For each track, create an ice gatherer, ice transport,
  14665. // dtls transport, potentially rtpsender and rtpreceiver.
  14666. var track = mline.track;
  14667. var kind = mline.kind;
  14668. var mid = SDPUtils.generateIdentifier();
  14669. var transports = self.usingBundle && sdpMLineIndex > 0 ? {
  14670. iceGatherer: transceivers[0].iceGatherer,
  14671. iceTransport: transceivers[0].iceTransport,
  14672. dtlsTransport: transceivers[0].dtlsTransport
  14673. } : self._createIceAndDtlsTransports(mid, sdpMLineIndex);
  14674. var localCapabilities = RTCRtpSender.getCapabilities(kind);
  14675. // filter RTX until additional stuff needed for RTX is implemented
  14676. // in adapter.js
  14677. localCapabilities.codecs = localCapabilities.codecs.filter(
  14678. function(codec) {
  14679. return codec.name !== 'rtx';
  14680. });
  14681. localCapabilities.codecs.forEach(function(codec) {
  14682. // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
  14683. // by adding level-asymmetry-allowed=1
  14684. if (codec.name === 'H264' &&
  14685. codec.parameters['level-asymmetry-allowed'] === undefined) {
  14686. codec.parameters['level-asymmetry-allowed'] = '1';
  14687. }
  14688. });
  14689. var rtpSender;
  14690. var rtpReceiver;
  14691. // generate an ssrc now, to be used later in rtpSender.send
  14692. var sendEncodingParameters = [{
  14693. ssrc: (2 * sdpMLineIndex + 1) * 1001
  14694. }];
  14695. if (track) {
  14696. rtpSender = new RTCRtpSender(track, transports.dtlsTransport);
  14697. }
  14698. if (mline.wantReceive) {
  14699. rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind);
  14700. }
  14701. transceivers[sdpMLineIndex] = {
  14702. iceGatherer: transports.iceGatherer,
  14703. iceTransport: transports.iceTransport,
  14704. dtlsTransport: transports.dtlsTransport,
  14705. localCapabilities: localCapabilities,
  14706. remoteCapabilities: null,
  14707. rtpSender: rtpSender,
  14708. rtpReceiver: rtpReceiver,
  14709. kind: kind,
  14710. mid: mid,
  14711. sendEncodingParameters: sendEncodingParameters,
  14712. recvEncodingParameters: null
  14713. };
  14714. });
  14715. if (this.usingBundle) {
  14716. sdp += 'a=group:BUNDLE ' + transceivers.map(function(t) {
  14717. return t.mid;
  14718. }).join(' ') + '\r\n';
  14719. }
  14720. tracks.forEach(function(mline, sdpMLineIndex) {
  14721. var transceiver = transceivers[sdpMLineIndex];
  14722. sdp += SDPUtils.writeMediaSection(transceiver,
  14723. transceiver.localCapabilities, 'offer', self.localStreams[0]);
  14724. });
  14725. this._pendingOffer = transceivers;
  14726. var desc = new RTCSessionDescription({
  14727. type: 'offer',
  14728. sdp: sdp
  14729. });
  14730. if (arguments.length && typeof arguments[0] === 'function') {
  14731. window.setTimeout(arguments[0], 0, desc);
  14732. }
  14733. return Promise.resolve(desc);
  14734. };
  14735. window.RTCPeerConnection.prototype.createAnswer = function() {
  14736. var self = this;
  14737. var sdp = SDPUtils.writeSessionBoilerplate();
  14738. if (this.usingBundle) {
  14739. sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) {
  14740. return t.mid;
  14741. }).join(' ') + '\r\n';
  14742. }
  14743. this.transceivers.forEach(function(transceiver) {
  14744. if (transceiver.isDatachannel) {
  14745. sdp += 'm=application 0 DTLS/SCTP 5000\r\n' +
  14746. 'c=IN IP4 0.0.0.0\r\n' +
  14747. 'a=mid:' + transceiver.mid + '\r\n';
  14748. return;
  14749. }
  14750. // Calculate intersection of capabilities.
  14751. var commonCapabilities = self._getCommonCapabilities(
  14752. transceiver.localCapabilities,
  14753. transceiver.remoteCapabilities);
  14754. sdp += SDPUtils.writeMediaSection(transceiver, commonCapabilities,
  14755. 'answer', self.localStreams[0]);
  14756. });
  14757. var desc = new RTCSessionDescription({
  14758. type: 'answer',
  14759. sdp: sdp
  14760. });
  14761. if (arguments.length && typeof arguments[0] === 'function') {
  14762. window.setTimeout(arguments[0], 0, desc);
  14763. }
  14764. return Promise.resolve(desc);
  14765. };
  14766. window.RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
  14767. if (!candidate) {
  14768. this.transceivers.forEach(function(transceiver) {
  14769. transceiver.iceTransport.addRemoteCandidate({});
  14770. });
  14771. } else {
  14772. var mLineIndex = candidate.sdpMLineIndex;
  14773. if (candidate.sdpMid) {
  14774. for (var i = 0; i < this.transceivers.length; i++) {
  14775. if (this.transceivers[i].mid === candidate.sdpMid) {
  14776. mLineIndex = i;
  14777. break;
  14778. }
  14779. }
  14780. }
  14781. var transceiver = this.transceivers[mLineIndex];
  14782. if (transceiver) {
  14783. var cand = Object.keys(candidate.candidate).length > 0 ?
  14784. SDPUtils.parseCandidate(candidate.candidate) : {};
  14785. // Ignore Chrome's invalid candidates since Edge does not like them.
  14786. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
  14787. return;
  14788. }
  14789. // Ignore RTCP candidates, we assume RTCP-MUX.
  14790. if (cand.component !== '1') {
  14791. return;
  14792. }
  14793. // A dirty hack to make samples work.
  14794. if (cand.type === 'endOfCandidates') {
  14795. cand = {};
  14796. }
  14797. transceiver.iceTransport.addRemoteCandidate(cand);
  14798. // update the remoteDescription.
  14799. var sections = SDPUtils.splitSections(this.remoteDescription.sdp);
  14800. sections[mLineIndex + 1] += (cand.type ? candidate.candidate.trim()
  14801. : 'a=end-of-candidates') + '\r\n';
  14802. this.remoteDescription.sdp = sections.join('');
  14803. }
  14804. }
  14805. if (arguments.length > 1 && typeof arguments[1] === 'function') {
  14806. window.setTimeout(arguments[1], 0);
  14807. }
  14808. return Promise.resolve();
  14809. };
  14810. window.RTCPeerConnection.prototype.getStats = function() {
  14811. var promises = [];
  14812. this.transceivers.forEach(function(transceiver) {
  14813. ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
  14814. 'dtlsTransport'].forEach(function(method) {
  14815. if (transceiver[method]) {
  14816. promises.push(transceiver[method].getStats());
  14817. }
  14818. });
  14819. });
  14820. var cb = arguments.length > 1 && typeof arguments[1] === 'function' &&
  14821. arguments[1];
  14822. return new Promise(function(resolve) {
  14823. // shim getStats with maplike support
  14824. var results = new Map();
  14825. Promise.all(promises).then(function(res) {
  14826. res.forEach(function(result) {
  14827. Object.keys(result).forEach(function(id) {
  14828. results.set(id, result[id]);
  14829. results[id] = result[id];
  14830. });
  14831. });
  14832. if (cb) {
  14833. window.setTimeout(cb, 0, results);
  14834. }
  14835. resolve(results);
  14836. });
  14837. });
  14838. };
  14839. }
  14840. };
  14841. // Expose public methods.
  14842. module.exports = {
  14843. shimPeerConnection: edgeShim.shimPeerConnection,
  14844. shimGetUserMedia: require('./getusermedia')
  14845. };
  14846. },{"../utils":98,"./getusermedia":94,"sdp":62}],94:[function(require,module,exports){
  14847. arguments[4][34][0].apply(exports,arguments)
  14848. },{"dup":34}],95:[function(require,module,exports){
  14849. /*
  14850. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  14851. *
  14852. * Use of this source code is governed by a BSD-style license
  14853. * that can be found in the LICENSE file in the root of the source
  14854. * tree.
  14855. */
  14856. /* eslint-env node */
  14857. 'use strict';
  14858. var browserDetails = require('../utils').browserDetails;
  14859. var firefoxShim = {
  14860. shimOnTrack: function() {
  14861. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  14862. window.RTCPeerConnection.prototype)) {
  14863. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  14864. get: function() {
  14865. return this._ontrack;
  14866. },
  14867. set: function(f) {
  14868. if (this._ontrack) {
  14869. this.removeEventListener('track', this._ontrack);
  14870. this.removeEventListener('addstream', this._ontrackpoly);
  14871. }
  14872. this.addEventListener('track', this._ontrack = f);
  14873. this.addEventListener('addstream', this._ontrackpoly = function(e) {
  14874. e.stream.getTracks().forEach(function(track) {
  14875. var event = new Event('track');
  14876. event.track = track;
  14877. event.receiver = {track: track};
  14878. event.streams = [e.stream];
  14879. this.dispatchEvent(event);
  14880. }.bind(this));
  14881. }.bind(this));
  14882. }
  14883. });
  14884. }
  14885. },
  14886. shimSourceObject: function() {
  14887. // Firefox has supported mozSrcObject since FF22, unprefixed in 42.
  14888. if (typeof window === 'object') {
  14889. if (window.HTMLMediaElement &&
  14890. !('srcObject' in window.HTMLMediaElement.prototype)) {
  14891. // Shim the srcObject property, once, when HTMLMediaElement is found.
  14892. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
  14893. get: function() {
  14894. return this.mozSrcObject;
  14895. },
  14896. set: function(stream) {
  14897. this.mozSrcObject = stream;
  14898. }
  14899. });
  14900. }
  14901. }
  14902. },
  14903. shimPeerConnection: function() {
  14904. if (typeof window !== 'object' || !(window.RTCPeerConnection ||
  14905. window.mozRTCPeerConnection)) {
  14906. return; // probably media.peerconnection.enabled=false in about:config
  14907. }
  14908. // The RTCPeerConnection object.
  14909. if (!window.RTCPeerConnection) {
  14910. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  14911. if (browserDetails.version < 38) {
  14912. // .urls is not supported in FF < 38.
  14913. // create RTCIceServers with a single url.
  14914. if (pcConfig && pcConfig.iceServers) {
  14915. var newIceServers = [];
  14916. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  14917. var server = pcConfig.iceServers[i];
  14918. if (server.hasOwnProperty('urls')) {
  14919. for (var j = 0; j < server.urls.length; j++) {
  14920. var newServer = {
  14921. url: server.urls[j]
  14922. };
  14923. if (server.urls[j].indexOf('turn') === 0) {
  14924. newServer.username = server.username;
  14925. newServer.credential = server.credential;
  14926. }
  14927. newIceServers.push(newServer);
  14928. }
  14929. } else {
  14930. newIceServers.push(pcConfig.iceServers[i]);
  14931. }
  14932. }
  14933. pcConfig.iceServers = newIceServers;
  14934. }
  14935. }
  14936. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  14937. };
  14938. window.RTCPeerConnection.prototype = mozRTCPeerConnection.prototype;
  14939. // wrap static methods. Currently just generateCertificate.
  14940. if (mozRTCPeerConnection.generateCertificate) {
  14941. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  14942. get: function() {
  14943. return mozRTCPeerConnection.generateCertificate;
  14944. }
  14945. });
  14946. }
  14947. window.RTCSessionDescription = mozRTCSessionDescription;
  14948. window.RTCIceCandidate = mozRTCIceCandidate;
  14949. }
  14950. // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
  14951. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  14952. .forEach(function(method) {
  14953. var nativeMethod = RTCPeerConnection.prototype[method];
  14954. RTCPeerConnection.prototype[method] = function() {
  14955. arguments[0] = new ((method === 'addIceCandidate') ?
  14956. RTCIceCandidate : RTCSessionDescription)(arguments[0]);
  14957. return nativeMethod.apply(this, arguments);
  14958. };
  14959. });
  14960. // support for addIceCandidate(null or undefined)
  14961. var nativeAddIceCandidate =
  14962. RTCPeerConnection.prototype.addIceCandidate;
  14963. RTCPeerConnection.prototype.addIceCandidate = function() {
  14964. if (!arguments[0]) {
  14965. if (arguments[1]) {
  14966. arguments[1].apply(null);
  14967. }
  14968. return Promise.resolve();
  14969. }
  14970. return nativeAddIceCandidate.apply(this, arguments);
  14971. };
  14972. if (browserDetails.version < 48) {
  14973. // shim getStats with maplike support
  14974. var makeMapStats = function(stats) {
  14975. var map = new Map();
  14976. Object.keys(stats).forEach(function(key) {
  14977. map.set(key, stats[key]);
  14978. map[key] = stats[key];
  14979. });
  14980. return map;
  14981. };
  14982. var nativeGetStats = RTCPeerConnection.prototype.getStats;
  14983. RTCPeerConnection.prototype.getStats = function(selector, onSucc, onErr) {
  14984. return nativeGetStats.apply(this, [selector || null])
  14985. .then(function(stats) {
  14986. return makeMapStats(stats);
  14987. })
  14988. .then(onSucc, onErr);
  14989. };
  14990. }
  14991. }
  14992. };
  14993. // Expose public methods.
  14994. module.exports = {
  14995. shimOnTrack: firefoxShim.shimOnTrack,
  14996. shimSourceObject: firefoxShim.shimSourceObject,
  14997. shimPeerConnection: firefoxShim.shimPeerConnection,
  14998. shimGetUserMedia: require('./getusermedia')
  14999. };
  15000. },{"../utils":98,"./getusermedia":96}],96:[function(require,module,exports){
  15001. /*
  15002. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  15003. *
  15004. * Use of this source code is governed by a BSD-style license
  15005. * that can be found in the LICENSE file in the root of the source
  15006. * tree.
  15007. */
  15008. /* eslint-env node */
  15009. 'use strict';
  15010. var logging = require('../utils').log;
  15011. var browserDetails = require('../utils').browserDetails;
  15012. // Expose public methods.
  15013. module.exports = function() {
  15014. var shimError_ = function(e) {
  15015. return {
  15016. name: {
  15017. SecurityError: 'NotAllowedError',
  15018. PermissionDeniedError: 'NotAllowedError'
  15019. }[e.name] || e.name,
  15020. message: {
  15021. 'The operation is insecure.': 'The request is not allowed by the ' +
  15022. 'user agent or the platform in the current context.'
  15023. }[e.message] || e.message,
  15024. constraint: e.constraint,
  15025. toString: function() {
  15026. return this.name + (this.message && ': ') + this.message;
  15027. }
  15028. };
  15029. };
  15030. // getUserMedia constraints shim.
  15031. var getUserMedia_ = function(constraints, onSuccess, onError) {
  15032. var constraintsToFF37_ = function(c) {
  15033. if (typeof c !== 'object' || c.require) {
  15034. return c;
  15035. }
  15036. var require = [];
  15037. Object.keys(c).forEach(function(key) {
  15038. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  15039. return;
  15040. }
  15041. var r = c[key] = (typeof c[key] === 'object') ?
  15042. c[key] : {ideal: c[key]};
  15043. if (r.min !== undefined ||
  15044. r.max !== undefined || r.exact !== undefined) {
  15045. require.push(key);
  15046. }
  15047. if (r.exact !== undefined) {
  15048. if (typeof r.exact === 'number') {
  15049. r. min = r.max = r.exact;
  15050. } else {
  15051. c[key] = r.exact;
  15052. }
  15053. delete r.exact;
  15054. }
  15055. if (r.ideal !== undefined) {
  15056. c.advanced = c.advanced || [];
  15057. var oc = {};
  15058. if (typeof r.ideal === 'number') {
  15059. oc[key] = {min: r.ideal, max: r.ideal};
  15060. } else {
  15061. oc[key] = r.ideal;
  15062. }
  15063. c.advanced.push(oc);
  15064. delete r.ideal;
  15065. if (!Object.keys(r).length) {
  15066. delete c[key];
  15067. }
  15068. }
  15069. });
  15070. if (require.length) {
  15071. c.require = require;
  15072. }
  15073. return c;
  15074. };
  15075. constraints = JSON.parse(JSON.stringify(constraints));
  15076. if (browserDetails.version < 38) {
  15077. logging('spec: ' + JSON.stringify(constraints));
  15078. if (constraints.audio) {
  15079. constraints.audio = constraintsToFF37_(constraints.audio);
  15080. }
  15081. if (constraints.video) {
  15082. constraints.video = constraintsToFF37_(constraints.video);
  15083. }
  15084. logging('ff37: ' + JSON.stringify(constraints));
  15085. }
  15086. return navigator.mozGetUserMedia(constraints, onSuccess, function(e) {
  15087. onError(shimError_(e));
  15088. });
  15089. };
  15090. // Returns the result of getUserMedia as a Promise.
  15091. var getUserMediaPromise_ = function(constraints) {
  15092. return new Promise(function(resolve, reject) {
  15093. getUserMedia_(constraints, resolve, reject);
  15094. });
  15095. };
  15096. // Shim for mediaDevices on older versions.
  15097. if (!navigator.mediaDevices) {
  15098. navigator.mediaDevices = {getUserMedia: getUserMediaPromise_,
  15099. addEventListener: function() { },
  15100. removeEventListener: function() { }
  15101. };
  15102. }
  15103. navigator.mediaDevices.enumerateDevices =
  15104. navigator.mediaDevices.enumerateDevices || function() {
  15105. return new Promise(function(resolve) {
  15106. var infos = [
  15107. {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
  15108. {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
  15109. ];
  15110. resolve(infos);
  15111. });
  15112. };
  15113. if (browserDetails.version < 41) {
  15114. // Work around http://bugzil.la/1169665
  15115. var orgEnumerateDevices =
  15116. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
  15117. navigator.mediaDevices.enumerateDevices = function() {
  15118. return orgEnumerateDevices().then(undefined, function(e) {
  15119. if (e.name === 'NotFoundError') {
  15120. return [];
  15121. }
  15122. throw e;
  15123. });
  15124. };
  15125. }
  15126. if (browserDetails.version < 49) {
  15127. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  15128. bind(navigator.mediaDevices);
  15129. navigator.mediaDevices.getUserMedia = function(c) {
  15130. return origGetUserMedia(c).then(function(stream) {
  15131. // Work around https://bugzil.la/802326
  15132. if (c.audio && !stream.getAudioTracks().length ||
  15133. c.video && !stream.getVideoTracks().length) {
  15134. stream.getTracks().forEach(function(track) {
  15135. track.stop();
  15136. });
  15137. throw new DOMException('The object can not be found here.',
  15138. 'NotFoundError');
  15139. }
  15140. return stream;
  15141. }, function(e) {
  15142. return Promise.reject(shimError_(e));
  15143. });
  15144. };
  15145. }
  15146. navigator.getUserMedia = function(constraints, onSuccess, onError) {
  15147. if (browserDetails.version < 44) {
  15148. return getUserMedia_(constraints, onSuccess, onError);
  15149. }
  15150. // Replace Firefox 44+'s deprecation warning with unprefixed version.
  15151. console.warn('navigator.getUserMedia has been replaced by ' +
  15152. 'navigator.mediaDevices.getUserMedia');
  15153. navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  15154. };
  15155. };
  15156. },{"../utils":98}],97:[function(require,module,exports){
  15157. /*
  15158. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  15159. *
  15160. * Use of this source code is governed by a BSD-style license
  15161. * that can be found in the LICENSE file in the root of the source
  15162. * tree.
  15163. */
  15164. 'use strict';
  15165. var safariShim = {
  15166. // TODO: DrAlex, should be here, double check against LayoutTests
  15167. // shimOnTrack: function() { },
  15168. // TODO: once the back-end for the mac port is done, add.
  15169. // TODO: check for webkitGTK+
  15170. // shimPeerConnection: function() { },
  15171. shimGetUserMedia: function() {
  15172. navigator.getUserMedia = navigator.webkitGetUserMedia;
  15173. }
  15174. };
  15175. // Expose public methods.
  15176. module.exports = {
  15177. shimGetUserMedia: safariShim.shimGetUserMedia
  15178. // TODO
  15179. // shimOnTrack: safariShim.shimOnTrack,
  15180. // shimPeerConnection: safariShim.shimPeerConnection
  15181. };
  15182. },{}],98:[function(require,module,exports){
  15183. /*
  15184. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  15185. *
  15186. * Use of this source code is governed by a BSD-style license
  15187. * that can be found in the LICENSE file in the root of the source
  15188. * tree.
  15189. */
  15190. /* eslint-env node */
  15191. 'use strict';
  15192. var logDisabled_ = true;
  15193. // Utility methods.
  15194. var utils = {
  15195. disableLog: function(bool) {
  15196. if (typeof bool !== 'boolean') {
  15197. return new Error('Argument type: ' + typeof bool +
  15198. '. Please use a boolean.');
  15199. }
  15200. logDisabled_ = bool;
  15201. return (bool) ? 'adapter.js logging disabled' :
  15202. 'adapter.js logging enabled';
  15203. },
  15204. log: function() {
  15205. if (typeof window === 'object') {
  15206. if (logDisabled_) {
  15207. return;
  15208. }
  15209. if (typeof console !== 'undefined' && typeof console.log === 'function') {
  15210. console.log.apply(console, arguments);
  15211. }
  15212. }
  15213. },
  15214. /**
  15215. * Extract browser version out of the provided user agent string.
  15216. *
  15217. * @param {!string} uastring userAgent string.
  15218. * @param {!string} expr Regular expression used as match criteria.
  15219. * @param {!number} pos position in the version string to be returned.
  15220. * @return {!number} browser version.
  15221. */
  15222. extractVersion: function(uastring, expr, pos) {
  15223. var match = uastring.match(expr);
  15224. return match && match.length >= pos && parseInt(match[pos], 10);
  15225. },
  15226. /**
  15227. * Browser detector.
  15228. *
  15229. * @return {object} result containing browser and version
  15230. * properties.
  15231. */
  15232. detectBrowser: function() {
  15233. // Returned result object.
  15234. var result = {};
  15235. result.browser = null;
  15236. result.version = null;
  15237. // Fail early if it's not a browser
  15238. if (typeof window === 'undefined' || !window.navigator) {
  15239. result.browser = 'Not a browser.';
  15240. return result;
  15241. }
  15242. // Firefox.
  15243. if (navigator.mozGetUserMedia) {
  15244. result.browser = 'firefox';
  15245. result.version = this.extractVersion(navigator.userAgent,
  15246. /Firefox\/([0-9]+)\./, 1);
  15247. // all webkit-based browsers
  15248. } else if (navigator.webkitGetUserMedia) {
  15249. // Chrome, Chromium, Webview, Opera, all use the chrome shim for now
  15250. if (window.webkitRTCPeerConnection) {
  15251. result.browser = 'chrome';
  15252. result.version = this.extractVersion(navigator.userAgent,
  15253. /Chrom(e|ium)\/([0-9]+)\./, 2);
  15254. // Safari or unknown webkit-based
  15255. // for the time being Safari has support for MediaStreams but not webRTC
  15256. } else {
  15257. // Safari UA substrings of interest for reference:
  15258. // - webkit version: AppleWebKit/602.1.25 (also used in Op,Cr)
  15259. // - safari UI version: Version/9.0.3 (unique to Safari)
  15260. // - safari UI webkit version: Safari/601.4.4 (also used in Op,Cr)
  15261. //
  15262. // if the webkit version and safari UI webkit versions are equals,
  15263. // ... this is a stable version.
  15264. //
  15265. // only the internal webkit version is important today to know if
  15266. // media streams are supported
  15267. //
  15268. if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) {
  15269. result.browser = 'safari';
  15270. result.version = this.extractVersion(navigator.userAgent,
  15271. /AppleWebKit\/([0-9]+)\./, 1);
  15272. // unknown webkit-based browser
  15273. } else {
  15274. result.browser = 'Unsupported webkit-based browser ' +
  15275. 'with GUM support but no WebRTC support.';
  15276. return result;
  15277. }
  15278. }
  15279. // Edge.
  15280. } else if (navigator.mediaDevices &&
  15281. navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) {
  15282. result.browser = 'edge';
  15283. result.version = this.extractVersion(navigator.userAgent,
  15284. /Edge\/(\d+).(\d+)$/, 2);
  15285. // Default fallthrough: not supported.
  15286. } else {
  15287. result.browser = 'Not a supported browser.';
  15288. return result;
  15289. }
  15290. return result;
  15291. }
  15292. };
  15293. // Export.
  15294. module.exports = {
  15295. log: utils.log,
  15296. disableLog: utils.disableLog,
  15297. browserDetails: utils.detectBrowser(),
  15298. extractVersion: utils.extractVersion
  15299. };
  15300. },{}],99:[function(require,module,exports){
  15301. // created by @HenrikJoreteg
  15302. var prefix;
  15303. var version;
  15304. if (window.mozRTCPeerConnection || navigator.mozGetUserMedia) {
  15305. prefix = 'moz';
  15306. version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  15307. } else if (window.webkitRTCPeerConnection || navigator.webkitGetUserMedia) {
  15308. prefix = 'webkit';
  15309. version = navigator.userAgent.match(/Chrom(e|ium)/) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  15310. }
  15311. var PC = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  15312. var IceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
  15313. var SessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
  15314. var MediaStream = window.webkitMediaStream || window.MediaStream;
  15315. var screenSharing = window.location.protocol === 'https:' &&
  15316. ((prefix === 'webkit' && version >= 26) ||
  15317. (prefix === 'moz' && version >= 33))
  15318. var AudioContext = window.AudioContext || window.webkitAudioContext;
  15319. var videoEl = document.createElement('video');
  15320. var supportVp8 = videoEl && videoEl.canPlayType && videoEl.canPlayType('video/webm; codecs="vp8", vorbis') === "probably";
  15321. var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia || navigator.mozGetUserMedia;
  15322. // export support flags and constructors.prototype && PC
  15323. module.exports = {
  15324. prefix: prefix,
  15325. browserVersion: version,
  15326. support: !!PC && !!getUserMedia,
  15327. // new support style
  15328. supportRTCPeerConnection: !!PC,
  15329. supportVp8: supportVp8,
  15330. supportGetUserMedia: !!getUserMedia,
  15331. supportDataChannel: !!(PC && PC.prototype && PC.prototype.createDataChannel),
  15332. supportWebAudio: !!(AudioContext && AudioContext.prototype.createMediaStreamSource),
  15333. supportMediaStream: !!(MediaStream && MediaStream.prototype.removeTrack),
  15334. supportScreenSharing: !!screenSharing,
  15335. // constructors
  15336. AudioContext: AudioContext,
  15337. PeerConnection: PC,
  15338. SessionDescription: SessionDescription,
  15339. IceCandidate: IceCandidate,
  15340. MediaStream: MediaStream,
  15341. getUserMedia: getUserMedia
  15342. };
  15343. },{}],100:[function(require,module,exports){
  15344. /*
  15345. WildEmitter.js is a slim little event emitter by @henrikjoreteg largely based
  15346. on @visionmedia's Emitter from UI Kit.
  15347. Why? I wanted it standalone.
  15348. I also wanted support for wildcard emitters like this:
  15349. emitter.on('*', function (eventName, other, event, payloads) {
  15350. });
  15351. emitter.on('somenamespace*', function (eventName, payloads) {
  15352. });
  15353. Please note that callbacks triggered by wildcard registered events also get
  15354. the event name as the first argument.
  15355. */
  15356. module.exports = WildEmitter;
  15357. function WildEmitter() { }
  15358. WildEmitter.mixin = function (constructor) {
  15359. var prototype = constructor.prototype || constructor;
  15360. prototype.isWildEmitter= true;
  15361. // Listen on the given `event` with `fn`. Store a group name if present.
  15362. prototype.on = function (event, groupName, fn) {
  15363. this.callbacks = this.callbacks || {};
  15364. var hasGroup = (arguments.length === 3),
  15365. group = hasGroup ? arguments[1] : undefined,
  15366. func = hasGroup ? arguments[2] : arguments[1];
  15367. func._groupName = group;
  15368. (this.callbacks[event] = this.callbacks[event] || []).push(func);
  15369. return this;
  15370. };
  15371. // Adds an `event` listener that will be invoked a single
  15372. // time then automatically removed.
  15373. prototype.once = function (event, groupName, fn) {
  15374. var self = this,
  15375. hasGroup = (arguments.length === 3),
  15376. group = hasGroup ? arguments[1] : undefined,
  15377. func = hasGroup ? arguments[2] : arguments[1];
  15378. function on() {
  15379. self.off(event, on);
  15380. func.apply(this, arguments);
  15381. }
  15382. this.on(event, group, on);
  15383. return this;
  15384. };
  15385. // Unbinds an entire group
  15386. prototype.releaseGroup = function (groupName) {
  15387. this.callbacks = this.callbacks || {};
  15388. var item, i, len, handlers;
  15389. for (item in this.callbacks) {
  15390. handlers = this.callbacks[item];
  15391. for (i = 0, len = handlers.length; i < len; i++) {
  15392. if (handlers[i]._groupName === groupName) {
  15393. //console.log('removing');
  15394. // remove it and shorten the array we're looping through
  15395. handlers.splice(i, 1);
  15396. i--;
  15397. len--;
  15398. }
  15399. }
  15400. }
  15401. return this;
  15402. };
  15403. // Remove the given callback for `event` or all
  15404. // registered callbacks.
  15405. prototype.off = function (event, fn) {
  15406. this.callbacks = this.callbacks || {};
  15407. var callbacks = this.callbacks[event],
  15408. i;
  15409. if (!callbacks) return this;
  15410. // remove all handlers
  15411. if (arguments.length === 1) {
  15412. delete this.callbacks[event];
  15413. return this;
  15414. }
  15415. // remove specific handler
  15416. i = callbacks.indexOf(fn);
  15417. callbacks.splice(i, 1);
  15418. if (callbacks.length === 0) {
  15419. delete this.callbacks[event];
  15420. }
  15421. return this;
  15422. };
  15423. /// Emit `event` with the given args.
  15424. // also calls any `*` handlers
  15425. prototype.emit = function (event) {
  15426. this.callbacks = this.callbacks || {};
  15427. var args = [].slice.call(arguments, 1),
  15428. callbacks = this.callbacks[event],
  15429. specialCallbacks = this.getWildcardCallbacks(event),
  15430. i,
  15431. len,
  15432. item,
  15433. listeners;
  15434. if (callbacks) {
  15435. listeners = callbacks.slice();
  15436. for (i = 0, len = listeners.length; i < len; ++i) {
  15437. if (!listeners[i]) {
  15438. break;
  15439. }
  15440. listeners[i].apply(this, args);
  15441. }
  15442. }
  15443. if (specialCallbacks) {
  15444. len = specialCallbacks.length;
  15445. listeners = specialCallbacks.slice();
  15446. for (i = 0, len = listeners.length; i < len; ++i) {
  15447. if (!listeners[i]) {
  15448. break;
  15449. }
  15450. listeners[i].apply(this, [event].concat(args));
  15451. }
  15452. }
  15453. return this;
  15454. };
  15455. // Helper for for finding special wildcard event handlers that match the event
  15456. prototype.getWildcardCallbacks = function (eventName) {
  15457. this.callbacks = this.callbacks || {};
  15458. var item,
  15459. split,
  15460. result = [];
  15461. for (item in this.callbacks) {
  15462. split = item.split('*');
  15463. if (item === '*' || (split.length === 2 && eventName.slice(0, split[0].length) === split[0])) {
  15464. result = result.concat(this.callbacks[item]);
  15465. }
  15466. }
  15467. return result;
  15468. };
  15469. };
  15470. WildEmitter.mixin(WildEmitter);
  15471. },{}],101:[function(require,module,exports){
  15472. /**
  15473. * Module dependencies.
  15474. */
  15475. var global = (function() { return this; })();
  15476. /**
  15477. * WebSocket constructor.
  15478. */
  15479. var WebSocket = global.WebSocket || global.MozWebSocket;
  15480. /**
  15481. * Module exports.
  15482. */
  15483. module.exports = WebSocket ? ws : null;
  15484. /**
  15485. * WebSocket constructor.
  15486. *
  15487. * The third `opts` options object gets ignored in web browsers, since it's
  15488. * non-standard, and throws a TypeError if passed to the constructor.
  15489. * See: https://github.com/einaros/ws/issues/227
  15490. *
  15491. * @param {String} uri
  15492. * @param {Array} protocols (optional)
  15493. * @param {Object) opts (optional)
  15494. * @api public
  15495. */
  15496. function ws(uri, protocols, opts) {
  15497. var instance;
  15498. if (protocols) {
  15499. instance = new WebSocket(uri, protocols);
  15500. } else {
  15501. instance = new WebSocket(uri);
  15502. }
  15503. return instance;
  15504. }
  15505. if (WebSocket) ws.prototype = WebSocket.prototype;
  15506. },{}],102:[function(require,module,exports){
  15507. var util = require('util');
  15508. var webrtcSupport = require('webrtcsupport');
  15509. var PeerConnection = require('rtcpeerconnection');
  15510. var WildEmitter = require('wildemitter');
  15511. var FileTransfer = require('filetransfer');
  15512. // the inband-v1 protocol is sending metadata inband in a serialized JSON object
  15513. // followed by the actual data. Receiver closes the datachannel upon completion
  15514. var INBAND_FILETRANSFER_V1 = 'https://simplewebrtc.com/protocol/filetransfer#inband-v1';
  15515. function isAllTracksEnded(stream) {
  15516. var isAllTracksEnded = true;
  15517. stream.getTracks().forEach(function (t) {
  15518. isAllTracksEnded = t.readyState === 'ended' && isAllTracksEnded;
  15519. });
  15520. return isAllTracksEnded;
  15521. }
  15522. function Peer(options) {
  15523. var self = this;
  15524. // call emitter constructor
  15525. WildEmitter.call(this);
  15526. this.id = options.id;
  15527. this.parent = options.parent;
  15528. this.type = options.type || 'video';
  15529. this.oneway = options.oneway || false;
  15530. this.sharemyscreen = options.sharemyscreen || false;
  15531. this.browserPrefix = options.prefix;
  15532. this.stream = options.stream;
  15533. this.enableDataChannels = options.enableDataChannels === undefined ? this.parent.config.enableDataChannels : options.enableDataChannels;
  15534. this.receiveMedia = options.receiveMedia || this.parent.config.receiveMedia;
  15535. this.channels = {};
  15536. this.sid = options.sid || Date.now().toString();
  15537. // Create an RTCPeerConnection via the polyfill
  15538. this.pc = new PeerConnection(this.parent.config.peerConnectionConfig, this.parent.config.peerConnectionConstraints);
  15539. this.pc.on('ice', this.onIceCandidate.bind(this));
  15540. this.pc.on('endOfCandidates', function (event) {
  15541. self.send('endOfCandidates', event);
  15542. });
  15543. this.pc.on('offer', function (offer) {
  15544. if (self.parent.config.nick) offer.nick = self.parent.config.nick;
  15545. self.send('offer', offer);
  15546. });
  15547. this.pc.on('answer', function (answer) {
  15548. if (self.parent.config.nick) answer.nick = self.parent.config.nick;
  15549. self.send('answer', answer);
  15550. });
  15551. this.pc.on('addStream', this.handleRemoteStreamAdded.bind(this));
  15552. this.pc.on('addChannel', this.handleDataChannelAdded.bind(this));
  15553. this.pc.on('removeStream', this.handleStreamRemoved.bind(this));
  15554. // Just fire negotiation needed events for now
  15555. // When browser re-negotiation handling seems to work
  15556. // we can use this as the trigger for starting the offer/answer process
  15557. // automatically. We'll just leave it be for now while this stabalizes.
  15558. this.pc.on('negotiationNeeded', this.emit.bind(this, 'negotiationNeeded'));
  15559. this.pc.on('iceConnectionStateChange', this.emit.bind(this, 'iceConnectionStateChange'));
  15560. this.pc.on('iceConnectionStateChange', function () {
  15561. switch (self.pc.iceConnectionState) {
  15562. case 'failed':
  15563. // currently, in chrome only the initiator goes to failed
  15564. // so we need to signal this to the peer
  15565. if (self.pc.pc.peerconnection.localDescription.type === 'offer') {
  15566. self.parent.emit('iceFailed', self);
  15567. self.send('connectivityError');
  15568. }
  15569. break;
  15570. }
  15571. });
  15572. this.pc.on('signalingStateChange', this.emit.bind(this, 'signalingStateChange'));
  15573. this.logger = this.parent.logger;
  15574. // handle screensharing/broadcast mode
  15575. if (options.type === 'screen') {
  15576. if (this.parent.localScreen && this.sharemyscreen) {
  15577. this.logger.log('adding local screen stream to peer connection');
  15578. this.pc.addStream(this.parent.localScreen);
  15579. this.broadcaster = options.broadcaster;
  15580. }
  15581. } else {
  15582. this.parent.localStreams.forEach(function (stream) {
  15583. self.pc.addStream(stream);
  15584. });
  15585. }
  15586. this.on('channelOpen', function (channel) {
  15587. if (channel.protocol === INBAND_FILETRANSFER_V1) {
  15588. channel.onmessage = function (event) {
  15589. var metadata = JSON.parse(event.data);
  15590. var receiver = new FileTransfer.Receiver();
  15591. receiver.receive(metadata, channel);
  15592. self.emit('fileTransfer', metadata, receiver);
  15593. receiver.on('receivedFile', function (file, metadata) {
  15594. receiver.channel.close();
  15595. });
  15596. };
  15597. }
  15598. });
  15599. // proxy events to parent
  15600. this.on('*', function () {
  15601. self.parent.emit.apply(self.parent, arguments);
  15602. });
  15603. }
  15604. util.inherits(Peer, WildEmitter);
  15605. Peer.prototype.handleMessage = function (message) {
  15606. var self = this;
  15607. this.logger.log('getting', message.type, message);
  15608. if (message.prefix) this.browserPrefix = message.prefix;
  15609. if (message.type === 'offer') {
  15610. if (!this.nick) this.nick = message.payload.nick;
  15611. delete message.payload.nick;
  15612. this.pc.handleOffer(message.payload, function (err) {
  15613. if (err) {
  15614. return;
  15615. }
  15616. // auto-accept
  15617. self.pc.answer(function (err, sessionDescription) {
  15618. //self.send('answer', sessionDescription);
  15619. });
  15620. });
  15621. } else if (message.type === 'answer') {
  15622. if (!this.nick) this.nick = message.payload.nick;
  15623. delete message.payload.nick;
  15624. this.pc.handleAnswer(message.payload);
  15625. } else if (message.type === 'candidate') {
  15626. this.pc.processIce(message.payload);
  15627. } else if (message.type === 'connectivityError') {
  15628. this.parent.emit('connectivityError', self);
  15629. } else if (message.type === 'mute') {
  15630. this.parent.emit('mute', {id: message.from, name: message.payload.name});
  15631. } else if (message.type === 'unmute') {
  15632. this.parent.emit('unmute', {id: message.from, name: message.payload.name});
  15633. } else if (message.type === 'endOfCandidates') {
  15634. // Edge requires an end-of-candidates. Since only Edge will have mLines or tracks on the
  15635. // shim this will only be called in Edge.
  15636. var mLines = this.pc.pc.peerconnection.transceivers || [];
  15637. mLines.forEach(function (mLine) {
  15638. if (mLine.iceTransport) {
  15639. mLine.iceTransport.addRemoteCandidate({});
  15640. }
  15641. });
  15642. }
  15643. };
  15644. // send via signalling channel
  15645. Peer.prototype.send = function (messageType, payload) {
  15646. var message = {
  15647. to: this.id,
  15648. sid: this.sid,
  15649. broadcaster: this.broadcaster,
  15650. roomType: this.type,
  15651. type: messageType,
  15652. payload: payload,
  15653. prefix: webrtcSupport.prefix
  15654. };
  15655. this.logger.log('sending', messageType, message);
  15656. this.parent.emit('message', message);
  15657. };
  15658. // send via data channel
  15659. // returns true when message was sent and false if channel is not open
  15660. Peer.prototype.sendDirectly = function (channel, messageType, payload) {
  15661. var message = {
  15662. type: messageType,
  15663. payload: payload
  15664. };
  15665. this.logger.log('sending via datachannel', channel, messageType, message);
  15666. var dc = this.getDataChannel(channel);
  15667. if (dc.readyState != 'open') return false;
  15668. dc.send(JSON.stringify(message));
  15669. return true;
  15670. };
  15671. // Internal method registering handlers for a data channel and emitting events on the peer
  15672. Peer.prototype._observeDataChannel = function (channel) {
  15673. var self = this;
  15674. channel.onclose = this.emit.bind(this, 'channelClose', channel);
  15675. channel.onerror = this.emit.bind(this, 'channelError', channel);
  15676. channel.onmessage = function (event) {
  15677. self.emit('channelMessage', self, channel.label, JSON.parse(event.data), channel, event);
  15678. };
  15679. channel.onopen = this.emit.bind(this, 'channelOpen', channel);
  15680. };
  15681. // Fetch or create a data channel by the given name
  15682. Peer.prototype.getDataChannel = function (name, opts) {
  15683. if (!webrtcSupport.supportDataChannel) return this.emit('error', new Error('createDataChannel not supported'));
  15684. var channel = this.channels[name];
  15685. opts || (opts = {});
  15686. if (channel) return channel;
  15687. // if we don't have one by this label, create it
  15688. channel = this.channels[name] = this.pc.createDataChannel(name, opts);
  15689. this._observeDataChannel(channel);
  15690. return channel;
  15691. };
  15692. Peer.prototype.onIceCandidate = function (candidate) {
  15693. if (this.closed) return;
  15694. if (candidate) {
  15695. var pcConfig = this.parent.config.peerConnectionConfig;
  15696. if (webrtcSupport.prefix === 'moz' && pcConfig && pcConfig.iceTransports &&
  15697. candidate.candidate && candidate.candidate.candidate &&
  15698. candidate.candidate.candidate.indexOf(pcConfig.iceTransports) < 0) {
  15699. this.logger.log('Ignoring ice candidate not matching pcConfig iceTransports type: ', pcConfig.iceTransports);
  15700. } else {
  15701. this.send('candidate', candidate);
  15702. }
  15703. } else {
  15704. this.logger.log("End of candidates.");
  15705. }
  15706. };
  15707. Peer.prototype.start = function () {
  15708. var self = this;
  15709. // well, the webrtc api requires that we either
  15710. // a) create a datachannel a priori
  15711. // b) do a renegotiation later to add the SCTP m-line
  15712. // Let's do (a) first...
  15713. if (this.enableDataChannels) {
  15714. this.getDataChannel('simplewebrtc');
  15715. }
  15716. this.pc.offer(this.receiveMedia, function (err, sessionDescription) {
  15717. //self.send('offer', sessionDescription);
  15718. });
  15719. };
  15720. Peer.prototype.icerestart = function () {
  15721. var constraints = this.receiveMedia;
  15722. constraints.mandatory.IceRestart = true;
  15723. this.pc.offer(constraints, function (err, success) { });
  15724. };
  15725. Peer.prototype.end = function () {
  15726. if (this.closed) return;
  15727. this.pc.close();
  15728. this.handleStreamRemoved();
  15729. };
  15730. Peer.prototype.handleRemoteStreamAdded = function (event) {
  15731. var self = this;
  15732. if (this.stream) {
  15733. this.logger.warn('Already have a remote stream');
  15734. } else {
  15735. this.stream = event.stream;
  15736. this.stream.getTracks().forEach(function (track) {
  15737. track.addEventListener('ended', function () {
  15738. if (isAllTracksEnded(self.stream)) {
  15739. self.end();
  15740. }
  15741. });
  15742. });
  15743. this.parent.emit('peerStreamAdded', this);
  15744. }
  15745. };
  15746. Peer.prototype.handleStreamRemoved = function () {
  15747. var peerIndex = this.parent.peers.indexOf(this);
  15748. if (peerIndex > -1) {
  15749. this.parent.peers.splice(peerIndex, 1);
  15750. this.closed = true;
  15751. this.parent.emit('peerStreamRemoved', this);
  15752. }
  15753. };
  15754. Peer.prototype.handleDataChannelAdded = function (channel) {
  15755. this.channels[channel.label] = channel;
  15756. this._observeDataChannel(channel);
  15757. };
  15758. Peer.prototype.sendFile = function (file) {
  15759. var sender = new FileTransfer.Sender();
  15760. var dc = this.getDataChannel('filetransfer' + (new Date()).getTime(), {
  15761. protocol: INBAND_FILETRANSFER_V1
  15762. });
  15763. // override onopen
  15764. dc.onopen = function () {
  15765. dc.send(JSON.stringify({
  15766. size: file.size,
  15767. name: file.name
  15768. }));
  15769. sender.send(file, dc);
  15770. };
  15771. // override onclose
  15772. dc.onclose = function () {
  15773. console.log('sender received transfer');
  15774. sender.emit('complete');
  15775. };
  15776. return sender;
  15777. };
  15778. module.exports = Peer;
  15779. },{"filetransfer":26,"rtcpeerconnection":56,"util":89,"webrtcsupport":99,"wildemitter":100}],103:[function(require,module,exports){
  15780. var WebRTC = require('./webrtc');
  15781. var WildEmitter = require('wildemitter');
  15782. var webrtcSupport = require('webrtcsupport');
  15783. var attachMediaStream = require('attachmediastream');
  15784. var mockconsole = require('mockconsole');
  15785. var SocketIoConnection = require('./socketioconnection');
  15786. function SimpleWebRTC(opts) {
  15787. var self = this;
  15788. var options = opts || {};
  15789. var config = this.config = {
  15790. url: 'https://sandbox.simplewebrtc.com:443/',
  15791. socketio: {/* 'force new connection':true*/},
  15792. connection: null,
  15793. debug: false,
  15794. localVideoEl: '',
  15795. remoteVideosEl: '',
  15796. enableDataChannels: true,
  15797. autoRequestMedia: false,
  15798. autoRemoveVideos: true,
  15799. adjustPeerVolume: false,
  15800. peerVolumeWhenSpeaking: 0.25,
  15801. media: {
  15802. video: true,
  15803. audio: true
  15804. },
  15805. receiveMedia: {
  15806. offerToReceiveAudio: 1,
  15807. offerToReceiveVideo: 1
  15808. },
  15809. localVideo: {
  15810. autoplay: true,
  15811. mirror: true,
  15812. muted: true
  15813. }
  15814. };
  15815. var item, connection;
  15816. // We also allow a 'logger' option. It can be any object that implements
  15817. // log, warn, and error methods.
  15818. // We log nothing by default, following "the rule of silence":
  15819. // http://www.linfo.org/rule_of_silence.html
  15820. this.logger = function () {
  15821. // we assume that if you're in debug mode and you didn't
  15822. // pass in a logger, you actually want to log as much as
  15823. // possible.
  15824. if (opts.debug) {
  15825. return opts.logger || console;
  15826. } else {
  15827. // or we'll use your logger which should have its own logic
  15828. // for output. Or we'll return the no-op.
  15829. return opts.logger || mockconsole;
  15830. }
  15831. }();
  15832. // set our config from options
  15833. for (item in options) {
  15834. if (options.hasOwnProperty(item)) {
  15835. this.config[item] = options[item];
  15836. }
  15837. }
  15838. // attach detected support for convenience
  15839. this.capabilities = webrtcSupport;
  15840. // call WildEmitter constructor
  15841. WildEmitter.call(this);
  15842. // create default SocketIoConnection if it's not passed in
  15843. if (this.config.connection === null) {
  15844. connection = this.connection = new SocketIoConnection(this.config);
  15845. } else {
  15846. connection = this.connection = this.config.connection;
  15847. }
  15848. connection.on('connect', function () {
  15849. self.emit('connectionReady', connection.getSessionid());
  15850. self.sessionReady = true;
  15851. self.testReadiness();
  15852. });
  15853. connection.on('message', function (message) {
  15854. var peers = self.webrtc.getPeers(message.from, message.roomType);
  15855. var peer;
  15856. if (message.type === 'offer') {
  15857. if (peers.length) {
  15858. peers.forEach(function (p) {
  15859. if (p.sid == message.sid) peer = p;
  15860. });
  15861. //if (!peer) peer = peers[0]; // fallback for old protocol versions
  15862. }
  15863. if (!peer) {
  15864. peer = self.webrtc.createPeer({
  15865. id: message.from,
  15866. sid: message.sid,
  15867. type: message.roomType,
  15868. enableDataChannels: self.config.enableDataChannels && message.roomType !== 'screen',
  15869. sharemyscreen: message.roomType === 'screen' && !message.broadcaster,
  15870. broadcaster: message.roomType === 'screen' && !message.broadcaster ? self.connection.getSessionid() : null
  15871. });
  15872. self.emit('createdPeer', peer);
  15873. }
  15874. peer.handleMessage(message);
  15875. } else if (peers.length) {
  15876. peers.forEach(function (peer) {
  15877. if (message.sid) {
  15878. if (peer.sid === message.sid) {
  15879. peer.handleMessage(message);
  15880. }
  15881. } else {
  15882. peer.handleMessage(message);
  15883. }
  15884. });
  15885. }
  15886. });
  15887. connection.on('remove', function (room) {
  15888. if (room.id !== self.connection.getSessionid()) {
  15889. self.webrtc.removePeers(room.id, room.type);
  15890. }
  15891. });
  15892. // instantiate our main WebRTC helper
  15893. // using same logger from logic here
  15894. opts.logger = this.logger;
  15895. opts.debug = false;
  15896. this.webrtc = new WebRTC(opts);
  15897. // attach a few methods from underlying lib to simple.
  15898. ['mute', 'unmute', 'pauseVideo', 'resumeVideo', 'pause', 'resume', 'sendToAll', 'sendDirectlyToAll', 'getPeers'].forEach(function (method) {
  15899. self[method] = self.webrtc[method].bind(self.webrtc);
  15900. });
  15901. // proxy events from WebRTC
  15902. this.webrtc.on('*', function () {
  15903. self.emit.apply(self, arguments);
  15904. });
  15905. // log all events in debug mode
  15906. if (config.debug) {
  15907. this.on('*', this.logger.log.bind(this.logger, 'SimpleWebRTC event:'));
  15908. }
  15909. // check for readiness
  15910. this.webrtc.on('localStream', function () {
  15911. self.testReadiness();
  15912. });
  15913. this.webrtc.on('message', function (payload) {
  15914. self.connection.emit('message', payload);
  15915. });
  15916. this.webrtc.on('peerStreamAdded', this.handlePeerStreamAdded.bind(this));
  15917. this.webrtc.on('peerStreamRemoved', this.handlePeerStreamRemoved.bind(this));
  15918. // echo cancellation attempts
  15919. if (this.config.adjustPeerVolume) {
  15920. this.webrtc.on('speaking', this.setVolumeForAll.bind(this, this.config.peerVolumeWhenSpeaking));
  15921. this.webrtc.on('stoppedSpeaking', this.setVolumeForAll.bind(this, 1));
  15922. }
  15923. connection.on('stunservers', function (args) {
  15924. // resets/overrides the config
  15925. self.webrtc.config.peerConnectionConfig.iceServers = args;
  15926. self.emit('stunservers', args);
  15927. });
  15928. connection.on('turnservers', function (args) {
  15929. // appends to the config
  15930. self.webrtc.config.peerConnectionConfig.iceServers = self.webrtc.config.peerConnectionConfig.iceServers.concat(args);
  15931. self.emit('turnservers', args);
  15932. });
  15933. this.webrtc.on('iceFailed', function (peer) {
  15934. // local ice failure
  15935. });
  15936. this.webrtc.on('connectivityError', function (peer) {
  15937. // remote ice failure
  15938. });
  15939. // sending mute/unmute to all peers
  15940. this.webrtc.on('audioOn', function () {
  15941. self.webrtc.sendToAll('unmute', {name: 'audio'});
  15942. });
  15943. this.webrtc.on('audioOff', function () {
  15944. self.webrtc.sendToAll('mute', {name: 'audio'});
  15945. });
  15946. this.webrtc.on('videoOn', function () {
  15947. self.webrtc.sendToAll('unmute', {name: 'video'});
  15948. });
  15949. this.webrtc.on('videoOff', function () {
  15950. self.webrtc.sendToAll('mute', {name: 'video'});
  15951. });
  15952. // screensharing events
  15953. this.webrtc.on('localScreen', function (stream) {
  15954. var item,
  15955. el = document.createElement('video'),
  15956. container = self.getRemoteVideoContainer();
  15957. el.oncontextmenu = function () { return false; };
  15958. el.id = 'localScreen';
  15959. attachMediaStream(stream, el);
  15960. if (container) {
  15961. container.appendChild(el);
  15962. }
  15963. self.emit('localScreenAdded', el);
  15964. self.connection.emit('shareScreen');
  15965. self.webrtc.peers.forEach(function (existingPeer) {
  15966. var peer;
  15967. if (existingPeer.type === 'video') {
  15968. peer = self.webrtc.createPeer({
  15969. id: existingPeer.id,
  15970. type: 'screen',
  15971. sharemyscreen: true,
  15972. enableDataChannels: false,
  15973. receiveMedia: {
  15974. offerToReceiveAudio: 0,
  15975. offerToReceiveVideo: 0
  15976. },
  15977. broadcaster: self.connection.getSessionid(),
  15978. });
  15979. self.emit('createdPeer', peer);
  15980. peer.start();
  15981. }
  15982. });
  15983. });
  15984. this.webrtc.on('localScreenStopped', function (stream) {
  15985. if (self.getLocalScreen()) {
  15986. self.stopScreenShare();
  15987. }
  15988. /*
  15989. self.connection.emit('unshareScreen');
  15990. self.webrtc.peers.forEach(function (peer) {
  15991. if (peer.sharemyscreen) {
  15992. peer.end();
  15993. }
  15994. });
  15995. */
  15996. });
  15997. this.webrtc.on('channelMessage', function (peer, label, data) {
  15998. if (data.type == 'volume') {
  15999. self.emit('remoteVolumeChange', peer, data.volume);
  16000. }
  16001. });
  16002. if (this.config.autoRequestMedia) this.startLocalVideo();
  16003. }
  16004. SimpleWebRTC.prototype = Object.create(WildEmitter.prototype, {
  16005. constructor: {
  16006. value: SimpleWebRTC
  16007. }
  16008. });
  16009. SimpleWebRTC.prototype.leaveRoom = function () {
  16010. if (this.roomName) {
  16011. this.connection.emit('leave');
  16012. while (this.webrtc.peers.length) {
  16013. this.webrtc.peers[0].end();
  16014. }
  16015. if (this.getLocalScreen()) {
  16016. this.stopScreenShare();
  16017. }
  16018. this.emit('leftRoom', this.roomName);
  16019. this.roomName = undefined;
  16020. }
  16021. };
  16022. SimpleWebRTC.prototype.disconnect = function () {
  16023. this.connection.disconnect();
  16024. delete this.connection;
  16025. };
  16026. SimpleWebRTC.prototype.handlePeerStreamAdded = function (peer) {
  16027. var self = this;
  16028. var container = this.getRemoteVideoContainer();
  16029. var video = attachMediaStream(peer.stream);
  16030. // store video element as part of peer for easy removal
  16031. peer.videoEl = video;
  16032. video.id = this.getDomId(peer);
  16033. if (container) container.appendChild(video);
  16034. this.emit('videoAdded', video, peer);
  16035. // send our mute status to new peer if we're muted
  16036. // currently called with a small delay because it arrives before
  16037. // the video element is created otherwise (which happens after
  16038. // the async setRemoteDescription-createAnswer)
  16039. window.setTimeout(function () {
  16040. if (!self.webrtc.isAudioEnabled()) {
  16041. peer.send('mute', {name: 'audio'});
  16042. }
  16043. if (!self.webrtc.isVideoEnabled()) {
  16044. peer.send('mute', {name: 'video'});
  16045. }
  16046. }, 250);
  16047. };
  16048. SimpleWebRTC.prototype.handlePeerStreamRemoved = function (peer) {
  16049. var container = this.getRemoteVideoContainer();
  16050. var videoEl = peer.videoEl;
  16051. if (this.config.autoRemoveVideos && container && videoEl) {
  16052. container.removeChild(videoEl);
  16053. }
  16054. if (videoEl) this.emit('videoRemoved', videoEl, peer);
  16055. };
  16056. SimpleWebRTC.prototype.getDomId = function (peer) {
  16057. return [peer.id, peer.type, peer.broadcaster ? 'broadcasting' : 'incoming'].join('_');
  16058. };
  16059. // set volume on video tag for all peers takse a value between 0 and 1
  16060. SimpleWebRTC.prototype.setVolumeForAll = function (volume) {
  16061. this.webrtc.peers.forEach(function (peer) {
  16062. if (peer.videoEl) peer.videoEl.volume = volume;
  16063. });
  16064. };
  16065. SimpleWebRTC.prototype.joinRoom = function (name, cb) {
  16066. var self = this;
  16067. this.roomName = name;
  16068. this.connection.emit('join', name, function (err, roomDescription) {
  16069. console.log('join CB', err, roomDescription);
  16070. if (err) {
  16071. self.emit('error', err);
  16072. } else {
  16073. var id,
  16074. client,
  16075. type,
  16076. peer;
  16077. for (id in roomDescription.clients) {
  16078. client = roomDescription.clients[id];
  16079. for (type in client) {
  16080. if (client[type]) {
  16081. peer = self.webrtc.createPeer({
  16082. id: id,
  16083. type: type,
  16084. enableDataChannels: self.config.enableDataChannels && type !== 'screen',
  16085. receiveMedia: {
  16086. offerToReceiveAudio: type !== 'screen' && self.config.receiveMedia.offerToReceiveAudio ? 1 : 0,
  16087. offerToReceiveVideo: self.config.receiveMedia.offerToReceiveVideo
  16088. }
  16089. });
  16090. self.emit('createdPeer', peer);
  16091. peer.start();
  16092. }
  16093. }
  16094. }
  16095. }
  16096. if (cb) cb(err, roomDescription);
  16097. self.emit('joinedRoom', name);
  16098. });
  16099. };
  16100. SimpleWebRTC.prototype.getEl = function (idOrEl) {
  16101. if (typeof idOrEl === 'string') {
  16102. return document.getElementById(idOrEl);
  16103. } else {
  16104. return idOrEl;
  16105. }
  16106. };
  16107. SimpleWebRTC.prototype.startLocalVideo = function () {
  16108. var self = this;
  16109. this.webrtc.startLocalMedia(this.config.media, function (err, stream) {
  16110. if (err) {
  16111. self.emit('localMediaError', err);
  16112. } else {
  16113. attachMediaStream(stream, self.getLocalVideoContainer(), self.config.localVideo);
  16114. }
  16115. });
  16116. };
  16117. SimpleWebRTC.prototype.stopLocalVideo = function () {
  16118. this.webrtc.stopLocalMedia();
  16119. };
  16120. // this accepts either element ID or element
  16121. // and either the video tag itself or a container
  16122. // that will be used to put the video tag into.
  16123. SimpleWebRTC.prototype.getLocalVideoContainer = function () {
  16124. var el = this.getEl(this.config.localVideoEl);
  16125. if (el && el.tagName === 'VIDEO') {
  16126. el.oncontextmenu = function () { return false; };
  16127. return el;
  16128. } else if (el) {
  16129. var video = document.createElement('video');
  16130. video.oncontextmenu = function () { return false; };
  16131. el.appendChild(video);
  16132. return video;
  16133. } else {
  16134. return;
  16135. }
  16136. };
  16137. SimpleWebRTC.prototype.getRemoteVideoContainer = function () {
  16138. return this.getEl(this.config.remoteVideosEl);
  16139. };
  16140. SimpleWebRTC.prototype.shareScreen = function (cb) {
  16141. this.webrtc.startScreenShare(cb);
  16142. };
  16143. SimpleWebRTC.prototype.getLocalScreen = function () {
  16144. return this.webrtc.localScreen;
  16145. };
  16146. SimpleWebRTC.prototype.stopScreenShare = function () {
  16147. this.connection.emit('unshareScreen');
  16148. var videoEl = document.getElementById('localScreen');
  16149. var container = this.getRemoteVideoContainer();
  16150. if (this.config.autoRemoveVideos && container && videoEl) {
  16151. container.removeChild(videoEl);
  16152. }
  16153. // a hack to emit the event the removes the video
  16154. // element that we want
  16155. if (videoEl) {
  16156. this.emit('videoRemoved', videoEl);
  16157. }
  16158. if (this.getLocalScreen()) {
  16159. this.webrtc.stopScreenShare();
  16160. }
  16161. this.webrtc.peers.forEach(function (peer) {
  16162. if (peer.broadcaster) {
  16163. peer.end();
  16164. }
  16165. });
  16166. };
  16167. SimpleWebRTC.prototype.testReadiness = function () {
  16168. var self = this;
  16169. if (this.sessionReady) {
  16170. if (!this.config.media.video && !this.config.media.audio) {
  16171. self.emit('readyToCall', self.connection.getSessionid());
  16172. } else if (this.webrtc.localStreams.length > 0) {
  16173. self.emit('readyToCall', self.connection.getSessionid());
  16174. }
  16175. }
  16176. };
  16177. SimpleWebRTC.prototype.createRoom = function (name, cb) {
  16178. this.roomName = name;
  16179. if (arguments.length === 2) {
  16180. this.connection.emit('create', name, cb);
  16181. } else {
  16182. this.connection.emit('create', name);
  16183. }
  16184. };
  16185. SimpleWebRTC.prototype.sendFile = function () {
  16186. if (!webrtcSupport.dataChannel) {
  16187. return this.emit('error', new Error('DataChannelNotSupported'));
  16188. }
  16189. };
  16190. module.exports = SimpleWebRTC;
  16191. },{"./socketioconnection":104,"./webrtc":105,"attachmediastream":3,"mockconsole":50,"webrtcsupport":99,"wildemitter":100}],104:[function(require,module,exports){
  16192. var io = require('socket.io-client');
  16193. function SocketIoConnection(config) {
  16194. this.connection = io.connect(config.url, config.socketio);
  16195. }
  16196. SocketIoConnection.prototype.on = function (ev, fn) {
  16197. this.connection.on(ev, fn);
  16198. };
  16199. SocketIoConnection.prototype.emit = function () {
  16200. this.connection.emit.apply(this.connection, arguments);
  16201. };
  16202. SocketIoConnection.prototype.getSessionid = function () {
  16203. return this.connection.id;
  16204. };
  16205. SocketIoConnection.prototype.disconnect = function () {
  16206. return this.connection.disconnect();
  16207. };
  16208. module.exports = SocketIoConnection;
  16209. },{"socket.io-client":63}],105:[function(require,module,exports){
  16210. var util = require('util');
  16211. var webrtcSupport = require('webrtcsupport');
  16212. var mockconsole = require('mockconsole');
  16213. var localMedia = require('localmedia');
  16214. var Peer = require('./peer');
  16215. function WebRTC(opts) {
  16216. var self = this;
  16217. var options = opts || {};
  16218. var config = this.config = {
  16219. debug: false,
  16220. // makes the entire PC config overridable
  16221. peerConnectionConfig: {
  16222. iceServers: [{'urls': 'stun:stun.l.google.com:19302'}]
  16223. },
  16224. peerConnectionConstraints: {
  16225. optional: []
  16226. },
  16227. receiveMedia: {
  16228. offerToReceiveAudio: 1,
  16229. offerToReceiveVideo: 1
  16230. },
  16231. enableDataChannels: true
  16232. };
  16233. var item;
  16234. // We also allow a 'logger' option. It can be any object that implements
  16235. // log, warn, and error methods.
  16236. // We log nothing by default, following "the rule of silence":
  16237. // http://www.linfo.org/rule_of_silence.html
  16238. this.logger = function () {
  16239. // we assume that if you're in debug mode and you didn't
  16240. // pass in a logger, you actually want to log as much as
  16241. // possible.
  16242. if (opts.debug) {
  16243. return opts.logger || console;
  16244. } else {
  16245. // or we'll use your logger which should have its own logic
  16246. // for output. Or we'll return the no-op.
  16247. return opts.logger || mockconsole;
  16248. }
  16249. }();
  16250. // set options
  16251. for (item in options) {
  16252. if (options.hasOwnProperty(item)) {
  16253. this.config[item] = options[item];
  16254. }
  16255. }
  16256. // check for support
  16257. if (!webrtcSupport.support) {
  16258. this.logger.error('Your browser doesn\'t seem to support WebRTC');
  16259. }
  16260. // where we'll store our peer connections
  16261. this.peers = [];
  16262. // call localMedia constructor
  16263. localMedia.call(this, this.config);
  16264. this.on('speaking', function () {
  16265. if (!self.hardMuted) {
  16266. // FIXME: should use sendDirectlyToAll, but currently has different semantics wrt payload
  16267. self.peers.forEach(function (peer) {
  16268. if (peer.enableDataChannels) {
  16269. var dc = peer.getDataChannel('hark');
  16270. if (dc.readyState != 'open') return;
  16271. dc.send(JSON.stringify({type: 'speaking'}));
  16272. }
  16273. });
  16274. }
  16275. });
  16276. this.on('stoppedSpeaking', function () {
  16277. if (!self.hardMuted) {
  16278. // FIXME: should use sendDirectlyToAll, but currently has different semantics wrt payload
  16279. self.peers.forEach(function (peer) {
  16280. if (peer.enableDataChannels) {
  16281. var dc = peer.getDataChannel('hark');
  16282. if (dc.readyState != 'open') return;
  16283. dc.send(JSON.stringify({type: 'stoppedSpeaking'}));
  16284. }
  16285. });
  16286. }
  16287. });
  16288. this.on('volumeChange', function (volume, treshold) {
  16289. if (!self.hardMuted) {
  16290. // FIXME: should use sendDirectlyToAll, but currently has different semantics wrt payload
  16291. self.peers.forEach(function (peer) {
  16292. if (peer.enableDataChannels) {
  16293. var dc = peer.getDataChannel('hark');
  16294. if (dc.readyState != 'open') return;
  16295. dc.send(JSON.stringify({type: 'volume', volume: volume }));
  16296. }
  16297. });
  16298. }
  16299. });
  16300. // log events in debug mode
  16301. if (this.config.debug) {
  16302. this.on('*', function (event, val1, val2) {
  16303. var logger;
  16304. // if you didn't pass in a logger and you explicitly turning on debug
  16305. // we're just going to assume you're wanting log output with console
  16306. if (self.config.logger === mockconsole) {
  16307. logger = console;
  16308. } else {
  16309. logger = self.logger;
  16310. }
  16311. logger.log('event:', event, val1, val2);
  16312. });
  16313. }
  16314. }
  16315. util.inherits(WebRTC, localMedia);
  16316. WebRTC.prototype.createPeer = function (opts) {
  16317. var peer;
  16318. opts.parent = this;
  16319. peer = new Peer(opts);
  16320. this.peers.push(peer);
  16321. return peer;
  16322. };
  16323. // removes peers
  16324. WebRTC.prototype.removePeers = function (id, type) {
  16325. this.getPeers(id, type).forEach(function (peer) {
  16326. peer.end();
  16327. });
  16328. };
  16329. // fetches all Peer objects by session id and/or type
  16330. WebRTC.prototype.getPeers = function (sessionId, type) {
  16331. return this.peers.filter(function (peer) {
  16332. return (!sessionId || peer.id === sessionId) && (!type || peer.type === type);
  16333. });
  16334. };
  16335. // sends message to all
  16336. WebRTC.prototype.sendToAll = function (message, payload) {
  16337. this.peers.forEach(function (peer) {
  16338. peer.send(message, payload);
  16339. });
  16340. };
  16341. // sends message to all using a datachannel
  16342. // only sends to anyone who has an open datachannel
  16343. WebRTC.prototype.sendDirectlyToAll = function (channel, message, payload) {
  16344. this.peers.forEach(function (peer) {
  16345. if (peer.enableDataChannels) {
  16346. peer.sendDirectly(channel, message, payload);
  16347. }
  16348. });
  16349. };
  16350. module.exports = WebRTC;
  16351. },{"./peer":102,"localmedia":46,"mockconsole":50,"util":89,"webrtcsupport":99}]},{},[103])(103)
  16352. });